hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fb063781520cb0a4cca149aafebc08d9057c0538
| 2,161 |
cpp
|
C++
|
src/vkex/QueryPool.cpp
|
apazylbe/PorQue4K
|
209ba90a35f05df0be68df586c9e184183ed8263
|
[
"Apache-2.0"
] | 15 |
2020-06-12T01:40:34.000Z
|
2022-03-16T21:52:46.000Z
|
src/vkex/QueryPool.cpp
|
apazylbe/PorQue4K
|
209ba90a35f05df0be68df586c9e184183ed8263
|
[
"Apache-2.0"
] | 4 |
2020-06-12T23:57:52.000Z
|
2020-06-24T19:19:16.000Z
|
src/vkex/QueryPool.cpp
|
apazylbe/PorQue4K
|
209ba90a35f05df0be68df586c9e184183ed8263
|
[
"Apache-2.0"
] | 3 |
2020-06-12T15:02:13.000Z
|
2020-07-05T17:34:20.000Z
|
/*
Copyright 2018-2019 Google Inc.
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 "vkex/QueryPool.h"
#include "vkex/Device.h"
#include "vkex/ToString.h"
namespace vkex {
// =================================================================================================
// QueryPool
// =================================================================================================
CQueryPool::CQueryPool()
{
}
CQueryPool::~CQueryPool()
{
}
vkex::Result CQueryPool::InternalCreate(
const vkex::QueryPoolCreateInfo& create_info,
const VkAllocationCallbacks* p_allocator
)
{
// Copy create info
m_create_info = create_info;
// Create Vulkan sampler
{
// Create info
m_vk_create_info = { VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO };
m_vk_create_info.queryType = m_create_info.query_type;
m_vk_create_info.queryCount = m_create_info.query_count;
m_vk_create_info.pipelineStatistics = m_create_info.pipeline_statistics.flags;
// Create Vulkan sampler
VkResult vk_result = InvalidValue<VkResult>::Value;
VKEX_VULKAN_RESULT_CALL(
vk_result,
vkex::CreateQueryPool(
*m_device,
&m_vk_create_info,
p_allocator,
&m_vk_object)
);
if (vk_result != VK_SUCCESS) {
return vkex::Result(vk_result);
}
}
return vkex::Result::Success;
}
vkex::Result CQueryPool::InternalDestroy(const VkAllocationCallbacks* p_allocator)
{
if (m_vk_object != VK_NULL_HANDLE) {
vkex::DestroyQueryPool(
*m_device,
m_vk_object,
p_allocator);
m_vk_object = VK_NULL_HANDLE;
}
return vkex::Result::Success;
}
} // namespace vkex
| 27.0125 | 100 | 0.648774 |
apazylbe
|
fb0918f6b14b61ff1c285851a2d06dc0989cd7fc
| 5,709 |
cpp
|
C++
|
engine/Ecs/Systems/CheckCollisionsSystem.cpp
|
ledocool/snail_engine
|
0114a62dbecbbe58348fbe7083d9182bc1bd8c3c
|
[
"Apache-2.0"
] | null | null | null |
engine/Ecs/Systems/CheckCollisionsSystem.cpp
|
ledocool/snail_engine
|
0114a62dbecbbe58348fbe7083d9182bc1bd8c3c
|
[
"Apache-2.0"
] | null | null | null |
engine/Ecs/Systems/CheckCollisionsSystem.cpp
|
ledocool/snail_engine
|
0114a62dbecbbe58348fbe7083d9182bc1bd8c3c
|
[
"Apache-2.0"
] | 1 |
2018-08-11T14:31:27.000Z
|
2018-08-11T14:31:27.000Z
|
/*
* Copyright 2018 LedoCool.
*
* 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.
*/
/*
* File: CheckCollisions.cpp
* Author: LedoCool
*
* Created on December 24, 2018, 8:35 PM
*/
#include "CheckCollisionsSystem.h"
#include "engine/Etc/Rect.h"
#include "engine/Etc/Vector2.h"
#include "engine/Game/Camera.h"
#include "engine/Ecs/Components/IncludeComponents.h"
CheckCollisionsSystem::CheckCollisionsSystem()
{
}
CheckCollisionsSystem::~ CheckCollisionsSystem()
{
}
void CheckCollisionsSystem::Execute(Uint32 dt, std::shared_ptr<GameState>& gameState)
{
gameState->collidingEntitites.clear();
BuildBinaryTree(gameState);
for(auto entity : gameState->map->GetEntities())
{
auto position = std::dynamic_pointer_cast<Position>(entity->GetComponent(ComponentTypes::POSITION).lock());
auto velocity = std::dynamic_pointer_cast<Velocity>(entity->GetComponent(ComponentTypes::VELOCITY).lock());
auto acceleration = std::dynamic_pointer_cast<Acceleration>(entity->GetComponent(ComponentTypes::ACCELERATION).lock());
auto size = std::dynamic_pointer_cast<Size>(entity->GetComponent(ComponentTypes::SIZE).lock());
if(!acceleration)
{
acceleration = std::make_shared<Acceleration>(Vector2<float>(0.f, 0.f), 0.f);
}
if(!velocity)
{
velocity = std::make_shared<Velocity>(Vector2<float>(0.f, 0.f), 0.f);
}
if(!(position && size))
{
continue;
}
float halfSize = size->size() / 2.f;
Rect<float> boundingRect(
- halfSize,
halfSize,
- halfSize,
halfSize
);
for(auto weakPossiblyCollidingEntity : gameState->collisionTree->GetObjects(boundingRect))
{
auto collider = weakPossiblyCollidingEntity.lock();
if(!collider || collider == entity)
{
continue;
}
auto colliderPosition = std::dynamic_pointer_cast<Position>(collider->GetComponent(ComponentTypes::POSITION).lock());
auto colliderVelocity = std::dynamic_pointer_cast<Velocity>(collider->GetComponent(ComponentTypes::VELOCITY).lock());
auto coliderAcceleration = std::dynamic_pointer_cast<Acceleration>(collider->GetComponent(ComponentTypes::ACCELERATION).lock());
auto colliderSize = std::dynamic_pointer_cast<Size>(collider->GetComponent(ComponentTypes::SIZE).lock());
if(!coliderAcceleration)
{
coliderAcceleration = std::make_shared<Acceleration>(Vector2<float>(0.f, 0.f), 0.f);
}
if(!colliderVelocity)
{
colliderVelocity = std::make_shared<Velocity>(Vector2<float>(0.f, 0.f), 0.f);
}
if(!(colliderPosition && colliderSize))
{
continue;
}
float colliderHalfSize = colliderSize->size() / 2.f;
Rect<float> colliderBoundingRect(
- colliderHalfSize,
colliderHalfSize,
- colliderHalfSize,
colliderHalfSize
);
for(Uint32 iTime = 0; iTime < dt; iTime++)
{
Vector2<float> entity1_position = position->coords();
entity1_position += velocity->velocity() * iTime;
entity1_position += acceleration->vector() * iTime * iTime / 2.f;
Vector2<float> entity2_position = colliderPosition->coords();
entity2_position += colliderVelocity->velocity() * iTime;
entity2_position += coliderAcceleration->vector() * iTime * iTime / 2.f;
if(boundingRect.addPosition(entity1_position.x(), entity1_position.y()).CollidesWith(
colliderBoundingRect.addPosition(entity2_position.x(), entity2_position.y())))
{
Vector2<float> diff = entity1_position - entity2_position;
if(diff.Magnitude() <= colliderSize->size() + size->size())
{
std::weak_ptr<Entity> leftEntity(entity);
std::pair<std::weak_ptr<Entity>, std::weak_ptr<Entity> > collidingPair(leftEntity, weakPossiblyCollidingEntity);
gameState->collidingEntitites.push_back(collidingPair);
}
}
}
}
}
}
void CheckCollisionsSystem::BuildBinaryTree(std::shared_ptr<GameState>& gameState)
{
auto cameraCoordinates = gameState->camera->GetCoordinates();
auto screenSize = gameState->camera->GetScreenProportions();
Rect<float> chunk(
cameraCoordinates.x() - screenSize.x(),
cameraCoordinates.x() + screenSize.x(),
cameraCoordinates.y() - screenSize.y(),
cameraCoordinates.y() + screenSize.y()
);
gameState->collisionTree = std::make_shared<TreeRoot>();
gameState->collisionTree->BuildTree(chunk, gameState->map->GetEntities());
}
| 39.372414 | 140 | 0.600981 |
ledocool
|
fb0b4d728927159583f2446954c539d1e2a12de0
| 1,186 |
cpp
|
C++
|
II semester/programming-techniques/labovi/T4/Z1/main.cpp
|
ksaracevic1/etf-alles-1
|
0ab1ad83d00fafc69b38266edd875bce08c1fc9e
|
[
"Unlicense"
] | 14 |
2019-02-11T18:35:19.000Z
|
2022-03-26T09:54:47.000Z
|
II semester/programming-techniques/labovi/T4/Z1/main.cpp
|
ksaracevic1/etf-alles-1
|
0ab1ad83d00fafc69b38266edd875bce08c1fc9e
|
[
"Unlicense"
] | 4 |
2021-12-22T12:01:34.000Z
|
2021-12-22T12:01:35.000Z
|
II semester/programming-techniques/labovi/T4/Z1/main.cpp
|
ksaracevic1/etf-alles-1
|
0ab1ad83d00fafc69b38266edd875bce08c1fc9e
|
[
"Unlicense"
] | 18 |
2019-06-09T22:06:09.000Z
|
2022-02-15T07:17:15.000Z
|
/* TP 2016/2017 (Tutorijal 4, Zadatak 1)
Autotestovi by Eldar Kurtic, sva pitanja, sugestije i prijave gresaka javite na
mail ekurtic3@etf.unsa.ba
NAPOMENA: testovi ce biti konacni TEK pred pocetak tutorijala. Zbog toga pokrenite
testove za SVE zadatke na tutorijalu, da se ne bi desila situacija da neko uradi
zadatak ranije i prolazi mu npr. 5/5 testova a naknadno dodano jos 2 testa koja mu
padaju!
*/
#include <iostream>
#include <limits>
#include <cmath>
int Cifre(long long int n, int &c_min, int &c_max){
auto pomocna(n);
int brojac=0;
int min(9), max(0);
if(pomocna==0) {
c_min=0; c_max=0;
return brojac+1;
}
while(pomocna!=0){
int zadnja = std::fabs(pomocna % 10);
if(zadnja < min) min = zadnja;
if(zadnja > max) max = zadnja;
brojac++;
pomocna/=10;
}
c_min = min;
c_max = max;
return brojac;
}
int main ()
{
int a, b;
long long broj;
std::cout << "Unesite broj: ";
std::cin >> broj;
int cifre = Cifre(broj, a, b);
std::cout << "Broj " << broj << " ima " << cifre << " cifara, najveca je " << b << " a najmanja " << a << ".";
return 0;
}
| 23.72 | 114 | 0.600337 |
ksaracevic1
|
fb0c822bd4723386ad46a1d03f4d974cacbae84b
| 10,884 |
cpp
|
C++
|
export/windows/obj/src/openfl/display/GraphicsStroke.cpp
|
seanbashaw/frozenlight
|
47c540d30d63e946ea2dc787b4bb602cc9347d21
|
[
"MIT"
] | null | null | null |
export/windows/obj/src/openfl/display/GraphicsStroke.cpp
|
seanbashaw/frozenlight
|
47c540d30d63e946ea2dc787b4bb602cc9347d21
|
[
"MIT"
] | null | null | null |
export/windows/obj/src/openfl/display/GraphicsStroke.cpp
|
seanbashaw/frozenlight
|
47c540d30d63e946ea2dc787b4bb602cc9347d21
|
[
"MIT"
] | null | null | null |
// Generated by Haxe 3.4.7
#include <hxcpp.h>
#ifndef INCLUDED_95f339a1d026d52c
#define INCLUDED_95f339a1d026d52c
#include "hxMath.h"
#endif
#ifndef INCLUDED_openfl_display_GraphicsDataType
#include <openfl/display/GraphicsDataType.h>
#endif
#ifndef INCLUDED_openfl_display_GraphicsStroke
#include <openfl/display/GraphicsStroke.h>
#endif
#ifndef INCLUDED_openfl_display_IGraphicsData
#include <openfl/display/IGraphicsData.h>
#endif
#ifndef INCLUDED_openfl_display_IGraphicsFill
#include <openfl/display/IGraphicsFill.h>
#endif
#ifndef INCLUDED_openfl_display_IGraphicsStroke
#include <openfl/display/IGraphicsStroke.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_55614d7317440053_221_new,"openfl.display.GraphicsStroke","new",0x5684f03f,"openfl.display.GraphicsStroke.new","openfl/display/GraphicsStroke.hx",221,0x5e4870cf)
namespace openfl{
namespace display{
void GraphicsStroke_obj::__construct( ::Dynamic thickness,hx::Null< bool > __o_pixelHinting, ::Dynamic __o_scaleMode, ::Dynamic __o_caps, ::Dynamic __o_joints,hx::Null< Float > __o_miterLimit,::Dynamic fill){
bool pixelHinting = __o_pixelHinting.Default(false);
::Dynamic scaleMode = __o_scaleMode.Default(2);
::Dynamic caps = __o_caps.Default(0);
::Dynamic joints = __o_joints.Default(2);
Float miterLimit = __o_miterLimit.Default(3);
HX_STACKFRAME(&_hx_pos_55614d7317440053_221_new)
HXLINE( 223) if (hx::IsNull( thickness )) {
HXLINE( 223) thickness = ::Math_obj::NaN;
}
HXLINE( 225) this->caps = caps;
HXLINE( 226) this->fill = fill;
HXLINE( 227) this->joints = joints;
HXLINE( 228) this->miterLimit = miterLimit;
HXLINE( 229) this->pixelHinting = pixelHinting;
HXLINE( 230) this->scaleMode = scaleMode;
HXLINE( 231) this->thickness = thickness;
HXLINE( 232) this->_hx___graphicsDataType = ::openfl::display::GraphicsDataType_obj::STROKE_dyn();
}
Dynamic GraphicsStroke_obj::__CreateEmpty() { return new GraphicsStroke_obj; }
void *GraphicsStroke_obj::_hx_vtable = 0;
Dynamic GraphicsStroke_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< GraphicsStroke_obj > _hx_result = new GraphicsStroke_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4],inArgs[5],inArgs[6]);
return _hx_result;
}
bool GraphicsStroke_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x7fc28725;
}
static ::openfl::display::IGraphicsStroke_obj _hx_openfl_display_GraphicsStroke__hx_openfl_display_IGraphicsStroke= {
};
static ::openfl::display::IGraphicsData_obj _hx_openfl_display_GraphicsStroke__hx_openfl_display_IGraphicsData= {
};
void *GraphicsStroke_obj::_hx_getInterface(int inHash) {
switch(inHash) {
case (int)0xf088881a: return &_hx_openfl_display_GraphicsStroke__hx_openfl_display_IGraphicsStroke;
case (int)0xc177ee0c: return &_hx_openfl_display_GraphicsStroke__hx_openfl_display_IGraphicsData;
}
#ifdef HXCPP_SCRIPTABLE
return super::_hx_getInterface(inHash);
#else
return 0;
#endif
}
hx::ObjectPtr< GraphicsStroke_obj > GraphicsStroke_obj::__new( ::Dynamic thickness,hx::Null< bool > __o_pixelHinting, ::Dynamic __o_scaleMode, ::Dynamic __o_caps, ::Dynamic __o_joints,hx::Null< Float > __o_miterLimit,::Dynamic fill) {
hx::ObjectPtr< GraphicsStroke_obj > __this = new GraphicsStroke_obj();
__this->__construct(thickness,__o_pixelHinting,__o_scaleMode,__o_caps,__o_joints,__o_miterLimit,fill);
return __this;
}
hx::ObjectPtr< GraphicsStroke_obj > GraphicsStroke_obj::__alloc(hx::Ctx *_hx_ctx, ::Dynamic thickness,hx::Null< bool > __o_pixelHinting, ::Dynamic __o_scaleMode, ::Dynamic __o_caps, ::Dynamic __o_joints,hx::Null< Float > __o_miterLimit,::Dynamic fill) {
GraphicsStroke_obj *__this = (GraphicsStroke_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(GraphicsStroke_obj), true, "openfl.display.GraphicsStroke"));
*(void **)__this = GraphicsStroke_obj::_hx_vtable;
__this->__construct(thickness,__o_pixelHinting,__o_scaleMode,__o_caps,__o_joints,__o_miterLimit,fill);
return __this;
}
GraphicsStroke_obj::GraphicsStroke_obj()
{
}
void GraphicsStroke_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(GraphicsStroke);
HX_MARK_MEMBER_NAME(caps,"caps");
HX_MARK_MEMBER_NAME(fill,"fill");
HX_MARK_MEMBER_NAME(joints,"joints");
HX_MARK_MEMBER_NAME(miterLimit,"miterLimit");
HX_MARK_MEMBER_NAME(pixelHinting,"pixelHinting");
HX_MARK_MEMBER_NAME(scaleMode,"scaleMode");
HX_MARK_MEMBER_NAME(thickness,"thickness");
HX_MARK_MEMBER_NAME(_hx___graphicsDataType,"__graphicsDataType");
HX_MARK_END_CLASS();
}
void GraphicsStroke_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(caps,"caps");
HX_VISIT_MEMBER_NAME(fill,"fill");
HX_VISIT_MEMBER_NAME(joints,"joints");
HX_VISIT_MEMBER_NAME(miterLimit,"miterLimit");
HX_VISIT_MEMBER_NAME(pixelHinting,"pixelHinting");
HX_VISIT_MEMBER_NAME(scaleMode,"scaleMode");
HX_VISIT_MEMBER_NAME(thickness,"thickness");
HX_VISIT_MEMBER_NAME(_hx___graphicsDataType,"__graphicsDataType");
}
hx::Val GraphicsStroke_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"caps") ) { return hx::Val( caps ); }
if (HX_FIELD_EQ(inName,"fill") ) { return hx::Val( fill ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"joints") ) { return hx::Val( joints ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"scaleMode") ) { return hx::Val( scaleMode ); }
if (HX_FIELD_EQ(inName,"thickness") ) { return hx::Val( thickness ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"miterLimit") ) { return hx::Val( miterLimit ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"pixelHinting") ) { return hx::Val( pixelHinting ); }
break;
case 18:
if (HX_FIELD_EQ(inName,"__graphicsDataType") ) { return hx::Val( _hx___graphicsDataType ); }
}
return super::__Field(inName,inCallProp);
}
hx::Val GraphicsStroke_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"caps") ) { caps=inValue.Cast< ::Dynamic >(); return inValue; }
if (HX_FIELD_EQ(inName,"fill") ) { fill=inValue.Cast< ::Dynamic >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"joints") ) { joints=inValue.Cast< ::Dynamic >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"scaleMode") ) { scaleMode=inValue.Cast< ::Dynamic >(); return inValue; }
if (HX_FIELD_EQ(inName,"thickness") ) { thickness=inValue.Cast< Float >(); return inValue; }
break;
case 10:
if (HX_FIELD_EQ(inName,"miterLimit") ) { miterLimit=inValue.Cast< Float >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"pixelHinting") ) { pixelHinting=inValue.Cast< bool >(); return inValue; }
break;
case 18:
if (HX_FIELD_EQ(inName,"__graphicsDataType") ) { _hx___graphicsDataType=inValue.Cast< ::openfl::display::GraphicsDataType >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void GraphicsStroke_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("caps","\x21","\x1c","\xba","\x41"));
outFields->push(HX_HCSTRING("fill","\x83","\xce","\xbb","\x43"));
outFields->push(HX_HCSTRING("joints","\xe9","\xe7","\x09","\x91"));
outFields->push(HX_HCSTRING("miterLimit","\xf6","\x5c","\x6a","\x54"));
outFields->push(HX_HCSTRING("pixelHinting","\xd5","\x9b","\xfb","\x6c"));
outFields->push(HX_HCSTRING("scaleMode","\x0d","\xdb","\xd3","\x2b"));
outFields->push(HX_HCSTRING("thickness","\x74","\xf1","\x66","\x5a"));
outFields->push(HX_HCSTRING("__graphicsDataType","\x0f","\x5d","\x4d","\x46"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo GraphicsStroke_obj_sMemberStorageInfo[] = {
{hx::fsObject /*Dynamic*/ ,(int)offsetof(GraphicsStroke_obj,caps),HX_HCSTRING("caps","\x21","\x1c","\xba","\x41")},
{hx::fsObject /*::openfl::display::IGraphicsFill*/ ,(int)offsetof(GraphicsStroke_obj,fill),HX_HCSTRING("fill","\x83","\xce","\xbb","\x43")},
{hx::fsObject /*Dynamic*/ ,(int)offsetof(GraphicsStroke_obj,joints),HX_HCSTRING("joints","\xe9","\xe7","\x09","\x91")},
{hx::fsFloat,(int)offsetof(GraphicsStroke_obj,miterLimit),HX_HCSTRING("miterLimit","\xf6","\x5c","\x6a","\x54")},
{hx::fsBool,(int)offsetof(GraphicsStroke_obj,pixelHinting),HX_HCSTRING("pixelHinting","\xd5","\x9b","\xfb","\x6c")},
{hx::fsObject /*Dynamic*/ ,(int)offsetof(GraphicsStroke_obj,scaleMode),HX_HCSTRING("scaleMode","\x0d","\xdb","\xd3","\x2b")},
{hx::fsFloat,(int)offsetof(GraphicsStroke_obj,thickness),HX_HCSTRING("thickness","\x74","\xf1","\x66","\x5a")},
{hx::fsObject /*::openfl::display::GraphicsDataType*/ ,(int)offsetof(GraphicsStroke_obj,_hx___graphicsDataType),HX_HCSTRING("__graphicsDataType","\x0f","\x5d","\x4d","\x46")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *GraphicsStroke_obj_sStaticStorageInfo = 0;
#endif
static ::String GraphicsStroke_obj_sMemberFields[] = {
HX_HCSTRING("caps","\x21","\x1c","\xba","\x41"),
HX_HCSTRING("fill","\x83","\xce","\xbb","\x43"),
HX_HCSTRING("joints","\xe9","\xe7","\x09","\x91"),
HX_HCSTRING("miterLimit","\xf6","\x5c","\x6a","\x54"),
HX_HCSTRING("pixelHinting","\xd5","\x9b","\xfb","\x6c"),
HX_HCSTRING("scaleMode","\x0d","\xdb","\xd3","\x2b"),
HX_HCSTRING("thickness","\x74","\xf1","\x66","\x5a"),
HX_HCSTRING("__graphicsDataType","\x0f","\x5d","\x4d","\x46"),
::String(null()) };
static void GraphicsStroke_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(GraphicsStroke_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void GraphicsStroke_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(GraphicsStroke_obj::__mClass,"__mClass");
};
#endif
hx::Class GraphicsStroke_obj::__mClass;
void GraphicsStroke_obj::__register()
{
hx::Object *dummy = new GraphicsStroke_obj;
GraphicsStroke_obj::_hx_vtable = *(void **)dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("openfl.display.GraphicsStroke","\xcd","\x64","\xa2","\xa3");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = GraphicsStroke_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(GraphicsStroke_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< GraphicsStroke_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = GraphicsStroke_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = GraphicsStroke_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = GraphicsStroke_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace openfl
} // end namespace display
| 42.186047 | 255 | 0.745774 |
seanbashaw
|
fb113e8a751c34140e126541462a2fd262c1b6fb
| 2,805 |
cc
|
C++
|
components/service/ucloud/iot/src/model/ListProductByTagsResult.cc
|
wanguojian/AliOS-Things
|
47fce29d4dd39d124f0bfead27998ad7beea8441
|
[
"Apache-2.0"
] | 89 |
2018-02-02T03:54:39.000Z
|
2021-12-13T01:32:55.000Z
|
components/service/ucloud/iot/src/model/ListProductByTagsResult.cc
|
wanguojian/AliOS-Things
|
47fce29d4dd39d124f0bfead27998ad7beea8441
|
[
"Apache-2.0"
] | 89 |
2018-03-14T07:44:54.000Z
|
2021-11-26T07:43:25.000Z
|
components/service/ucloud/iot/src/model/ListProductByTagsResult.cc
|
wanguojian/AliOS-Things
|
47fce29d4dd39d124f0bfead27998ad7beea8441
|
[
"Apache-2.0"
] | 69 |
2018-01-22T09:45:52.000Z
|
2022-03-28T07:58:38.000Z
|
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* 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 <alibabacloud/iot/model/ListProductByTagsResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Iot;
using namespace AlibabaCloud::Iot::Model;
ListProductByTagsResult::ListProductByTagsResult() :
ServiceResult()
{}
ListProductByTagsResult::ListProductByTagsResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListProductByTagsResult::~ListProductByTagsResult()
{}
void ListProductByTagsResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allProductInfosNode = value["ProductInfos"]["ProductInfo"];
for (auto valueProductInfosProductInfo : allProductInfosNode)
{
ProductInfo productInfosObject;
if(!valueProductInfosProductInfo["ProductName"].isNull())
productInfosObject.productName = valueProductInfosProductInfo["ProductName"].asString();
if(!valueProductInfosProductInfo["ProductKey"].isNull())
productInfosObject.productKey = valueProductInfosProductInfo["ProductKey"].asString();
if(!valueProductInfosProductInfo["CreateTime"].isNull())
productInfosObject.createTime = std::stol(valueProductInfosProductInfo["CreateTime"].asString());
if(!valueProductInfosProductInfo["Description"].isNull())
productInfosObject.description = valueProductInfosProductInfo["Description"].asString();
if(!valueProductInfosProductInfo["NodeType"].isNull())
productInfosObject.nodeType = std::stoi(valueProductInfosProductInfo["NodeType"].asString());
productInfos_.push_back(productInfosObject);
}
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["ErrorMessage"].isNull())
errorMessage_ = value["ErrorMessage"].asString();
if(!value["Code"].isNull())
code_ = value["Code"].asString();
}
std::string ListProductByTagsResult::getErrorMessage()const
{
return errorMessage_;
}
std::vector<ListProductByTagsResult::ProductInfo> ListProductByTagsResult::getProductInfos()const
{
return productInfos_;
}
std::string ListProductByTagsResult::getCode()const
{
return code_;
}
bool ListProductByTagsResult::getSuccess()const
{
return success_;
}
| 32.241379 | 100 | 0.76934 |
wanguojian
|
fb1232dae595059d8531347e9f6289b8481a1010
| 4,166 |
cpp
|
C++
|
src/mxml/parsing/AppearanceHandler.cpp
|
dkun7944/mxml
|
6450e7cab88eb6ee0ac469f437047072e1868ea4
|
[
"MIT"
] | 18 |
2016-05-22T00:55:28.000Z
|
2021-03-29T08:44:23.000Z
|
src/mxml/parsing/AppearanceHandler.cpp
|
dkun7944/mxml
|
6450e7cab88eb6ee0ac469f437047072e1868ea4
|
[
"MIT"
] | 6 |
2017-05-17T13:20:09.000Z
|
2018-10-22T20:00:57.000Z
|
src/mxml/parsing/AppearanceHandler.cpp
|
dkun7944/mxml
|
6450e7cab88eb6ee0ac469f437047072e1868ea4
|
[
"MIT"
] | 14 |
2016-05-12T22:54:34.000Z
|
2021-10-19T12:43:16.000Z
|
// Copyright © 2016 Venture Media Labs.
//
// This file is part of mxml. The full mxml copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "AppearanceHandler.h"
#include <lxml/DoubleHandler.h>
#include <mxml/dom/InvalidDataError.h>
#include <cstring>
namespace mxml {
static const char* kLineWidthTag = "line-width";
static const char* kNoteSizeTag = "note-size";
static const char* kDistanceTag = "distance";
void AppearanceHandler::startElement(const lxml::QName& qname, const AttributeMap& attributes) {
_result = dom::Appearance{};
}
lxml::RecursiveHandler* AppearanceHandler::startSubElement(const lxml::QName& qname) {
if (strcmp(qname.localName(), kLineWidthTag) == 0)
return &_handler;
else if (strcmp(qname.localName(), kNoteSizeTag) == 0)
return &_handler;
else if (strcmp(qname.localName(), kDistanceTag) == 0)
return &_handler;
return 0;
}
void AppearanceHandler::endSubElement(const lxml::QName& qname, RecursiveHandler* parser) {
if (strcmp(qname.localName(), kLineWidthTag) == 0) {
auto lineWidthNode = _handler.result();
auto type = lineTypeFromString(lineWidthNode->attribute("type"));
auto value = lxml::DoubleHandler::parseDouble(lineWidthNode->text());
_result.lineWidths[type] = static_cast<dom::tenths_t>(value);
} else if (strcmp(qname.localName(), kNoteSizeTag) == 0) {
auto sizeNode = _handler.result();
auto type = noteTypeFromString(sizeNode->attribute("type"));
auto value = lxml::DoubleHandler::parseDouble(sizeNode->text());
_result.noteSizes[type] = static_cast<dom::tenths_t>(value);
} else if (strcmp(qname.localName(), kDistanceTag) == 0) {
auto distanceNode = _handler.result();
auto type = distanceTypeFromString(distanceNode->attribute("type"));
auto value = lxml::DoubleHandler::parseDouble(distanceNode->text());
_result.distances[type] = static_cast<dom::tenths_t>(value);
}
}
dom::LineType AppearanceHandler::lineTypeFromString(const std::string& string) {
if (string == "beam") return dom::LineType::Beam;
if (string == "bracket") return dom::LineType::Bracket;
if (string == "dashes") return dom::LineType::Dashes;
if (string == "enclosure") return dom::LineType::Enclosure;
if (string == "ending") return dom::LineType::Ending;
if (string == "extend") return dom::LineType::Extend;
if (string == "heavy barline") return dom::LineType::HeavyBarline;
if (string == "leger") return dom::LineType::Leger;
if (string == "light barline") return dom::LineType::LightBarline;
if (string == "octave shift") return dom::LineType::OctaveShift;
if (string == "pedal") return dom::LineType::Pedal;
if (string == "slur middle") return dom::LineType::SlurMiddle;
if (string == "slur tip") return dom::LineType::SlurTip;
if (string == "staff") return dom::LineType::Staff;
if (string == "stem") return dom::LineType::Stem;
if (string == "tie middle") return dom::LineType::TieMiddle;
if (string == "tie tip") return dom::LineType::TieTip;
if (string == "tuplet bracket") return dom::LineType::TupletBracket;
if (string == "wedge") return dom::LineType::Wedge;
throw dom::InvalidDataError("Invalid halign type " + string);
}
dom::NoteType AppearanceHandler::noteTypeFromString(const std::string& string) {
if (string == "cue") return dom::NoteType::Cue;
if (string == "grace") return dom::NoteType::Grace;
if (string == "large") return dom::NoteType::Large;
throw dom::InvalidDataError("Invalid halign type " + string);
}
dom::DistanceType AppearanceHandler::distanceTypeFromString(const std::string& string) {
if (string == "beam") return dom::DistanceType::Beam;
if (string == "hyphen") return dom::DistanceType::Hyphen;
throw dom::InvalidDataError("Invalid halign type " + string);
}
} // namespace mxml
| 44.795699 | 96 | 0.665146 |
dkun7944
|
fb161d2f66bb84e081547beefeb177c30c8fbee2
| 3,912 |
cpp
|
C++
|
willow/src/op/add.cpp
|
gglin001/popart
|
3225214343f6d98550b6620e809a3544e8bcbfc6
|
[
"MIT"
] | 61 |
2020-07-06T17:11:46.000Z
|
2022-03-12T14:42:51.000Z
|
willow/src/op/add.cpp
|
gglin001/popart
|
3225214343f6d98550b6620e809a3544e8bcbfc6
|
[
"MIT"
] | 1 |
2021-02-25T01:30:29.000Z
|
2021-11-09T11:13:14.000Z
|
willow/src/op/add.cpp
|
gglin001/popart
|
3225214343f6d98550b6620e809a3544e8bcbfc6
|
[
"MIT"
] | 6 |
2020-07-15T12:33:13.000Z
|
2021-11-07T06:55:00.000Z
|
// Copyright (c) 2018 Graphcore Ltd. All rights reserved.
#include <vector>
// for `find', we need the algorithm header
#include <algorithm>
#include <memory>
#include <popart/op/add.hpp>
#include <popart/opmanager.hpp>
#include <popart/tensor.hpp>
namespace popart {
// TODO : T6250 : Add support for V6 axis & broadcast attributes
AddOp::AddOp(const OperatorIdentifier &_opid, const Op::Settings &_settings)
: ElementWiseNpBroadcastableBinaryWithGradOp(_opid, _settings) {
// TODO : Use the attributes in Add-6
}
std::unique_ptr<Op> AddOp::clone() const {
return std::make_unique<AddOp>(*this);
}
bool AddOp::hasLhsInplaceVariant() const { return true; }
bool AddOp::hasRhsInplaceVariant() const { return true; }
std::unique_ptr<Op> AddOp::getLhsInplaceVariant() const {
return std::make_unique<AddLhsInplaceOp>(getSettings());
}
std::unique_ptr<Op> AddOp::getRhsInplaceVariant() const {
return std::make_unique<AddRhsInplaceOp>(getSettings());
}
OperatorIdentifier AddOp::getLhsOperatorIdentifier() const {
return Onnx::CustomOperators::AddLhsInplace;
}
OperatorIdentifier AddOp::getRhsOperatorIdentifier() const {
return Onnx::CustomOperators::AddRhsInplace;
}
AddArg0GradOp::AddArg0GradOp(const Op &op, const std::vector<int64_t> &_axes)
: ReduceSumOp(Onnx::GradOperators::AddArg0Grad,
_axes,
false,
op.getSettings()),
forward_op_arg_info(op.inInfo(AddOp::getArg0InIndex())) {}
const std::map<int, int> &AddArg0GradOp::gradOutToNonGradIn() const {
static const std::map<int, int> outInfo = {
{getOutIndex(), AddOp::getArg0InIndex()}};
return outInfo;
}
const std::vector<GradInOutMapper> &AddArg0GradOp::gradInputInfo() const {
static const std::vector<GradInOutMapper> inInfo = {
{getInIndex(), AddOp::getOutIndex(), GradOpInType::GradOut}};
return inInfo;
}
void AddArg0GradOp::setup() { outInfo(getOutIndex()) = forward_op_arg_info; }
std::unique_ptr<Op> AddArg0GradOp::clone() const {
return std::make_unique<AddArg0GradOp>(*this);
}
AddArg1GradOp::AddArg1GradOp(const Op &op, const std::vector<int64_t> &_axes)
: ReduceSumOp(Onnx::GradOperators::AddArg1Grad,
_axes,
false,
op.getSettings()),
forward_op_arg_info(op.inInfo(AddOp::getArg1InIndex())) {}
const std::map<int, int> &AddArg1GradOp::gradOutToNonGradIn() const {
static const std::map<int, int> outInfo = {
{getOutIndex(), AddOp::getArg1InIndex()}};
return outInfo;
}
const std::vector<GradInOutMapper> &AddArg1GradOp::gradInputInfo() const {
// input at index 0 : gradient of output of add
// might need to reduce across certain axes of this
// if numpy broadcasting happened
static const std::vector<GradInOutMapper> inInfo = {
{getInIndex(), AddOp::getOutIndex(), GradOpInType::GradOut}};
return inInfo;
}
void AddArg1GradOp::setup() { outInfo(getOutIndex()) = forward_op_arg_info; }
std::unique_ptr<Op> AddArg1GradOp::clone() const {
return std::make_unique<AddArg1GradOp>(*this);
}
namespace {
static OpDefinition::DataTypes T = {DataType::UINT32,
DataType::UINT64,
DataType::INT32,
DataType::INT64,
DataType::FLOAT16,
DataType::FLOAT};
static OpDefinition addOpDef({OpDefinition::Inputs({{"A", T}, {"B", T}}),
OpDefinition::Outputs({{"C", T}}),
OpDefinition::Attributes({})});
static OpCreator<AddOp> addOpCreator(OpDefinitions(
{{Onnx::Operators::Add_6, addOpDef}, {Onnx::Operators::Add_7, addOpDef}}));
static OpCreator<AddLhsInplaceOp> addAddLhsInplaceCreator(
OpDefinitions({{Onnx::CustomOperators::AddLhsInplace, addOpDef}}));
} // namespace
} // namespace popart
| 33.152542 | 79 | 0.667434 |
gglin001
|
fb1627497d33e1aa4cfdeed432b13bf54f8f836d
| 1,092 |
cpp
|
C++
|
IO/src/raw/src/export.cpp
|
tlalexander/stitchEm
|
cdff821ad2c500703e6cb237ec61139fce7bf11c
|
[
"MIT"
] | 182 |
2019-04-19T12:38:30.000Z
|
2022-03-20T16:48:20.000Z
|
IO/src/raw/src/export.cpp
|
doymcc/stitchEm
|
20693a55fa522d7a196b92635e7a82df9917c2e2
|
[
"MIT"
] | 107 |
2019-04-23T10:49:35.000Z
|
2022-03-02T18:12:28.000Z
|
IO/src/raw/src/export.cpp
|
doymcc/stitchEm
|
20693a55fa522d7a196b92635e7a82df9917c2e2
|
[
"MIT"
] | 59 |
2019-06-04T11:27:25.000Z
|
2022-03-17T23:49:49.000Z
|
// Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm
#include "export.hpp"
#include "rawOutput.hpp"
#include "libgpudiscovery/delayLoad.hpp"
#include "libvideostitch/output.hpp"
#include "libvideostitch/plugin.hpp"
#ifdef DELAY_LOAD_ENABLED
SET_DELAY_LOAD_HOOK
#endif // DELAY_LOAD_ENABLED
/** \name Services for writer plugin. */
//\{
extern "C" VS_PLUGINS_EXPORT VideoStitch::Potential<VideoStitch::Output::Output>* createWriterFn(
VideoStitch::Ptv::Value const* config, VideoStitch::Plugin::VSWriterPlugin::Config run_time) {
VideoStitch::Output::RawWriter* writer = VideoStitch::Output::RawWriter::create(config, run_time);
if (writer) {
return new VideoStitch::Potential<VideoStitch::Output::Output>(writer);
}
return new VideoStitch::Potential<VideoStitch::Output::Output>(
VideoStitch::Origin::Output, VideoStitch::ErrType::InvalidConfiguration, "Could not create RAW Writer");
}
extern "C" VS_PLUGINS_EXPORT bool handleWriterFn(VideoStitch::Ptv::Value const* config) {
return VideoStitch::Output::RawWriter::handles(config);
}
//\}
| 34.125 | 110 | 0.758242 |
tlalexander
|
fb166ed48090ebcf1b71d7b9cc98bb6a4615758e
| 1,765 |
cpp
|
C++
|
VNTextProxy/AlternateProxies/xinput1_3/Proxy.cpp
|
xenei/VNTranslationTools
|
7d197b3d0b73fd279b1fb5680404ea03975c31af
|
[
"MIT"
] | 41 |
2021-10-01T13:53:01.000Z
|
2022-03-22T22:30:58.000Z
|
VNTextProxy/AlternateProxies/xinput1_3/Proxy.cpp
|
xenei/VNTranslationTools
|
7d197b3d0b73fd279b1fb5680404ea03975c31af
|
[
"MIT"
] | 28 |
2021-10-15T03:56:27.000Z
|
2022-03-28T08:04:35.000Z
|
VNTextProxy/AlternateProxies/xinput1_3/Proxy.cpp
|
xenei/VNTranslationTools
|
7d197b3d0b73fd279b1fb5680404ea03975c31af
|
[
"MIT"
] | 9 |
2021-12-04T17:35:16.000Z
|
2022-03-19T17:14:42.000Z
|
#include "pch.h"
void Proxy::Init()
{
wchar_t realDllPath[MAX_PATH];
GetSystemDirectory(realDllPath, MAX_PATH);
wcscat_s(realDllPath, L"\\xinput1_3.dll");
HMODULE hDll = LoadLibrary(realDllPath);
if (hDll == nullptr)
{
MessageBox(nullptr, L"Cannot load original xinput1_3.dll library", L"Proxy", MB_ICONERROR);
ExitProcess(0);
}
#define RESOLVE(fn) Original##fn = GetProcAddress(hDll, #fn)
RESOLVE(DllMain);
RESOLVE(XInputEnable);
RESOLVE(XInputGetBatteryInformation);
RESOLVE(XInputGetCapabilities);
RESOLVE(XInputGetDSoundAudioDeviceGuids);
RESOLVE(XInputGetKeystroke);
RESOLVE(XInputGetState);
RESOLVE(XInputSetState);
#undef RESOLVE
}
__declspec(naked) void FakeDllMain() { __asm { jmp [Proxy::OriginalDllMain] } }
__declspec(naked) void FakeXInputEnable() { __asm { jmp [Proxy::OriginalXInputEnable] } }
__declspec(naked) void FakeXInputGetBatteryInformation() { __asm { jmp [Proxy::OriginalXInputGetBatteryInformation] } }
__declspec(naked) void FakeXInputGetCapabilities() { __asm { jmp [Proxy::OriginalXInputGetCapabilities] } }
__declspec(naked) void FakeXInputGetDSoundAudioDeviceGuids() { __asm { jmp [Proxy::OriginalXInputGetDSoundAudioDeviceGuids] } }
__declspec(naked) void FakeXInputGetKeystroke() { __asm { jmp [Proxy::OriginalXInputGetKeystroke] } }
__declspec(naked) void FakeXInputGetState() { __asm { jmp [Proxy::OriginalXInputGetState] } }
__declspec(naked) void FakeXInputSetState() { __asm { jmp [Proxy::OriginalXInputSetState] } }
| 51.911765 | 143 | 0.649858 |
xenei
|
fb16a001dc9906e5e013f5bca2efd32df7f3ba3d
| 9,245 |
cpp
|
C++
|
3dc/avp/bh_dummy.cpp
|
Melanikus/AvP
|
9d61eb974a23538e32bf2ef1b738643a018935a0
|
[
"BSD-3-Clause"
] | null | null | null |
3dc/avp/bh_dummy.cpp
|
Melanikus/AvP
|
9d61eb974a23538e32bf2ef1b738643a018935a0
|
[
"BSD-3-Clause"
] | null | null | null |
3dc/avp/bh_dummy.cpp
|
Melanikus/AvP
|
9d61eb974a23538e32bf2ef1b738643a018935a0
|
[
"BSD-3-Clause"
] | null | null | null |
/* CDF 9/10/98 A bold new initiaitive! */
#include "3dc.h"
#include "inline.h"
#include "module.h"
#include "io.h"
#include "strategy_def.h"
#include "gamedef.h"
#include "bh_types.h"
#include "dynblock.h"
#include "dynamics.h"
#include "weapons.h"
#include "compiled_shapes.h"
#include "inventory.h"
#include "triggers.h"
#include "mslhand.h"
#define UseLocalAssert TRUE
#include "ourasert.h"
#include "pmove.h"
#include "pvisible.h"
#include "bh_switch_door.h"
#include "bh_platform_lift.h"
#include "load_shape.h"
#include "bh_weapon.h"
#include "bh_debris.h"
#include "lighting.h"
#include "bh_link_switch.h"
#include "bh_binary_switch.h"
#include "pheromone.h"
#include "bh_predator.h"
#include "bh_agun.h"
#include "plat_shp.h"
#include "psnd.h"
#include "ai_sight.h"
#include "sequences.h"
#include "huddefs.h"
#include "showcmds.h"
#include "sfx.h"
#include "bh_marine.h"
#include "bh_dummy.h"
#include "bh_far.h"
#include "targeting.h"
#include "dxlog.h"
#include "los.h"
#include "psndplat.h"
#include "extents.h"
#include "pldghost.h"
#include "pldnet.h"
extern unsigned char Null_Name[8];
extern ACTIVESOUNDSAMPLE ActiveSounds[];
extern SECTION * GetNamedHierarchyFromLibrary(const char * rif_name, const char * hier_name);
void CreateDummy(VECTORCH *Position);
/* Begin code! */
void CastDummy(void) {
#define BOTRANGE 2000
VECTORCH position;
if (AvP.Network!=I_No_Network) {
NewOnScreenMessage("NO DUMMYS IN MULTIPLAYER MODE");
return;
}
position=Player->ObStrategyBlock->DynPtr->Position;
position.vx+=MUL_FIXED(Player->ObStrategyBlock->DynPtr->OrientMat.mat31,BOTRANGE);
position.vy+=MUL_FIXED(Player->ObStrategyBlock->DynPtr->OrientMat.mat32,BOTRANGE);
position.vz+=MUL_FIXED(Player->ObStrategyBlock->DynPtr->OrientMat.mat33,BOTRANGE);
CreateDummy(&position);
}
void CreateDummy(VECTORCH *Position) {
STRATEGYBLOCK* sbPtr;
/* create and initialise a strategy block */
sbPtr = CreateActiveStrategyBlock();
if(!sbPtr) {
NewOnScreenMessage("FAILED TO CREATE DUMMY: SB CREATION FAILURE");
return; /* failure */
}
InitialiseSBValues(sbPtr);
sbPtr->I_SBtype = I_BehaviourDummy;
AssignNewSBName(sbPtr);
/* create, initialise and attach a dynamics block */
sbPtr->DynPtr = AllocateDynamicsBlock(DYNAMICS_TEMPLATE_MARINE_PLAYER);
if(sbPtr->DynPtr)
{
EULER zeroEuler = {0,0,0};
DYNAMICSBLOCK *dynPtr = sbPtr->DynPtr;
GLOBALASSERT(dynPtr);
dynPtr->PrevPosition = dynPtr->Position = *Position;
dynPtr->OrientEuler = zeroEuler;
CreateEulerMatrix(&dynPtr->OrientEuler, &dynPtr->OrientMat);
TransposeMatrixCH(&dynPtr->OrientMat);
}
else
{
/* dynamics block allocation failed... */
RemoveBehaviourStrategy(sbPtr);
NewOnScreenMessage("FAILED TO CREATE DUMMY: DYNBLOCK CREATION FAILURE");
return;
}
sbPtr->shapeIndex = 0;
sbPtr->maintainVisibility = 1;
sbPtr->containingModule = ModuleFromPosition(&(sbPtr->DynPtr->Position), (MODULE*)0);
/* Initialise dummy's stats */
{
sbPtr->SBDamageBlock.Health=30000<<ONE_FIXED_SHIFT;
sbPtr->SBDamageBlock.Armour=30000<<ONE_FIXED_SHIFT;
sbPtr->SBDamageBlock.SB_H_flags.AcidResistant=1;
sbPtr->SBDamageBlock.SB_H_flags.FireResistant=1;
sbPtr->SBDamageBlock.SB_H_flags.ElectricResistant=1;
sbPtr->SBDamageBlock.SB_H_flags.PerfectArmour=1;
sbPtr->SBDamageBlock.SB_H_flags.ElectricSensitive=0;
sbPtr->SBDamageBlock.SB_H_flags.Combustability=0;
sbPtr->SBDamageBlock.SB_H_flags.Indestructable=1;
}
/* create, initialise and attach a dummy data block */
sbPtr->SBdataptr = (void *)AllocateMem(sizeof(DUMMY_STATUS_BLOCK));
if(sbPtr->SBdataptr)
{
SECTION *root_section;
DUMMY_STATUS_BLOCK *dummyStatus = (DUMMY_STATUS_BLOCK *)sbPtr->SBdataptr;
GLOBALASSERT(dummyStatus);
dummyStatus->incidentFlag=0;
dummyStatus->incidentTimer=0;
dummyStatus->HModelController.section_data=NULL;
dummyStatus->HModelController.Deltas=NULL;
switch (AvP.PlayerType) {
case I_Marine:
dummyStatus->PlayerType=I_Marine;
root_section=GetNamedHierarchyFromLibrary("hnpcmarine","marine with pulse rifle");
if (!root_section) {
RemoveBehaviourStrategy(sbPtr);
NewOnScreenMessage("FAILED TO CREATE DUMMY: NO HMODEL");
return;
}
Create_HModel(&dummyStatus->HModelController,root_section);
InitHModelSequence(&dummyStatus->HModelController,(int)HMSQT_MarineStand,(int)MSSS_Fidget_A,-1);
break;
case I_Alien:
dummyStatus->PlayerType=I_Alien;
root_section=GetNamedHierarchyFromLibrary("hnpcalien","alien");
if (!root_section) {
RemoveBehaviourStrategy(sbPtr);
NewOnScreenMessage("FAILED TO CREATE DUMMY: NO HMODEL");
return;
}
Create_HModel(&dummyStatus->HModelController,root_section);
InitHModelSequence(&dummyStatus->HModelController,(int)HMSQT_AlienStand,(int)ASSS_Standard,-1);
break;
case I_Predator:
dummyStatus->PlayerType=I_Predator;
root_section=GetNamedHierarchyFromLibrary("hnpcpredator","pred with wristblade");
if (!root_section) {
RemoveBehaviourStrategy(sbPtr);
NewOnScreenMessage("FAILED TO CREATE DUMMY: NO HMODEL");
return;
}
Create_HModel(&dummyStatus->HModelController,root_section);
InitHModelSequence(&dummyStatus->HModelController,(int)HMSQT_PredatorStand,(int)PSSS_Standard,-1);
break;
}
ProveHModel_Far(&dummyStatus->HModelController,sbPtr);
if(!(sbPtr->containingModule))
{
/* no containing module can be found... abort*/
RemoveBehaviourStrategy(sbPtr);
NewOnScreenMessage("FAILED TO CREATE DUMMY: MODULE CONTAINMENT FAILURE");
return;
}
LOCALASSERT(sbPtr->containingModule);
MakeDummyNear(sbPtr);
NewOnScreenMessage("DUMMY CREATED");
} else {
/* no data block can be allocated */
RemoveBehaviourStrategy(sbPtr);
NewOnScreenMessage("FAILED TO CREATE DUMMY: MALLOC FAILURE");
return;
}
}
void MakeDummyNear(STRATEGYBLOCK *sbPtr)
{
extern MODULEMAPBLOCK AlienDefaultMap;
MODULE tempModule;
DISPLAYBLOCK *dPtr;
DYNAMICSBLOCK *dynPtr;
DUMMY_STATUS_BLOCK *dummyStatusPointer;
LOCALASSERT(sbPtr);
LOCALASSERT(sbPtr->SBdptr == NULL);
dynPtr = sbPtr->DynPtr;
dummyStatusPointer = (DUMMY_STATUS_BLOCK *)(sbPtr->SBdataptr);
LOCALASSERT(dummyStatusPointer);
LOCALASSERT(dynPtr);
AlienDefaultMap.MapShape = sbPtr->shapeIndex;
tempModule.m_mapptr = &AlienDefaultMap;
tempModule.m_sbptr = (STRATEGYBLOCK*)NULL;
tempModule.m_numlights = 0;
tempModule.m_lightarray = (struct lightblock *)0;
tempModule.m_extraitemdata = (struct extraitemdata *)0;
tempModule.m_dptr = NULL;
AllocateModuleObject(&tempModule);
dPtr = tempModule.m_dptr;
if(dPtr==NULL) return; /* cannot allocate displayblock, so leave far */
sbPtr->SBdptr = dPtr;
dPtr->ObStrategyBlock = sbPtr;
dPtr->ObMyModule = NULL;
/* need to initialise positional information in the new display block */
dPtr->ObWorld = dynPtr->Position;
dPtr->ObEuler = dynPtr->OrientEuler;
dPtr->ObMat = dynPtr->OrientMat;
/* zero linear velocity in dynamics block */
sbPtr->DynPtr->LinVelocity.vx = 0;
sbPtr->DynPtr->LinVelocity.vy = 0;
sbPtr->DynPtr->LinVelocity.vz = 0;
/* state and sequence initialisation */
dPtr->HModelControlBlock=&dummyStatusPointer->HModelController;
ProveHModel(dPtr->HModelControlBlock,dPtr);
/*Copy extents from the collision extents in extents.c*/
dPtr->ObMinX=-CollisionExtents[CE_MARINE].CollisionRadius;
dPtr->ObMaxX=CollisionExtents[CE_MARINE].CollisionRadius;
dPtr->ObMinZ=-CollisionExtents[CE_MARINE].CollisionRadius;
dPtr->ObMaxZ=CollisionExtents[CE_MARINE].CollisionRadius;
dPtr->ObMinY=CollisionExtents[CE_MARINE].CrouchingTop;
dPtr->ObMaxY=CollisionExtents[CE_MARINE].Bottom;
dPtr->ObRadius = 1000;
}
void MakeDummyFar(STRATEGYBLOCK *sbPtr)
{
DUMMY_STATUS_BLOCK *dummyStatusPointer;
int i;
LOCALASSERT(sbPtr);
LOCALASSERT(sbPtr->SBdptr != NULL);
dummyStatusPointer = (DUMMY_STATUS_BLOCK *)(sbPtr->SBdataptr);
LOCALASSERT(dummyStatusPointer);
/* get rid of the displayblock */
i = DestroyActiveObject(sbPtr->SBdptr);
LOCALASSERT(i==0);
sbPtr->SBdptr = NULL;
/* zero linear velocity in dynamics block */
sbPtr->DynPtr->LinVelocity.vx = 0;
sbPtr->DynPtr->LinVelocity.vy = 0;
sbPtr->DynPtr->LinVelocity.vz = 0;
}
void DummyBehaviour(STRATEGYBLOCK *sbPtr) {
DUMMY_STATUS_BLOCK *dummyStatusPointer;
LOCALASSERT(sbPtr);
LOCALASSERT(sbPtr->containingModule);
dummyStatusPointer = (DUMMY_STATUS_BLOCK *)(sbPtr->SBdataptr);
LOCALASSERT(dummyStatusPointer);
/* Should be the same near as far. */
/* test if we've got a containing module: if we haven't, do nothing.
This is important as the object could have been marked for deletion by the visibility
management system...*/
if(!sbPtr->containingModule)
{
DestroyAnyStrategyBlock(sbPtr); /* just to make sure */
return;
} else if (dummyStatusPointer->PlayerType!=I_Alien) {
AddMarinePheromones(sbPtr->containingModule->m_aimodule);
}
/* Incident handling. */
dummyStatusPointer->incidentFlag=0;
dummyStatusPointer->incidentTimer-=NormalFrameTime;
if (dummyStatusPointer->incidentTimer<0) {
dummyStatusPointer->incidentFlag=1;
dummyStatusPointer->incidentTimer=32767+(FastRandom()&65535);
}
}
| 29.349206 | 102 | 0.743429 |
Melanikus
|
fb179647819ccf5ed6f7eb7feac4aa9e26f0d73d
| 31,699 |
cxx
|
C++
|
base/screg/sc/server/crash.cxx
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17 |
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
base/screg/sc/server/crash.cxx
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2 |
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
base/screg/sc/server/crash.cxx
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14 |
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
/*++
Copyright (c) 1992 Microsoft Corporation
Module Name:
crash.cxx
Abstract:
Contains code concerned with recovery actions that are taken when
a service crashes. This file contains the following functions:
ScQueueRecoveryAction
CCrashRecord::IncrementCount
CRestartContext::Perform
CRebootMessageContext::Perform
CRebootContext::Perform
CRunCommandContext::Perform
Author:
Anirudh Sahni (anirudhs) 02-Dec-1996
Environment:
User Mode -Win32
Revision History:
22-Oct-1998 jschwart
Convert SCM to use NT thread pool APIs
02-Dec-1996 AnirudhS
Created
--*/
//
// INCLUDES
//
#include "precomp.hxx"
#include <lmcons.h> // needed for other lm headers
#include <lmerr.h> // NERR_Success
#include <lmshare.h> // NetSessionEnum
#include <lmmsg.h> // NetMessageBufferSend
#include <lmapibuf.h> // NetApiBufferFree
#include <valid.h> // ACTION_TYPE_INVALID
#include <svcslib.h> // CWorkItemContext
#include "smartp.h" // CHeapPtr
#include "scconfig.h" // ScReadFailureActions, etc.
#include "depend.h" // ScStartServiceAndDependencies
#include "account.h" // ScLogonService
#include "scseclib.h" // ScCreateAndSetSD
#include "start.h" // ScAllowInteractiveServices, ScInitStartupInfo
#include "resource.h" // IDS_SC_ACTION_BASE
//
// Defines and Typedefs
//
#define FILETIMES_PER_SEC ((__int64) 10000000) // (1 second)/(100 ns)
#define LENGTH(array) (sizeof(array)/sizeof((array)[0]))
//
// Globals
//
//
// Local Function Prototypes
//
VOID
ScLogRecoveryFailure(
IN SC_ACTION_TYPE ActionType,
IN LPCWSTR ServiceDisplayName,
IN DWORD Error
);
inline LPWSTR
LocalDup(
LPCWSTR String
)
{
LPWSTR Dup = (LPWSTR) LocalAlloc(0, WCSSIZE(String));
if (Dup != NULL)
{
wcscpy(Dup, String);
}
return Dup;
}
//
// Callback context for restarting a service
//
class CRestartContext : public CWorkItemContext
{
DECLARE_CWorkItemContext
public:
CRestartContext(
IN LPSERVICE_RECORD ServiceRecord
) :
_ServiceRecord(ServiceRecord)
{
ServiceRecord->UseCount++;
SC_LOG2(USECOUNT, "CRestartContext: %ws increment "
"USECOUNT=%lu\n", ServiceRecord->ServiceName,
ServiceRecord->UseCount);
}
~CRestartContext()
{
CServiceRecordExclusiveLock RLock;
ScDecrementUseCountAndDelete(_ServiceRecord);
}
private:
LPSERVICE_RECORD _ServiceRecord;
};
//
// Callback context for broadcasting a reboot message
//
class CRebootMessageContext : public CWorkItemContext
{
DECLARE_CWorkItemContext
public:
CRebootMessageContext(
IN LPWSTR RebootMessage,
IN DWORD Delay,
IN LPWSTR DisplayName
) :
_RebootMessage(RebootMessage),
_Delay(Delay),
_DisplayName(LocalDup(DisplayName))
{ }
~CRebootMessageContext()
{
LocalFree(_RebootMessage);
}
private:
LPWSTR _RebootMessage;
DWORD _Delay;
LPWSTR _DisplayName;
};
//
// Callback context for a reboot
// (The service name is used only for logging)
//
class CRebootContext : public CWorkItemContext
{
DECLARE_CWorkItemContext
public:
CRebootContext(
IN DWORD ActionDelay,
IN LPWSTR DisplayName
) :
_Delay(ActionDelay),
_DisplayName(DisplayName)
{ }
~CRebootContext()
{
LocalFree(_DisplayName);
}
private:
DWORD _Delay;
LPWSTR _DisplayName;
};
//
// Callback context for running a recovery command
//
class CRunCommandContext : public CWorkItemContext
{
DECLARE_CWorkItemContext
public:
CRunCommandContext(
IN LPSERVICE_RECORD ServiceRecord,
IN LPWSTR FailureCommand
) :
_ServiceRecord(ServiceRecord),
_FailureCommand(FailureCommand)
{
//
// The service record is used to get the
// account name to run the command in.
//
ServiceRecord->UseCount++;
SC_LOG2(USECOUNT, "CRunCommandContext: %ws increment "
"USECOUNT=%lu\n", ServiceRecord->ServiceName,
ServiceRecord->UseCount);
}
~CRunCommandContext()
{
LocalFree(_FailureCommand);
CServiceRecordExclusiveLock RLock;
ScDecrementUseCountAndDelete(_ServiceRecord);
}
private:
LPSERVICE_RECORD _ServiceRecord;
LPWSTR _FailureCommand;
};
/****************************************************************************/
VOID
ScQueueRecoveryAction(
IN LPSERVICE_RECORD ServiceRecord
)
/*++
Routine Description:
Arguments:
Return Value:
none.
--*/
{
SC_ACTION_TYPE ActionType = SC_ACTION_NONE;
DWORD ActionDelay = 0;
DWORD FailNum = 1;
NTSTATUS ntStatus;
//
// See if there is any recovery action configured for this service.
//
HKEY Key = NULL;
{
DWORD ResetPeriod = INFINITE;
LPSERVICE_FAILURE_ACTIONS_WOW64 psfa = NULL;
DWORD Error = ScOpenServiceConfigKey(
ServiceRecord->ServiceName,
KEY_READ,
FALSE, // don't create if missing
&Key
);
if (Error == ERROR_SUCCESS)
{
Error = ScReadFailureActions(Key, &psfa);
}
if (Error != ERROR_SUCCESS)
{
SC_LOG(ERROR, "Couldn't read service's failure actions, %lu\n", Error);
}
else if (psfa != NULL && psfa->cActions > 0)
{
ResetPeriod = psfa->dwResetPeriod;
}
//
// Allocate a crash record for the service.
// Increment the service's crash count, subject to the reset period
// we just read from the registry (INFINITE if we read none).
//
if (ServiceRecord->CrashRecord == NULL)
{
ServiceRecord->CrashRecord = new CCrashRecord;
}
if (ServiceRecord->CrashRecord == NULL)
{
SC_LOG0(ERROR, "Couldn't allocate service's crash record\n");
//
// NOTE: We still continue, taking the failure count to be 1.
// (The crash record is used only in the "else" clause.)
//
}
else
{
FailNum = ServiceRecord->CrashRecord->IncrementCount(ResetPeriod);
}
//
// Figure out which recovery action we're going to take.
//
if (psfa != NULL && psfa->cActions > 0)
{
SC_ACTION * lpsaActions = (SC_ACTION *) ((LPBYTE) psfa + psfa->dwsaActionsOffset);
DWORD i = min(FailNum, psfa->cActions);
ActionType = lpsaActions[i - 1].Type;
ActionDelay = lpsaActions[i - 1].Delay;
if (ACTION_TYPE_INVALID(ActionType))
{
SC_LOG(ERROR, "Service has invalid action type %lu\n", ActionType);
ActionType = SC_ACTION_NONE;
}
}
LocalFree(psfa);
}
//
// Log an event about this service failing, and about the proposed
// recovery action.
//
if (ActionType != SC_ACTION_NONE)
{
WCHAR wszActionString[50];
if (!LoadString(GetModuleHandle(NULL),
IDS_SC_ACTION_BASE + ActionType,
wszActionString,
LENGTH(wszActionString)))
{
SC_LOG(ERROR, "LoadString failed %lu\n", GetLastError());
wszActionString[0] = L'\0';
}
SC_LOG2(ERROR, "The following recovery action will be taken in %d ms: %ws.\n",
ActionDelay, wszActionString);
ScLogEvent(NEVENT_SERVICE_CRASH,
ServiceRecord->DisplayName,
FailNum,
ActionDelay,
ActionType,
wszActionString);
}
else
{
ScLogEvent(NEVENT_SERVICE_CRASH_NO_ACTION,
ServiceRecord->DisplayName,
FailNum);
}
//
// Queue a work item that will actually carry out the action after the
// delay has elapsed.
//
switch (ActionType)
{
case SC_ACTION_NONE:
break;
case SC_ACTION_RESTART:
{
CRestartContext * pCtx = new CRestartContext(ServiceRecord);
if (pCtx == NULL)
{
SC_LOG0(ERROR, "Couldn't allocate restart context\n");
break;
}
ntStatus = pCtx->AddDelayedWorkItem(ActionDelay,
WT_EXECUTEONLYONCE);
if (!NT_SUCCESS(ntStatus))
{
SC_LOG(ERROR, "Couldn't add restart work item 0x%x\n", ntStatus);
delete pCtx;
}
break;
}
case SC_ACTION_REBOOT:
{
//
// Get the reboot message for the service, if any
//
LPWSTR RebootMessage = NULL;
ScReadRebootMessage(Key, &RebootMessage);
if (RebootMessage != NULL)
{
//
// Broadcast the message to all users. Do this in a separate
// thread so that we can release our exclusive lock on the
// service database quickly.
//
CRebootMessageContext * pCtx = new CRebootMessageContext(
RebootMessage,
ActionDelay,
ServiceRecord->DisplayName
);
if (pCtx == NULL)
{
SC_LOG0(ERROR, "Couldn't allocate restart context\n");
LocalFree(RebootMessage);
break;
}
ntStatus = pCtx->AddWorkItem(WT_EXECUTEONLYONCE);
if (!NT_SUCCESS(ntStatus))
{
SC_LOG(ERROR, "Couldn't add restart work item 0x%x\n", ntStatus);
delete pCtx;
}
}
else
{
//
// Queue a work item to perform the reboot after the delay has
// elapsed.
// (CODEWORK Share this code with CRebootMessageContext::Perform)
//
LPWSTR DisplayNameCopy = LocalDup(ServiceRecord->DisplayName);
CRebootContext * pCtx = new CRebootContext(
ActionDelay,
DisplayNameCopy
);
if (pCtx == NULL)
{
SC_LOG0(ERROR, "Couldn't allocate reboot context\n");
LocalFree(DisplayNameCopy);
}
else
{
ntStatus = pCtx->AddWorkItem(WT_EXECUTEONLYONCE);
if (!NT_SUCCESS(ntStatus))
{
SC_LOG(ERROR, "Couldn't add reboot work item 0x%x\n", ntStatus);
delete pCtx;
}
}
}
}
break;
case SC_ACTION_RUN_COMMAND:
{
//
// Get the failure command for the service, if any
//
CHeapPtr<LPWSTR> FailureCommand;
ScReadFailureCommand(Key, &FailureCommand);
if (FailureCommand == NULL)
{
SC_LOG0(ERROR, "Asked to run a failure command, but found "
"none for this service\n");
ScLogRecoveryFailure(
SC_ACTION_RUN_COMMAND,
ServiceRecord->DisplayName,
ERROR_NO_RECOVERY_PROGRAM
);
break;
}
//
// Replace %1% in the failure command with the failure count.
// (FormatMessage is *useless* for this purpose because it AV's
// if the failure command contains a %2, %3 etc.!)
//
UNICODE_STRING Formatted;
{
UNICODE_STRING Unformatted;
RtlInitUnicodeString(&Unformatted, FailureCommand);
Formatted.Length = 0;
Formatted.MaximumLength = Unformatted.MaximumLength + 200;
Formatted.Buffer =
(LPWSTR) LocalAlloc(0, Formatted.MaximumLength);
if (Formatted.Buffer == NULL)
{
SC_LOG(ERROR, "Couldn't allocate formatted string, %lu\n", GetLastError());
break;
}
WCHAR Environment[30];
wsprintf(Environment, L"1=%lu%c", FailNum, L'\0');
NTSTATUS ntstatus = RtlExpandEnvironmentStrings_U(
Environment,
&Unformatted,
&Formatted,
NULL);
if (!NT_SUCCESS(ntstatus))
{
SC_LOG(ERROR, "RtlExpandEnvironmentStrings_U failed %#lx\n", ntstatus);
wcscpy(Formatted.Buffer, FailureCommand);
}
}
CRunCommandContext * pCtx =
new CRunCommandContext(ServiceRecord, Formatted.Buffer);
if (pCtx == NULL)
{
SC_LOG0(ERROR, "Couldn't allocate RunCommand context\n");
LocalFree(Formatted.Buffer);
break;
}
ntStatus = pCtx->AddDelayedWorkItem(ActionDelay,
WT_EXECUTEONLYONCE);
if (!NT_SUCCESS(ntStatus))
{
SC_LOG(ERROR, "Couldn't add RunCommand work item 0x%x\n", ntStatus);
delete pCtx;
}
}
break;
default:
SC_ASSERT(0);
}
if (Key != NULL)
{
ScRegCloseKey(Key);
}
}
DWORD
CCrashRecord::IncrementCount(
DWORD ResetSeconds
)
/*++
Routine Description:
Increments a service's crash count.
Arguments:
ResetSeconds - Length, in seconds, of a period of no crashes after which
the crash count should be reset to zero.
Return Value:
The service's new crash count.
--*/
{
__int64 SecondLastCrashTime = _LastCrashTime;
GetSystemTimeAsFileTime((FILETIME *) &_LastCrashTime);
if (ResetSeconds == INFINITE ||
SecondLastCrashTime + ResetSeconds * FILETIMES_PER_SEC > _LastCrashTime)
{
_Count++;
}
else
{
SC_LOG(CONFIG_API, "More than %lu seconds have elapsed since last "
"crash, resetting crash count.\n",
ResetSeconds);
_Count = 1;
}
SC_LOG(CONFIG_API, "Service's crash count is now %lu\n", _Count);
return _Count;
}
VOID
CRestartContext::Perform(
IN BOOLEAN fWaitStatus
)
/*++
Routine Description:
--*/
{
//
// Make sure we were called because of a timeout
//
SC_ASSERT(fWaitStatus == TRUE);
SC_LOG(CONFIG_API, "Restarting %ws service...\n", _ServiceRecord->ServiceName);
RemoveDelayedWorkItem();
//
// CODEWORK Allow arguments to the service.
//
DWORD status = ScStartServiceAndDependencies(_ServiceRecord, 0, NULL, FALSE);
if (status == NO_ERROR)
{
status = _ServiceRecord->StartError;
SC_LOG(CONFIG_API, "ScStartServiceAndDependencies succeeded, StartError = %lu\n",
status);
}
else
{
SC_LOG(CONFIG_API, "ScStartServiceAndDependencies failed, %lu\n", status);
//
// Should we treat ERROR_SERVICE_ALREADY_RUNNING as a success?
// No, because it could alert the administrator to a less-than-
// optimal system configuration wherein something else is
// restarting the service.
//
ScLogRecoveryFailure(
SC_ACTION_RESTART,
_ServiceRecord->DisplayName,
status
);
}
delete this;
}
VOID
CRebootMessageContext::Perform(
IN BOOLEAN fWaitStatus
)
/*++
Routine Description:
--*/
{
//
// Broadcast the reboot message to all users
//
SESSION_INFO_0 * Buffer = NULL;
DWORD EntriesRead = 0, TotalEntries = 0;
NTSTATUS ntStatus;
NET_API_STATUS Status = NetSessionEnum(
NULL, // servername
NULL, // UncClientName
NULL, // username
0, // level
(LPBYTE *) &Buffer,
0xFFFFFFFF, // prefmaxlen
&EntriesRead,
&TotalEntries,
NULL // resume_handle
);
if (EntriesRead > 0)
{
SC_ASSERT(EntriesRead == TotalEntries);
SC_ASSERT(Status == NERR_Success);
WCHAR ComputerName[MAX_COMPUTERNAME_LENGTH + 1];
DWORD nSize = LENGTH(ComputerName);
if (!GetComputerName(ComputerName, &nSize))
{
SC_LOG(ERROR, "GetComputerName failed! %lu\n", GetLastError());
}
else
{
DWORD MsgLen = (DWORD) WCSSIZE(_RebootMessage);
for (DWORD i = 0; i < EntriesRead; i++)
{
Status = NetMessageBufferSend(
NULL, // servername
Buffer[i].sesi0_cname, // msgname
ComputerName, // fromname
(LPBYTE) _RebootMessage,// buf
MsgLen // buflen
);
if (Status != NERR_Success)
{
SC_LOG2(ERROR, "NetMessageBufferSend to %ws failed %lu\n",
Buffer[i].sesi0_cname, Status);
}
}
}
}
else if (Status != NERR_Success)
{
SC_LOG(ERROR, "NetSessionEnum failed %lu\n", Status);
}
if (Buffer != NULL)
{
NetApiBufferFree(Buffer);
}
//
// Queue a work item to perform the reboot after the delay has elapsed.
// Note: We're counting the delay from the time that the broadcast finished.
//
CRebootContext * pCtx = new CRebootContext(_Delay, _DisplayName);
if (pCtx == NULL)
{
SC_LOG0(ERROR, "Couldn't allocate reboot context\n");
}
else
{
_DisplayName = NULL; // pCtx will free it
ntStatus = pCtx->AddWorkItem(WT_EXECUTEONLYONCE);
if (!NT_SUCCESS(ntStatus))
{
SC_LOG(ERROR, "Couldn't add reboot work item 0x%x\n", ntStatus);
delete pCtx;
}
}
delete this;
}
VOID
CRebootContext::Perform(
IN BOOLEAN fWaitStatus
)
/*++
Routine Description:
--*/
{
SC_LOG0(CONFIG_API, "Rebooting machine...\n");
// Write an event log entry?
//
// Enable our shutdown privilege. Since we are shutting down, don't
// bother doing it for only the current thread and don't bother
// disabling it afterwards.
//
BOOLEAN WasEnabled;
NTSTATUS Status = RtlAdjustPrivilege(
SE_SHUTDOWN_PRIVILEGE,
TRUE, // enable
FALSE, // this thread only? - No
&WasEnabled);
if (!NT_SUCCESS(Status))
{
SC_LOG(ERROR, "RtlAdjustPrivilege failed! %#lx\n", Status);
SC_ASSERT(0);
}
else
{
WCHAR wszShutdownText[128];
WCHAR wszPrintableText[128 + MAX_SERVICE_NAME_LENGTH];
if (LoadString(GetModuleHandle(NULL),
IDS_SC_REBOOT_MESSAGE,
wszShutdownText,
LENGTH(wszShutdownText)))
{
wsprintf(wszPrintableText, wszShutdownText, _DisplayName);
}
else
{
//
// If LoadString failed, it probably means the buffer
// is too small to hold the localized string
//
SC_LOG(ERROR, "LoadString failed! %lu\n", GetLastError());
SC_ASSERT(FALSE);
wszShutdownText[0] = L'\0';
}
if (!InitiateSystemShutdownEx(NULL, // machine name
wszPrintableText, // reboot message
_Delay / 1000, // timeout in seconds
TRUE, // force apps closed
TRUE, // reboot
SHTDN_REASON_MAJOR_SOFTWARE |
SHTDN_REASON_MINOR_UNSTABLE))
{
DWORD dwError = GetLastError();
//
// If two services fail simultaneously and both are configured
// to reboot the machine, InitiateSystemShutdown will fail all
// calls past the first with ERROR_SHUTDOWN_IN_PROGRESS. We
// don't want to log an event in this case.
//
if (dwError != ERROR_SHUTDOWN_IN_PROGRESS) {
SC_LOG(ERROR, "InitiateSystemShutdown failed! %lu\n", dwError);
ScLogRecoveryFailure(
SC_ACTION_REBOOT,
_DisplayName,
dwError
);
}
}
}
delete this;
}
VOID
CRunCommandContext::Perform(
IN BOOLEAN fWaitStatus
)
/*++
Routine Description:
CODEWORK Share this code with ScLogonAndStartImage
--*/
{
//
// Make sure we were called because of a timeout
//
SC_ASSERT(fWaitStatus == TRUE);
DWORD status = NO_ERROR;
HANDLE Token = NULL;
PSID ServiceSid = NULL; // SID is returned only if not LocalSystem
LPWSTR AccountName = NULL;
SECURITY_ATTRIBUTES SaProcess; // Process security info (used only if not LocalSystem)
STARTUPINFOW StartupInfo;
PROCESS_INFORMATION ProcessInfo;
RemoveDelayedWorkItem();
//
// Get the Account Name for the service. A NULL Account Name means the
// service is configured to run in the LocalSystem account.
//
status = ScLookupServiceAccount(
_ServiceRecord->ServiceName,
&AccountName
);
// We only need to log on if it's not the LocalSystem account
if (AccountName != NULL)
{
//
// CODEWORK: Keep track of recovery EXEs spawned so we can
// load/unload the user profile for the process.
//
status = ScLogonService(
_ServiceRecord->ServiceName,
AccountName,
&Token,
NULL,
&ServiceSid
);
if (status != NO_ERROR)
{
SC_LOG(ERROR, "CRunCommandContext: ScLogonService failed, %lu\n", status);
goto Clean0;
}
SaProcess.nLength = sizeof(SECURITY_ATTRIBUTES);
SaProcess.bInheritHandle = FALSE;
SC_ACE_DATA AceData[] =
{
{ACCESS_ALLOWED_ACE_TYPE, 0, 0,
PROCESS_ALL_ACCESS, &ServiceSid},
{ACCESS_ALLOWED_ACE_TYPE, 0, 0,
PROCESS_SET_INFORMATION |
PROCESS_TERMINATE |
SYNCHRONIZE, &LocalSystemSid}
};
NTSTATUS ntstatus = ScCreateAndSetSD(
AceData, // AceData
LENGTH(AceData), // AceCount
NULL, // OwnerSid (optional)
NULL, // GroupSid (optional)
&SaProcess.lpSecurityDescriptor
// pNewDescriptor
);
LocalFree(ServiceSid);
if (! NT_SUCCESS(ntstatus))
{
SC_LOG(ERROR, "CRunCommandContext: ScCreateAndSetSD failed %#lx\n", ntstatus);
status = RtlNtStatusToDosError(ntstatus);
goto Clean1;
}
SC_LOG2(CONFIG_API,"CRunCommandContext: about to spawn recovery program in account %ws: %ws\n",
AccountName, _FailureCommand);
//
// Impersonate the user so we don't give access to
// EXEs that have been locked down for the account.
//
if (!ImpersonateLoggedOnUser(Token))
{
status = GetLastError();
SC_LOG1(ERROR,
"ScLogonAndStartImage: ImpersonateLoggedOnUser failed %d\n",
status);
goto Clean2;
}
//
// Spawn the Image Process
//
ScInitStartupInfo(&StartupInfo, FALSE);
if (!CreateProcessAsUserW(
Token, // logon token
NULL, // lpApplicationName
_FailureCommand, // lpCommandLine
&SaProcess, // process' security attributes
NULL, // first thread's security attributes
FALSE, // whether new process inherits handles
CREATE_NEW_CONSOLE, // creation flags
NULL, // environment block
NULL, // current directory
&StartupInfo, // startup info
&ProcessInfo // process info
))
{
status = GetLastError();
SC_LOG(ERROR, "CRunCommandContext: CreateProcessAsUser failed %lu\n", status);
RevertToSelf();
goto Clean2;
}
RevertToSelf();
}
else
{
//
// It's the LocalSystem account
//
//
// If the process is to be interactive, set the appropriate flags.
//
BOOL bInteractive = FALSE;
if (AccountName == NULL &&
_ServiceRecord->ServiceStatus.dwServiceType & SERVICE_INTERACTIVE_PROCESS)
{
bInteractive = ScAllowInteractiveServices();
if (!bInteractive)
{
//
// Write an event to indicate that an interactive service
// was started, but the system is configured to not allow
// services to be interactive.
//
ScLogEvent(NEVENT_SERVICE_NOT_INTERACTIVE,
_ServiceRecord->DisplayName);
}
}
ScInitStartupInfo(&StartupInfo, bInteractive);
SC_LOG1(CONFIG_API,"CRunCommandContext: about to spawn recovery program in "
"the LocalSystem account: %ws\n", _FailureCommand);
//
// Spawn the Image Process
//
if (!CreateProcessW(
NULL, // lpApplicationName
_FailureCommand, // lpCommandLine
NULL, // process' security attributes
NULL, // first thread's security attributes
FALSE, // whether new process inherits handles
CREATE_NEW_CONSOLE, // creation flags
NULL, // environment block
NULL, // current directory
&StartupInfo, // startup info
&ProcessInfo // process info
))
{
status = GetLastError();
SC_LOG(ERROR, "CRunCommandContext: CreateProcess failed %lu\n", status);
goto Clean2;
}
}
SC_LOG0(CONFIG_API, "Recovery program spawned successfully.\n");
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
Clean2:
if (AccountName != NULL)
{
RtlDeleteSecurityObject(&SaProcess.lpSecurityDescriptor);
}
Clean1:
if (AccountName != NULL)
{
CloseHandle(Token);
}
Clean0:
if (status != NO_ERROR)
{
ScLogRecoveryFailure(
SC_ACTION_RUN_COMMAND,
_ServiceRecord->DisplayName,
status
);
}
delete this;
}
VOID
ScLogRecoveryFailure(
IN SC_ACTION_TYPE ActionType,
IN LPCWSTR ServiceDisplayName,
IN DWORD Error
)
/*++
Routine Description:
--*/
{
WCHAR wszActionString[50];
if (!LoadString(GetModuleHandle(NULL),
IDS_SC_ACTION_BASE + ActionType,
wszActionString,
LENGTH(wszActionString)))
{
SC_LOG(ERROR, "LoadString failed %lu\n", GetLastError());
wszActionString[0] = L'\0';
}
ScLogEvent(
NEVENT_SERVICE_RECOVERY_FAILED,
ActionType,
wszActionString,
(LPWSTR) ServiceDisplayName,
Error
);
}
| 29.680712 | 104 | 0.481151 |
npocmaka
|
fb17e58356bb333e7cedf7bbe6d02f3b46ff139b
| 2,517 |
cpp
|
C++
|
Algorithms/graphs/TwoColor/TwoColor/main.cpp
|
mingyuefly/geekTimeCode
|
d97c5f29a429ac9cc7289ac34e049ea43fa58822
|
[
"MIT"
] | 1 |
2019-05-01T04:51:14.000Z
|
2019-05-01T04:51:14.000Z
|
Algorithms/graphs/TwoColor/TwoColor/main.cpp
|
mingyuefly/geekTimeCode
|
d97c5f29a429ac9cc7289ac34e049ea43fa58822
|
[
"MIT"
] | null | null | null |
Algorithms/graphs/TwoColor/TwoColor/main.cpp
|
mingyuefly/geekTimeCode
|
d97c5f29a429ac9cc7289ac34e049ea43fa58822
|
[
"MIT"
] | null | null | null |
//
// main.cpp
// TwoColor
//
// Created by mingyue on 2022/3/6.
// Copyright © 2022 Gmingyue. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
class Graph {
public:
vector<vector<int> *> * adj;
Graph() {
}
Graph(int V) {
this->V = V;
this->E = 0;
adj = new vector<vector<int> *>(this->V);
for (int i = 0; i < V; i++) {
adj->at(i) = new vector<int>();
}
}
~Graph() {
cout << "~Graph()" << endl;
for (int i = 0; i < V; i++) {
delete adj->at(i);
}
delete adj;
}
int getV() {
return V;
}
int getE() {
return E;
}
void addEdge(int v, int w) {
adj->at(v)->push_back(w);
adj->at(w)->push_back(v);
E++;
}
void show() {
for (int i = 0; i < adj->size(); i++) {
cout << i << ":";
for (int j = 0; j < adj->at(i)->size(); j++) {
cout << adj->at(i)->at(j) << " ";
}
cout << endl;
}
}
private:
int V;
int E;
};
class TwoColor {
public:
TwoColor() {
}
TwoColor(Graph * g) {
marked = new vector<bool>(g->getV(), false);
color = new vector<bool>(g->getV(), false);
for (int s = 0; s < g->getV(); s++) {
if (marked->at(s) == false) {
dfs(g, s);
}
}
}
~TwoColor() {
cout << "~TwoColor()" << endl;
delete marked;
delete color;
}
bool getIsTwoColorable() {
return isTwoColorable;
}
private:
vector<bool> * marked;
vector<bool> * color;
bool isTwoColorable = true;
void dfs(Graph * g, int v) {
marked->at(v) = true;
for (int w = 0; w < g->adj->at(v)->size(); w++) {
if (marked->at(g->adj->at(v)->at(w)) == false) {
color->at(g->adj->at(v)->at(w)) = !color->at(v);
dfs(g, g->adj->at(v)->at(w));
} else if (color->at(g->adj->at(v)->at(w)) == color->at(v)) {
isTwoColorable = false;
}
}
}
};
int main(int argc, const char * argv[]) {
Graph * g = new Graph(4);
g->addEdge(0, 1);
g->addEdge(1, 2);
g->addEdge(2, 3);
g->addEdge(3, 0);
// g->addEdge(1, 3);
g->show();
TwoColor twoColor = TwoColor(g);
cout << twoColor.getIsTwoColorable() << endl;
delete g;
return 0;
}
| 21.512821 | 73 | 0.424712 |
mingyuefly
|
fb183a4b905d4aae0fb85a0f3a6d0268f39b6326
| 597 |
cpp
|
C++
|
src/platforms/android/androidadjusthelper.cpp
|
swatson555/mozilla-vpn-client
|
feb23f893968bd032686fc16bbab71e02b006289
|
[
"MIT"
] | null | null | null |
src/platforms/android/androidadjusthelper.cpp
|
swatson555/mozilla-vpn-client
|
feb23f893968bd032686fc16bbab71e02b006289
|
[
"MIT"
] | null | null | null |
src/platforms/android/androidadjusthelper.cpp
|
swatson555/mozilla-vpn-client
|
feb23f893968bd032686fc16bbab71e02b006289
|
[
"MIT"
] | null | null | null |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "androidadjusthelper.h"
#include <QAndroidJniObject>
#include <QString>
void AndroidAdjustHelper::trackEvent(const QString& event) {
QAndroidJniObject javaMessage = QAndroidJniObject::fromString(event);
QAndroidJniObject::callStaticMethod<void>(
"org/mozilla/firefox/vpn/qt/VPNAdjustHelper", "trackEvent",
"(Ljava/lang/String;)V", javaMessage.object<jstring>());
}
| 39.8 | 71 | 0.743719 |
swatson555
|
fb1a14fc904379b1fedd08288d1128d830a1dc14
| 2,469 |
cpp
|
C++
|
Engine/BuildSystem/Configuration/BuildConfiguration.cpp
|
GabyForceQ/PolluxEngine
|
2dbc84ed1d434f1b6d794f775f315758f0e8cc49
|
[
"BSD-3-Clause"
] | 3 |
2020-05-19T20:24:28.000Z
|
2020-09-27T11:28:42.000Z
|
Engine/BuildSystem/Configuration/BuildConfiguration.cpp
|
GabyForceQ/PolluxEngine
|
2dbc84ed1d434f1b6d794f775f315758f0e8cc49
|
[
"BSD-3-Clause"
] | 31 |
2020-05-27T11:01:27.000Z
|
2020-08-08T15:53:23.000Z
|
Engine/BuildSystem/Configuration/BuildConfiguration.cpp
|
GabyForceQ/PolluxEngine
|
2dbc84ed1d434f1b6d794f775f315758f0e8cc49
|
[
"BSD-3-Clause"
] | null | null | null |
/*****************************************************************************************************************************
* Copyright 2020 Gabriel Gheorghe. All rights reserved.
* This code is licensed under the BSD 3-Clause "New" or "Revised" License
* License url: https://github.com/GabyForceQ/PolluxEngine/blob/master/LICENSE
*****************************************************************************************************************************/
#include "Engine/enginepch.hpp"
#include "BuildConfiguration.hpp"
namespace Pollux::BuildSystem
{
BuildConfiguration::BuildConfiguration(BuildOptimization optimization) noexcept
:
optimization{ optimization }
{
}
BuildConfiguration& BuildConfiguration::operator=(const BuildConfiguration& rhs)
{
projectName = rhs.projectName;
projectPath = rhs.projectPath;
buildOutputType = rhs.buildOutputType;
preprocessorDefinitions = rhs.preprocessorDefinitions;
includeDirectories = rhs.includeDirectories;
bUsePrecompiledHeaders = rhs.bUsePrecompiledHeaders;
precompiledHeaderName = rhs.precompiledHeaderName;
bUseDebugLibraries = rhs.bUseDebugLibraries;
wholeProgramOptimization = rhs.wholeProgramOptimization;
bLinkIncremental = rhs.bLinkIncremental;
functionLevelLinking = rhs.functionLevelLinking;
bIntrinsicFunctions = rhs.bIntrinsicFunctions;
bBufferSecurityCheck = rhs.bBufferSecurityCheck;
bStringPooling = rhs.bStringPooling;
bGenerateDebugInformation = rhs.bGenerateDebugInformation;
bOptimizeReferences = rhs.bOptimizeReferences;
bEnableCOMDATFolding = rhs.bEnableCOMDATFolding;
return *this;
}
void BuildConfiguration::Reset()
{
projectName = "";
projectPath = "";
buildOutputType = BuildOutputType::None;
preprocessorDefinitions.clear();
includeDirectories.clear();
bUsePrecompiledHeaders = false;
precompiledHeaderName = "";
bUseDebugLibraries = false;
wholeProgramOptimization = BuildBooleanType::None;
bLinkIncremental = false;
functionLevelLinking = BuildBooleanType::None;
bIntrinsicFunctions = false;
bBufferSecurityCheck = false;
bStringPooling = false;
bGenerateDebugInformation = false;
bOptimizeReferences = false;
bEnableCOMDATFolding = false;
}
}
| 37.984615 | 127 | 0.63143 |
GabyForceQ
|
fb1a82d0bc8757861267ea43a083192d92e9c198
| 2,695 |
cpp
|
C++
|
D3dEngine/PhysicsComponent.cpp
|
KyleBCox/Direct3d12-Engine
|
eab9791bdb00a2ff3103e6b83c1c8a2ccb280241
|
[
"MIT"
] | 11 |
2018-04-14T12:10:19.000Z
|
2020-12-31T08:58:47.000Z
|
D3dEngine/PhysicsComponent.cpp
|
KyleBCox/Direct3d-12-Engine-
|
eab9791bdb00a2ff3103e6b83c1c8a2ccb280241
|
[
"MIT"
] | null | null | null |
D3dEngine/PhysicsComponent.cpp
|
KyleBCox/Direct3d-12-Engine-
|
eab9791bdb00a2ff3103e6b83c1c8a2ccb280241
|
[
"MIT"
] | 3 |
2019-01-29T14:03:59.000Z
|
2019-10-09T13:21:31.000Z
|
#include "stdafx.h"
#include "PhysicsComponent.h"
#include "ComponentManager.h"
#include "BoxCollider.h"
/**
* @brief Construct a new Physics Component:: Physics Component object
* controls physics movements in the world
*
*/
PhysicsComponent::PhysicsComponent() :
minY(0),
isRising(false),
yPosFallDiff(0)
{
}
PhysicsComponent::~PhysicsComponent()
{
}
int PhysicsComponent::InitRootSignatureParameters(int indexOffset)
{
return 0;
}
void PhysicsComponent::Init()
{
}
/**
* @brief updates the node position with physics movements
*
*/
void PhysicsComponent::Update()
{
ComponentManager* fullOwner = ComponentManager::GetOwner(owner);
auto colliderComp = fullOwner->GetComponent(typeid(BoxCollider).name());
if (colliderComp != nullptr) {
auto collider = ((BoxCollider*)colliderComp.get())->GetCollider();
if (XMVectorGetY(m_transform->position) - collider.Extents.y >= minY && !isRising) {
if (previouslyRising) {
previouslyRising = false;
yPos = XMVectorGetY(m_transform->position);
}
// fall down
yPosFallDiff *= yPosFallMultiplyer;
yPos -= yPosFallDiff;
m_transform->position = XMVectorSetY(m_transform->position, yPos);
}
// is going up
if (isRising) {
yPos = XMVectorGetY(m_transform->position);
yPosFallDiff = yPosFallStart;
previouslyRising = true;
}
// is under minY
if (XMVectorGetY(m_transform->position) - collider.Extents.y <= minY) {
yPos = minY;
//put on top of minY
yPosFallDiff = yPosFallStart;
m_transform->position = XMVectorSetY(m_transform->position, minY + collider.Extents.y);
}
}
else {
if (XMVectorGetY(m_transform->position) >= minY && !isRising) {
if (previouslyRising) {
previouslyRising = false;
yPos = XMVectorGetY(m_transform->position);
}
// fall down
yPosFallDiff = yPosFallDiff * yPosFallMultiplyer + (yPosFallDiff);
yPos -= yPosFallDiff;
m_transform->position = XMVectorSetY(m_transform->position, yPos);
}
// is going up
if (isRising) {
yPos = XMVectorGetY(m_transform->position);
yPosFallDiff = yPosFallStart;
previouslyRising = true;
}
// is under minY
if (XMVectorGetY(m_transform->position) <= minY) {
yPos = minY;
//put on top of minY
yPosFallDiff = yPosFallStart;
m_transform->position = XMVectorSetY(m_transform->position, minY);
}
}
}
void PhysicsComponent::Render()
{
}
void PhysicsComponent::OnKeyDown(UINT key)
{
}
void PhysicsComponent::OnKeyUp(UINT key)
{
}
void PhysicsComponent::OnMouseMoved(float x, float y)
{
}
void PhysicsComponent::OnDeviceRemoved()
{
}
void PhysicsComponent::CreateWindowSizeDependentResources()
{
}
void PhysicsComponent::CreateDeviceDependentResources()
{
}
| 22.272727 | 90 | 0.711317 |
KyleBCox
|
fb1c7d34a6e0be7d8373d8d836ee1e503286d08f
| 1,690 |
cpp
|
C++
|
tlx/string/appendline.cpp
|
GerHobbelt/tlx
|
81a71238b17df27d98a4dff9ceba21bd79fddffb
|
[
"BSL-1.0"
] | 284 |
2017-02-26T08:49:15.000Z
|
2022-03-30T21:55:37.000Z
|
tlx/string/appendline.cpp
|
xiao2mo/tlx
|
b311126e670753897c1defceeaa75c83d2d9531a
|
[
"BSL-1.0"
] | 24 |
2017-09-05T21:02:41.000Z
|
2022-03-07T10:09:59.000Z
|
tlx/string/appendline.cpp
|
xiao2mo/tlx
|
b311126e670753897c1defceeaa75c83d2d9531a
|
[
"BSL-1.0"
] | 62 |
2017-02-23T12:29:27.000Z
|
2022-03-31T07:45:59.000Z
|
/*******************************************************************************
* tlx/string/appendline.cpp
*
* Part of tlx - http://panthema.net/tlx
*
* Copyright (C) 2019 Timo Bingmann <tb@panthema.net>
*
* All rights reserved. Published under the Boost Software License, Version 1.0
******************************************************************************/
#include <tlx/string/appendline.hpp>
#include <algorithm>
namespace tlx {
std::istream& appendline(std::istream& is, std::string& str, char delim) {
size_t size = str.size();
size_t capacity = str.capacity();
std::streamsize rest = capacity - size;
if (rest == 0) {
// if rest is zero, already expand string
capacity = std::max(static_cast<size_t>(8), capacity * 2);
rest = capacity - size;
}
// give getline access to all of capacity
str.resize(capacity);
// get until delim or rest is filled
is.getline(const_cast<char*>(str.data()) + size, rest, delim);
// gcount includes the delimiter
size_t new_size = size + is.gcount();
// is failbit set?
if (!is) {
// if string ran out of space, expand, and retry
if (is.gcount() + 1 == rest) {
is.clear();
str.resize(new_size);
str.reserve(capacity * 2);
return appendline(is, str, delim);
}
// else fall through and deliver error
}
else if (!is.eof()) {
// subtract delimiter
--new_size;
}
// resize string to fit its contents
str.resize(new_size);
return is;
}
} // namespace tlx
/******************************************************************************/
| 27.704918 | 80 | 0.511243 |
GerHobbelt
|
fb296164604e03b8de299a508c7ae07883a02eb2
| 5,743 |
cpp
|
C++
|
ros/src/convert.cpp
|
norlab-ulaval/navtechradar
|
4d3ccd2558e79142d656a6c12cd826d9397b0f2d
|
[
"MIT"
] | 2 |
2020-11-18T17:48:40.000Z
|
2021-01-12T14:15:17.000Z
|
ros/src/convert.cpp
|
norlab-ulaval/navtechradar
|
4d3ccd2558e79142d656a6c12cd826d9397b0f2d
|
[
"MIT"
] | null | null | null |
ros/src/convert.cpp
|
norlab-ulaval/navtechradar
|
4d3ccd2558e79142d656a6c12cd826d9397b0f2d
|
[
"MIT"
] | 1 |
2022-03-22T16:09:51.000Z
|
2022-03-22T16:09:51.000Z
|
#include <ros/ros.h>
#include <omp.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/Image.h>
#include <opencv2/core.hpp>
#include <opencv2/highgui/highgui.hpp>
ros::Publisher pub;
ros::Subscriber sub;
double radar_upgrade_time = 1632182400;
void load_radar(cv::Mat raw_data, std::vector<int64_t> ×tamps, std::vector<float> &azimuths,
std::vector<bool> &valid, cv::Mat &fft_data) {
int encoder_size = 5600;
int N = raw_data.rows;
timestamps = std::vector<int64_t>(N, 0);
azimuths = std::vector<float>(N, 0);
valid = std::vector<bool>(N, true);
int range_bins = raw_data.cols - 11;
fft_data = cv::Mat::zeros(N, range_bins, CV_32F);
#pragma omp parallel
for (int i = 0; i < N; ++i) {
uchar* byteArray = raw_data.ptr<uchar>(i);
timestamps[i] = *((int64_t *)(byteArray));
azimuths[i] = *((uint16_t *)(byteArray + 8)) * 2 * M_PI / float(encoder_size);
// std::cout << azimuths[i] << std::endl;
valid[i] = byteArray[10] == 255;
for (int j = 0; j < range_bins; j++) {
fft_data.at<float>(i, j) = (float)*(byteArray + 11 + j) / 255.0;
}
}
// std::cout << timestamps[0] << " " << timestamps[1] << std::endl;
}
float get_azimuth_index(std::vector<float> &azimuths, float azimuth) {
float mind = 1000;
float closest = 0;
for (uint i = 0; i < azimuths.size(); ++i) {
float d = fabs(azimuths[i] - azimuth);
if (d < mind) {
mind = d;
closest = i;
}
}
if (azimuths[closest] < azimuth) {
float delta = (azimuth - azimuths[closest]) / (azimuths[closest + 1] - azimuths[closest]);
closest += delta;
} else if (azimuths[closest] > azimuth){
float delta = (azimuths[closest] - azimuth) / (azimuths[closest] - azimuths[closest - 1]);
closest -= delta;
}
return closest;
}
void radar_polar_to_cartesian(std::vector<float> &azimuths, cv::Mat &fft_data, float radar_resolution,
float cart_resolution, int cart_pixel_width, bool interpolate_crossover, cv::Mat &cart_img) {
float cart_min_range = (cart_pixel_width / 2) * cart_resolution;
if (cart_pixel_width % 2 == 0)
cart_min_range = (cart_pixel_width / 2 - 0.5) * cart_resolution;
cv::Mat map_x = cv::Mat::zeros(cart_pixel_width, cart_pixel_width, CV_32F);
cv::Mat map_y = cv::Mat::zeros(cart_pixel_width, cart_pixel_width, CV_32F);
#pragma omp parallel for collapse(2)
for (int j = 0; j < map_y.cols; ++j) {
for (int i = 0; i < map_y.rows; ++i) {
map_y.at<float>(i, j) = -1 * cart_min_range + j * cart_resolution;
}
}
#pragma omp parallel for collapse(2)
for (int i = 0; i < map_x.rows; ++i) {
for (int j = 0; j < map_x.cols; ++j) {
map_x.at<float>(i, j) = cart_min_range - i * cart_resolution;
}
}
cv::Mat range = cv::Mat::zeros(cart_pixel_width, cart_pixel_width, CV_32F);
cv::Mat angle = cv::Mat::zeros(cart_pixel_width, cart_pixel_width, CV_32F);
float azimuth_step = azimuths[1] - azimuths[0];
// float azimuth_step = (M_PI / 200);
// azimuths[0] = 0;
#pragma omp parallel for collapse(2)
for (int i = 0; i < range.rows; ++i) {
for (int j = 0; j < range.cols; ++j) {
float x = map_x.at<float>(i, j);
float y = map_y.at<float>(i, j);
float r = (sqrt(pow(x, 2) + pow(y, 2)) - radar_resolution / 2) / radar_resolution;
if (r < 0)
r = 0;
range.at<float>(i, j) = r;
float theta = atan2f(y, x);
if (theta < 0)
theta += 2 * M_PI;
// angle.at<float>(i, j) = get_azimuth_index(azimuths, theta);
angle.at<float>(i, j) = (theta - azimuths[0]) / azimuth_step;
}
}
if (interpolate_crossover) {
cv::Mat a0 = cv::Mat::zeros(1, fft_data.cols, CV_32F);
cv::Mat aN_1 = cv::Mat::zeros(1, fft_data.cols, CV_32F);
for (int j = 0; j < fft_data.cols; ++j) {
a0.at<float>(0, j) = fft_data.at<float>(0, j);
aN_1.at<float>(0, j) = fft_data.at<float>(fft_data.rows-1, j);
}
cv::vconcat(aN_1, fft_data, fft_data);
cv::vconcat(fft_data, a0, fft_data);
angle = angle + 1;
}
cv::remap(fft_data, cart_img, range, angle, cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar(0, 0, 0));
}
void callback(const sensor_msgs::ImageConstPtr & msg) {
cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::MONO8);
cv::Mat raw_data = cv_ptr->image;
// Extract fft_data and relevant meta data
std::vector<int64_t> timestamps;
std::vector<float> azimuths;
std::vector<bool> valid;
cv::Mat polar_img;
load_radar(raw_data, timestamps, azimuths, valid, polar_img);
cv::Mat cart_img;
float cart_resolution = 0.25;
int cart_pixel_width = 1000;
bool interpolate_crossover = true;
float radar_resolution = 0.0596;
double t = msg->header.stamp.toSec();;
if (t > radar_upgrade_time) {
radar_resolution = 0.04381;
}
radar_polar_to_cartesian(azimuths, polar_img, radar_resolution, cart_resolution, cart_pixel_width,
interpolate_crossover, cart_img);
// Convert to cartesian
cv::Mat vis;
cart_img.convertTo(vis, CV_8U, 255.0);
cv_bridge::CvImage out_msg;
out_msg.encoding = "mono8";
out_msg.image = vis;
pub.publish(out_msg.toImageMsg());
}
int main(int32_t argc, char** argv) {
ros::init(argc, argv, "convert");
ros::NodeHandle nh;
std::cout << omp_get_num_threads() << std::endl;
pub = nh.advertise<sensor_msgs::Image>("/Navtech/Cartesian", 4);
sub = nh.subscribe("/talker1/Navtech/Polar", 10, &callback);
ros::spin();
return 0;
}
| 37.535948 | 108 | 0.608045 |
norlab-ulaval
|
fb2f7b6e5e5b37fa23bdc5935bd721bfb325d3e9
| 239 |
hpp
|
C++
|
include/Pomdog/Graphics/Shader.hpp
|
ValtoForks/pomdog
|
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
|
[
"MIT"
] | null | null | null |
include/Pomdog/Graphics/Shader.hpp
|
ValtoForks/pomdog
|
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
|
[
"MIT"
] | null | null | null |
include/Pomdog/Graphics/Shader.hpp
|
ValtoForks/pomdog
|
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.
#pragma once
#include "Pomdog/Basic/Export.hpp"
namespace Pomdog {
class POMDOG_EXPORT Shader {
public:
virtual ~Shader() = default;
};
} // namespace Pomdog
| 15.933333 | 71 | 0.719665 |
ValtoForks
|
fb2fb867682534a281555932584875709596e0ab
| 381 |
cc
|
C++
|
ports/www/chromium-legacy/newport/files/patch-content_common_user__agent.cc
|
liweitianux/DeltaPorts
|
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
|
[
"BSD-2-Clause-FreeBSD"
] | 31 |
2015-02-06T17:06:37.000Z
|
2022-03-08T19:53:28.000Z
|
ports/www/chromium-legacy/newport/files/patch-content_common_user__agent.cc
|
liweitianux/DeltaPorts
|
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
|
[
"BSD-2-Clause-FreeBSD"
] | 236 |
2015-06-29T19:51:17.000Z
|
2021-12-16T22:46:38.000Z
|
ports/www/chromium-legacy/newport/files/patch-content_common_user__agent.cc
|
liweitianux/DeltaPorts
|
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
|
[
"BSD-2-Clause-FreeBSD"
] | 52 |
2015-02-06T17:05:36.000Z
|
2021-10-21T12:13:06.000Z
|
--- content/common/user_agent.cc.orig 2021-01-18 21:28:57 UTC
+++ content/common/user_agent.cc
@@ -213,6 +213,14 @@ std::string BuildOSCpuInfoFromOSVersionAndCpuType(cons
);
#endif
+#if defined(OS_BSD)
+#if defined(__x86_64__)
+ base::StringAppendF(&os_cpu, "; Linux x86_64");
+#else
+ base::StringAppendF(&os_cpu, "; Linux i686");
+#endif
+#endif
+
return os_cpu;
}
| 21.166667 | 75 | 0.685039 |
liweitianux
|
fb2fe2d8dc1a20e134b62b4b28f2096cef0e7054
| 2,212 |
cpp
|
C++
|
examples/tcp_server/client.cpp
|
jharmer95/rpc.hpp
|
8cba8ff7b63b28546d58bcf828ab93a9df03744e
|
[
"BSD-3-Clause"
] | 1 |
2019-11-15T21:05:18.000Z
|
2019-11-15T21:05:18.000Z
|
examples/tcp_server/client.cpp
|
jharmer95/rpc.hpp
|
8cba8ff7b63b28546d58bcf828ab93a9df03744e
|
[
"BSD-3-Clause"
] | 47 |
2019-11-15T20:58:44.000Z
|
2022-03-30T13:19:24.000Z
|
examples/tcp_server/client.cpp
|
jharmer95/rpc.hpp
|
8cba8ff7b63b28546d58bcf828ab93a9df03744e
|
[
"BSD-3-Clause"
] | null | null | null |
#define RPC_HPP_CLIENT_IMPL
#include "client.hpp"
#include <iostream>
#include <stdexcept>
#include <string>
int main(int argc, char* argv[])
{
if (argc < 3)
{
std::cerr << "USAGE: rpc_client <server_ipv4> <port_num>\n";
return EXIT_FAILURE;
}
RpcClient client{ argv[1], argv[2] };
std::string currentFuncName;
try
{
// Trivial function example
{
currentFuncName = "Sum";
const auto result = client.template call_func<int>("Sum", 1, 2);
std::cout << "Sum(1, 2) == " << result << '\n';
}
// Example of calling w/ references
{
currentFuncName = "AddOneToEach";
std::vector<int> vec{ 1, 2, 3, 4, 5 };
client.template call_func<void>("AddOneToEach", vec);
std::cout << "AddOneToEach({ 1, 2, 3, 4, 5 }) == {";
for (size_t i = 0; i < vec.size() - 1; ++i)
{
std::cout << ' ' << vec[i] << ", ";
}
std::cout << ' ' << vec.back() << " }\n";
}
// Template function example
{
currentFuncName = "GetTypeName<int>";
auto result = client.template call_func<std::string>("GetTypeName<int>");
std::cout << "GetTypeName<int>() == \"" << result << "\"\n";
currentFuncName = "GetTypeName<double>";
result = client.template call_func<std::string>("GetTypeName<double>");
std::cout << "GetTypeName<double>() == \"" << result << "\"\n";
currentFuncName = "GetTypeName<std::string>";
result = client.template call_func<std::string>("GetTypeName<std::string>");
std::cout << "GetTypeName<std::string>() == \"" << result << "\"\n";
}
// Now shutdown the server
{
currentFuncName = "KillServer";
client.call_func("KillServer");
std::cout << "Server shutdown remotely...\n";
}
return EXIT_SUCCESS;
}
catch (const std::exception& ex)
{
std::cerr << "Call to '" << currentFuncName << "' failed, reason: " << ex.what() << '\n';
return EXIT_FAILURE;
}
}
| 28 | 97 | 0.5 |
jharmer95
|
fb30994a202bfeb9828de5ca268a6dab7bbc8898
| 1,851 |
cpp
|
C++
|
deps/icu4c/source/layout/TrimmedArrayProcessor2.cpp
|
alexhenrie/poedit
|
b9b31a111d9e8a84cf1e698aff2c922a79bdd859
|
[
"MIT"
] | 1,155 |
2015-01-10T19:04:33.000Z
|
2022-03-30T12:30:30.000Z
|
deps/icu4c/source/layout/TrimmedArrayProcessor2.cpp
|
alexhenrie/poedit
|
b9b31a111d9e8a84cf1e698aff2c922a79bdd859
|
[
"MIT"
] | 618 |
2015-01-02T01:39:26.000Z
|
2022-03-28T15:18:40.000Z
|
deps/icu4c/source/layout/TrimmedArrayProcessor2.cpp
|
alexhenrie/poedit
|
b9b31a111d9e8a84cf1e698aff2c922a79bdd859
|
[
"MIT"
] | 228 |
2015-01-13T12:55:42.000Z
|
2022-03-30T11:11:05.000Z
|
/*
*
* (C) Copyright IBM Corp. and others 1998-2013 - All Rights Reserved
*
*/
#include "LETypes.h"
#include "MorphTables.h"
#include "SubtableProcessor2.h"
#include "NonContextualGlyphSubst.h"
#include "NonContextualGlyphSubstProc2.h"
#include "TrimmedArrayProcessor2.h"
#include "LEGlyphStorage.h"
#include "LESwaps.h"
U_NAMESPACE_BEGIN
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TrimmedArrayProcessor2)
TrimmedArrayProcessor2::TrimmedArrayProcessor2()
{
}
TrimmedArrayProcessor2::TrimmedArrayProcessor2(const LEReferenceTo<MorphSubtableHeader2> &morphSubtableHeader, LEErrorCode &success)
: NonContextualGlyphSubstitutionProcessor2(morphSubtableHeader, success)
{
const LEReferenceTo<NonContextualGlyphSubstitutionHeader2> header(morphSubtableHeader, success);
trimmedArrayLookupTable = LEReferenceTo<TrimmedArrayLookupTable>(morphSubtableHeader, success, &header->table);
firstGlyph = SWAPW(trimmedArrayLookupTable->firstGlyph);
lastGlyph = firstGlyph + SWAPW(trimmedArrayLookupTable->glyphCount);
valueArray = LEReferenceToArrayOf<LookupValue>(morphSubtableHeader, success, &trimmedArrayLookupTable->valueArray[0], LE_UNBOUNDED_ARRAY);
}
TrimmedArrayProcessor2::~TrimmedArrayProcessor2()
{
}
void TrimmedArrayProcessor2::process(LEGlyphStorage &glyphStorage, LEErrorCode &success)
{
if(LE_FAILURE(success)) return;
le_int32 glyphCount = glyphStorage.getGlyphCount();
le_int32 glyph;
for (glyph = 0; glyph < glyphCount; glyph += 1) {
LEGlyphID thisGlyph = glyphStorage[glyph];
TTGlyphID ttGlyph = (TTGlyphID) LE_GET_GLYPH(thisGlyph);
if ((ttGlyph > firstGlyph) && (ttGlyph < lastGlyph)) {
TTGlyphID newGlyph = SWAPW(valueArray(ttGlyph - firstGlyph, success));
glyphStorage[glyph] = LE_SET_GLYPH(thisGlyph, newGlyph);
}
}
}
U_NAMESPACE_END
| 31.913793 | 142 | 0.766613 |
alexhenrie
|
fb340a6f0dc9961334a1fdffd26a1ea936070fc7
| 893 |
cpp
|
C++
|
code chef/Temple Land TEMPLELA adhoc .cpp
|
priojeetpriyom/competitive-programming
|
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
|
[
"MIT"
] | 1 |
2021-11-22T02:26:43.000Z
|
2021-11-22T02:26:43.000Z
|
code chef/Temple Land TEMPLELA adhoc .cpp
|
priojeetpriyom/competitive-programming
|
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
|
[
"MIT"
] | null | null | null |
code chef/Temple Land TEMPLELA adhoc .cpp
|
priojeetpriyom/competitive-programming
|
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
int t;
cin>>t;
int n;
int ara[111];
while(t--) {
int i;
scanf("%d", &n);
for(int i=1; i<=n; i++)
scanf("%d", &ara[i]);
int ans=1;
if( !(n&1)) ans=0;
else {
for(i=1; i<=(n>>1)+1; i++ ) {
if(ara[i]!= i) {
ans=0;
break;
}
}
for(i; i<=n; i++) {
if(ara[i]!= n-i+1) {
ans=0;
break;
}
// cnt--;
}
}
if(ans) printf("yes\n");
else printf("no\n");
}
return 0;
}
| 16.849057 | 42 | 0.293393 |
priojeetpriyom
|
fb34cb6914cc1384df3e55f5b72e6fd365cc4c18
| 353 |
cpp
|
C++
|
cpp/ss_example.cpp
|
jieyaren/hello-world
|
9fbc7d117b9aee98d748669646dd200c25a4122f
|
[
"WTFPL"
] | 3 |
2021-11-12T09:20:21.000Z
|
2022-02-18T11:34:33.000Z
|
cpp/ss_example.cpp
|
jieyaren/hello-world
|
9fbc7d117b9aee98d748669646dd200c25a4122f
|
[
"WTFPL"
] | 1 |
2021-03-08T03:23:04.000Z
|
2021-03-08T03:23:04.000Z
|
cpp/ss_example.cpp
|
jieyaren/hello-world
|
9fbc7d117b9aee98d748669646dd200c25a4122f
|
[
"WTFPL"
] | null | null | null |
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
int main()
{
stringstream ss;
ss << "there are " << 9 << "apple in my cart";
cout << ss.str() << endl;
ss.str("");
ss << showbase << hex << 16;
cout << "ss = " << ss.str() << endl;
ss.str("");
ss << 3.14;
cout << "ss = " << ss.str() << endl;
}
| 16.809524 | 47 | 0.541076 |
jieyaren
|
fb364774eda945e18763b58742a6b965aa847895
| 1,196 |
cpp
|
C++
|
stl/pqueue_fns.cpp
|
Praneeth-rdy/cp-practice
|
26ef8beae3708a0867ed332d308743b990f0a68c
|
[
"MIT"
] | null | null | null |
stl/pqueue_fns.cpp
|
Praneeth-rdy/cp-practice
|
26ef8beae3708a0867ed332d308743b990f0a68c
|
[
"MIT"
] | null | null | null |
stl/pqueue_fns.cpp
|
Praneeth-rdy/cp-practice
|
26ef8beae3708a0867ed332d308743b990f0a68c
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <queue>
using namespace std;
int main(){
// declaring max pqueue
priority_queue<int> maxpq;
// declaring min pqueue
// any container which supports the following opreations can be used to implement priority_queue
// empty(), push_back(), size(), pop_back(), front()
// replace the container you want in place of vector
priority_queue<int, vector<int>, greater<int>> minpq;
// operations on max pq
// inserting a new element into priority queue
maxpq.push(10);
maxpq.push(20);
maxpq.push(30);
// getting top element
cout << "maxpq top element: " << maxpq.top() << "\n";
// removing top element which is the highest value element
maxpq.pop();
// operations on minpq
minpq.push(30);
minpq.push(100);
minpq.push(25);
minpq.push(40);
// getting the top element
cout << "minpq top element: " << minpq.top() << "\n";
return 0;
}
/*
maxpqueue is a container adaptor
heap property is always maintained
first element is always the greatest element (max maxpqueue)
internally uses functions of heap like make_heap, push_heap and pop_heap to maintain heap structure
*/
/*
*/
| 26 | 100 | 0.668896 |
Praneeth-rdy
|
fb3a6a685fb315858b43119fbf797eac5c326813
| 2,575 |
cpp
|
C++
|
Vishv_GE/Framework/AI/Src/WorldIO.cpp
|
InFaNsO/Vishv_GameEngine
|
e721afa899fb8715e52cdd67c2656ba6cce7ffed
|
[
"MIT"
] | 1 |
2021-12-19T02:06:12.000Z
|
2021-12-19T02:06:12.000Z
|
Vishv_GE/Framework/AI/Src/WorldIO.cpp
|
InFaNsO/Vishv_GameEngine
|
e721afa899fb8715e52cdd67c2656ba6cce7ffed
|
[
"MIT"
] | null | null | null |
Vishv_GE/Framework/AI/Src/WorldIO.cpp
|
InFaNsO/Vishv_GameEngine
|
e721afa899fb8715e52cdd67c2656ba6cce7ffed
|
[
"MIT"
] | null | null | null |
#include "Precompiled.h"
#include "WorldIO.h"
#include "World.h"
namespace
{
std::string ToString(const Vishv::Math::Shapes::Capsule& cap)
{
std::string txt;
txt += "Position: " + cap.mTransform.Position().ToString() + "\n";
txt += "Rotation: " + cap.mTransform.Rotation().ToString() + "\n";
txt += "Radius: " + std::to_string(cap.mRadius) + "\n";
txt += "Height: " + std::to_string(cap.GetHeight()) + "\n";
return std::move(txt);
}
std::string ToString(const Vishv::Math::Shapes::Cuboid& c)
{
std::string txt;
txt += "Position: " + c.mTransform.Position().ToString() + "\n";
txt += "Rotation: " + c.mTransform.Rotation().ToString() + "\n";
txt += "LengthX: " + std::to_string(c.GetLengthX()) + "\n";
txt += "LengthY: " + std::to_string(c.GetLengthY()) + "\n";
txt += "LengthZ: " + std::to_string(c.GetLengthZ()) + "\n";
return std::move(txt);
}
}
void Vishv::AI::WorldIO::Save(std::filesystem::path path, const World & world)
{
std::fstream file;
file.open(path, std::ios::out);
file.close();
file.open(path);
if (!file.is_open())
return;
file << "NumberObstacles: " << world.GetObstacles().size() << std::endl;
file << "NumberWalls: " << world.GetWalls().size() << std::endl;
for (size_t i = 0; i < world.GetObstacles().size(); ++i)
file << ToString(world.GetObstacles()[i]);
for (size_t i = 0; i < world.GetWalls().size(); ++i)
file << ToString(world.GetWalls()[i]);
}
void Vishv::AI::WorldIO::Load(std::filesystem::path path, World & world)
{
std::fstream file;
file.close();
file.open(path);
if (!file.is_open())
return;
size_t maxObs, maxWall;
std::string holder;
file >> holder >> maxObs >> holder >> maxWall;
world.GetObstacles().reserve(maxObs);
world.GetWalls().reserve(maxWall);
for (size_t i = 0; i < maxObs; ++i)
{
World::Obstacle obs;
Math::Vector3 pr;
Math::Quaternion q;
file >> holder >> pr.x >> pr.y >> pr.z;
obs.mTransform.mPosition = pr;
file >> holder >> q.w >> q.x >> q.y >> q.z;
obs.mTransform.SetRotation(std::move(q));
float h;
file >> holder >> obs.mRadius >> holder >> h;
obs.SetHeight(h);
world.Register(obs);
}
for (size_t i = 0; i < maxWall; ++i)
{
World::Wall wall;
Math::Vector3 pr;
Math::Quaternion q;
file >> holder >> pr.x >> pr.y >> pr.z;
wall.mTransform.mPosition = pr;
file >> holder >> q.w >> q.x >> q.y >> q.z;
wall.mTransform.SetRotation(std::move(q));
file >> holder >> pr.x >> holder >> pr.y >> holder >> pr.z;
wall.SetLengthX(pr.x);
wall.SetLengthY(pr.y);
wall.SetLengthZ(pr.z);
world.Register(wall);
}
}
| 26.010101 | 78 | 0.609709 |
InFaNsO
|
fb3c7db2c5f5eacc5dffc352ec7f72f84c430573
| 5,891 |
cpp
|
C++
|
extensions/opengl/examples/glpixmap/glbox.cpp
|
sandsmark/qt1
|
e62eef42291be80065a7f824530aa42b79917a8d
|
[
"Xnet",
"X11"
] | 18 |
2018-02-16T16:57:26.000Z
|
2022-02-10T21:23:47.000Z
|
extensions/opengl/examples/glpixmap/glbox.cpp
|
sandsmark/qt1
|
e62eef42291be80065a7f824530aa42b79917a8d
|
[
"Xnet",
"X11"
] | 2 |
2018-08-12T12:46:38.000Z
|
2020-06-19T16:30:06.000Z
|
extensions/opengl/examples/glpixmap/glbox.cpp
|
sandsmark/qt1
|
e62eef42291be80065a7f824530aa42b79917a8d
|
[
"Xnet",
"X11"
] | 7 |
2018-06-22T01:17:58.000Z
|
2021-09-02T21:05:28.000Z
|
/****************************************************************************
** $Id: glbox.cpp,v 1.1.2.3 1999/02/01 12:17:42 aavit Exp $
**
** Implementation of GLBox
** This is a simple QGLWidget displaying a box
**
** The OpenGL code is mostly borrowed from Brian Pauls "spin" example
** in the Mesa distribution
**
****************************************************************************/
#include "glbox.h"
#include <math.h>
/*!
Create a GLBox widget
*/
GLBox::GLBox( QWidget* parent, const char* name, const QGLWidget* shareWidget )
: QGLWidget( parent, name, shareWidget )
{
xRot = yRot = zRot = 0.0; // default object rotation
scale = 1.5; // default object scale
}
/*!
Create a GLBox widget
*/
GLBox::GLBox( const QGLFormat& format, QWidget* parent, const char* name,
const QGLWidget* shareWidget )
: QGLWidget( format, parent, name, shareWidget )
{
xRot = yRot = zRot = 0.0; // default object rotation
scale = 1.5; // default object scale
}
/*!
Release allocated resources
*/
GLBox::~GLBox()
{
glDeleteLists( object, 1 );
}
/*!
Set up the OpenGL rendering state, and define display list
*/
void GLBox::initializeGL()
{
glClearColor( 0.0, 0.5, 0.0, 0.0 ); // Let OpenGL clear to green
object = makeObject(); // Make display list
glEnable( GL_DEPTH_TEST );
}
/*!
Set up the OpenGL view port, matrix mode, etc.
*/
void GLBox::resizeGL( int w, int h )
{
glViewport( 0, 0, (GLint)w, (GLint)h );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 200.0);
}
/*!
Paint the box. The actual openGL commands for drawing the box are
performed here.
*/
void GLBox::paintGL()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glTranslatef( 0.0, 0.0, -3.0 );
glScalef( scale, scale, scale );
glRotatef( xRot, 1.0, 0.0, 0.0 );
glRotatef( yRot, 0.0, 1.0, 0.0 );
glRotatef( zRot, 0.0, 0.0, 1.0 );
glCallList( object );
}
/*!
Generate an OpenGL display list for the object to be shown, i.e. the box
*/
GLuint GLBox::makeObject()
{
GLuint list;
list = glGenLists( 1 );
glNewList( list, GL_COMPILE );
GLint i, j, rings, sides;
float theta1, phi1, theta2, phi2;
float v0[03], v1[3], v2[3], v3[3];
float t0[03], t1[3], t2[3], t3[3];
float n0[3], n1[3], n2[3], n3[3];
float innerRadius=0.4;
float outerRadius=0.8;
float scalFac;
double pi = 3.14159265358979323846;
rings = 8;
sides = 10;
scalFac=1/(outerRadius*2);
for (i = 0; i < rings; i++) {
theta1 = (float)i * 2.0 * pi / rings;
theta2 = (float)(i + 1) * 2.0 * pi / rings;
for (j = 0; j < sides; j++) {
phi1 = (float)j * 2.0 * pi / sides;
phi2 = (float)(j + 1) * 2.0 * pi / sides;
v0[0] = cos(theta1) * (outerRadius + innerRadius * cos(phi1));
v0[1] = -sin(theta1) * (outerRadius + innerRadius * cos(phi1));
v0[2] = innerRadius * sin(phi1);
v1[0] = cos(theta2) * (outerRadius + innerRadius * cos(phi1));
v1[1] = -sin(theta2) * (outerRadius + innerRadius * cos(phi1));
v1[2] = innerRadius * sin(phi1);
v2[0] = cos(theta2) * (outerRadius + innerRadius * cos(phi2));
v2[1] = -sin(theta2) * (outerRadius + innerRadius * cos(phi2));
v2[2] = innerRadius * sin(phi2);
v3[0] = cos(theta1) * (outerRadius + innerRadius * cos(phi2));
v3[1] = -sin(theta1) * (outerRadius + innerRadius * cos(phi2));
v3[2] = innerRadius * sin(phi2);
n0[0] = cos(theta1) * (cos(phi1));
n0[1] = -sin(theta1) * (cos(phi1));
n0[2] = sin(phi1);
n1[0] = cos(theta2) * (cos(phi1));
n1[1] = -sin(theta2) * (cos(phi1));
n1[2] = sin(phi1);
n2[0] = cos(theta2) * (cos(phi2));
n2[1] = -sin(theta2) * (cos(phi2));
n2[2] = sin(phi2);
n3[0] = cos(theta1) * (cos(phi2));
n3[1] = -sin(theta1) * (cos(phi2));
n3[2] = sin(phi2);
t0[0] = v0[0]*scalFac + 0.5;
t0[1] = v0[1]*scalFac + 0.5;
t0[2] = v0[2]*scalFac + 0.5;
t1[0] = v1[0]*scalFac + 0.5;
t1[1] = v1[1]*scalFac + 0.5;
t1[2] = v1[2]*scalFac + 0.5;
t2[0] = v2[0]*scalFac + 0.5;
t2[1] = v2[1]*scalFac + 0.5;
t2[2] = v2[2]*scalFac + 0.5;
t3[0] = v3[0]*scalFac + 0.5;
t3[1] = v3[1]*scalFac + 0.5;
t3[2] = v3[2]*scalFac + 0.5;
glColor3f( (GLfloat) ((i+j) % 2),
(GLfloat) 0.0,
(GLfloat) 0.0 );
glBegin(GL_POLYGON);
glNormal3fv(n3); glTexCoord3fv(t3); glVertex3fv(v3);
glNormal3fv(n2); glTexCoord3fv(t2); glVertex3fv(v2);
glNormal3fv(n1); glTexCoord3fv(t1); glVertex3fv(v1);
glNormal3fv(n0); glTexCoord3fv(t0); glVertex3fv(v0);
glEnd();
}
}
glEndList();
return list;
}
/*!
Set the rotation angle of the object to \e degrees around the X axis.
*/
void GLBox::setXRotation( int degrees )
{
xRot = (GLfloat)(degrees % 360);
updateGL();
}
/*!
Set the rotation angle of the object to \e degrees around the Y axis.
*/
void GLBox::setYRotation( int degrees )
{
yRot = (GLfloat)(degrees % 360);
updateGL();
}
/*!
Set the rotation angle of the object to \e degrees around the Z axis.
*/
void GLBox::setZRotation( int degrees )
{
zRot = (GLfloat)(degrees % 360);
updateGL();
}
/*!
Sets the rotation angles of this object to that of \a fromBox
*/
void GLBox::copyRotation( const GLBox& fromBox )
{
xRot = fromBox.xRot;
yRot = fromBox.yRot;
zRot = fromBox.zRot;
}
| 24.143443 | 79 | 0.532337 |
sandsmark
|
fb3dea7527198b4818d176f7146d3dc90932d1be
| 3,279 |
cpp
|
C++
|
src/base/muduo/base/common/logfile.cpp
|
sbfhy/server1
|
b9597a3783a0f7bb929b4b9fa7f621c81740b056
|
[
"BSD-3-Clause"
] | null | null | null |
src/base/muduo/base/common/logfile.cpp
|
sbfhy/server1
|
b9597a3783a0f7bb929b4b9fa7f621c81740b056
|
[
"BSD-3-Clause"
] | null | null | null |
src/base/muduo/base/common/logfile.cpp
|
sbfhy/server1
|
b9597a3783a0f7bb929b4b9fa7f621c81740b056
|
[
"BSD-3-Clause"
] | null | null | null |
#include "muduo/base/common/logfile.h"
#include "muduo/base/common/logging.h"
#include "muduo/base/common/file_util.h"
#include "muduo/base/common/process_info.h"
#include "define/define_new.h"
#include <assert.h>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <libgen.h>
using namespace muduo;
std::string LogFile::s_fileDir = "log/";
std::unique_ptr<muduo::LogFile> g_logFile;
void outputFunc(const CHAR* msg, SDWORD len)
{
g_logFile->append(msg, len);
}
void flushFunc()
{
g_logFile->flush();
}
LogFile::LogFile(const std::string& basename, off_t rollSize,
bool threadSafe, SDWORD flushInterval, SDWORD checkEveryN)
: m_basename(basename)
, m_rollSize(rollSize)
, m_flushInterval(flushInterval)
, m_checkEveryN(checkEveryN)
, m_count(0)
, m_mutex(threadSafe ? NEW MutexLock : nullptr)
, m_startOfPeriod(0)
, m_lastRoll(0)
, m_lastFlush(0)
{
assert(basename.find('/') == std::string::npos);
RollFile();
}
LogFile::~LogFile() = default;
void LogFile::append(const CHAR* logline, SDWORD len)
{
if (m_mutex)
{
MutexLockGuard lock(*m_mutex);
append_unlocked(logline, len);
}
else
{
append_unlocked(logline, len);
}
}
void LogFile::flush()
{
if (m_mutex)
{
MutexLockGuard lock(*m_mutex);
m_file->flush();
}
else
{
m_file->flush();
}
}
void LogFile::append_unlocked(const CHAR* logline, SDWORD len)
{
m_file->append(logline, len);
if (m_file->getWrittenBytes() > m_rollSize)
{
RollFile();
}
else
{
++ m_count;
if (m_count >= m_checkEveryN)
{
m_count = 0;
time_t now = ::time(nullptr);
time_t thisPeriod = now / kRollPerSeconds * kRollPerSeconds;
if (thisPeriod != m_startOfPeriod)
{
RollFile();
}
else if (now - m_lastFlush > m_flushInterval)
{
m_lastFlush = now;
m_file->flush();
}
}
}
}
bool LogFile::RollFile()
{
time_t now = 0;
std::string filename = getLogFileName(m_basename, &now);
time_t start = now / kRollPerSeconds * kRollPerSeconds;
if (now > m_lastRoll)
{
m_lastRoll = now;
m_lastFlush = now;
m_startOfPeriod = start;
m_file.reset(NEW FileUtil::AppendFile(LogFile::s_fileDir + filename));
return true;
}
return false;
}
void LogFile::SetLogFile(const char* exePath, const char* baseName, off_t rollSize)
{
g_logFile.reset(NEW muduo::LogFile(baseName, rollSize));
muduo::Logger::setOutputFunc(outputFunc);
muduo::Logger::setFlushFunc(flushFunc);
}
void LogFile::setLogFileDir(const char* fileDir)
{
s_fileDir = ::dirname(const_cast<char*>(fileDir));
s_fileDir += "/log/";
}
std::string LogFile::getLogFileName(const std::string& basename, time_t* now)
{
std::string filename;
filename.reserve(basename.size() + 64);
filename = basename;
CHAR timebuf[32];
struct tm tm;
*now = time(nullptr);
//gmtime_r(now, &tm); // FIXME: localtime_r ?
localtime_r(now, &tm);
strftime(timebuf, sizeof timebuf, "_%Y%m%d_%H%M%S_", &tm);
filename += timebuf;
// filename += ProcessInfo::hostname();
CHAR pidbuf[32];
snprintf(pidbuf, sizeof pidbuf, "%d", ProcessInfo::pid());
filename += pidbuf;
filename += ".log";
return filename;
}
| 21.715232 | 83 | 0.652028 |
sbfhy
|
fb41daf612b10ada62a4d52accc687895a383c62
| 8,237 |
cpp
|
C++
|
anet/test/sockettf.cpp
|
imyouxia/Source
|
624df9ffeb73d9ce918d5f7ef77bae6b9919e30a
|
[
"MIT"
] | 115 |
2016-08-02T02:07:12.000Z
|
2022-03-04T01:44:13.000Z
|
anet/test/sockettf.cpp
|
EmpTan/Source
|
624df9ffeb73d9ce918d5f7ef77bae6b9919e30a
|
[
"MIT"
] | null | null | null |
anet/test/sockettf.cpp
|
EmpTan/Source
|
624df9ffeb73d9ce918d5f7ef77bae6b9919e30a
|
[
"MIT"
] | 46 |
2016-08-09T09:54:27.000Z
|
2021-03-05T10:47:55.000Z
|
#include <iostream>
#include <string>
#include "sockettf.h"
#include <anet/anet.h>
#include <unistd.h>
#include <anet/serversocket.h>
#include <anet/log.h>
#include <signal.h>
using namespace std;
namespace anet {
CPPUNIT_TEST_SUITE_REGISTRATION(SocketTF);
class PlainConnectRunnable : public Runnable {
public:
void run(Thread* thread, void *args) {
Socket *socket = (Socket *) args;
CPPUNIT_ASSERT(socket);
CPPUNIT_ASSERT(socket->connect());
}
};
struct SocketPair {
ServerSocket * serverSocket;
Socket *acceptedSocket;
};
class PlainServerRunnable : public Runnable {
public:
void run(Thread* thread, void *args) {
SocketPair *sockpair = (SocketPair*)args;
CPPUNIT_ASSERT(sockpair->serverSocket);
sockpair->acceptedSocket = sockpair->serverSocket->accept();
CPPUNIT_ASSERT(sockpair->acceptedSocket);
}
};
struct PlainReadArgs {
Socket *socket;
char * buffer;
int bytes;
int bytesRead;
};
class PlainReadRunnable : public Runnable {
public:
void run(Thread* thread, void *args) {
PlainReadArgs *myArgs = static_cast<PlainReadArgs*> (args);
myArgs->bytesRead = myArgs->socket->read(myArgs->buffer,
myArgs->bytes);
}
};
void SocketTF::setUp() {
}
void SocketTF::tearDown() {
}
void SocketTF::testSetGetAddress() {
Socket socket;
char result[32];
string expect;
//testing invalid address
CPPUNIT_ASSERT(!socket.setAddress("NoSushAddress.james.zhang",12345));
CPPUNIT_ASSERT(socket.setAddress(NULL, 12345));
CPPUNIT_ASSERT(socket.getAddr(result, 10));
CPPUNIT_ASSERT_EQUAL(string("0.0.0.0:1"), string(result));
CPPUNIT_ASSERT(socket.setAddress("", 0));
CPPUNIT_ASSERT(socket.setAddress("localhost", 12345));
CPPUNIT_ASSERT(socket.getAddr(result, 32));
CPPUNIT_ASSERT_EQUAL(string("127.0.0.1:12345"), string(result));
CPPUNIT_ASSERT(socket.setAddress("127.0.0.1", -1));
CPPUNIT_ASSERT(socket.getAddr(result, 32));
CPPUNIT_ASSERT_EQUAL(string("127.0.0.1:65535"), string(result));
CPPUNIT_ASSERT(socket.setAddress("202.165.102.205", 12345));
CPPUNIT_ASSERT(socket.setAddress("www.yahoo.com", 12345));
CPPUNIT_ASSERT(socket.setAddress("g.cn", 12345));
}
void SocketTF::testReadWrite() {
Socket socket;
ServerSocket serverSocket;
char data[]="Some Data";
char output[1024];
CPPUNIT_ASSERT_EQUAL(-1,socket.write(data, strlen(data)));
CPPUNIT_ASSERT(socket.setAddress("localhost", 11234));
CPPUNIT_ASSERT(serverSocket.setAddress("localhost", 11234));
CPPUNIT_ASSERT(serverSocket.listen());
SocketPair socketPair;
socketPair.serverSocket=&serverSocket;
Thread tc, ts;
PlainConnectRunnable pcr;
PlainServerRunnable psr;
tc.start(&pcr,&socket);//connect
ts.start(&psr,&socketPair);//accept
ts.join();
tc.join();
Socket *acceptedSocket = socketPair.acceptedSocket;
acceptedSocket->setSoBlocking(false);
socket.setSoBlocking(false);
CPPUNIT_ASSERT(acceptedSocket);
CPPUNIT_ASSERT_EQUAL(9, socket.write(data, strlen(data)));
CPPUNIT_ASSERT_EQUAL(9, acceptedSocket->read(output, 10));
CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(NULL, 3));
CPPUNIT_ASSERT_EQUAL(string(data, 9), string(output, 9));
CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(output,10));
CPPUNIT_ASSERT_EQUAL(EAGAIN, Socket::getLastError());
CPPUNIT_ASSERT_EQUAL(3, socket.write(data, 3));
CPPUNIT_ASSERT_EQUAL(3, acceptedSocket->read(output, 10));
CPPUNIT_ASSERT_EQUAL(4, acceptedSocket->write(data, 4));
CPPUNIT_ASSERT_EQUAL(4, socket.read(output, 10));
CPPUNIT_ASSERT_EQUAL(string(data, 4), string(output, 4));
CPPUNIT_ASSERT_EQUAL(-1, socket.write(NULL, 3));
CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(NULL, 3));
acceptedSocket->close();
CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(output, 10));
CPPUNIT_ASSERT_EQUAL(0, socket.read(output,3));
/**@note: we can write to socket whose peer was closed*/
CPPUNIT_ASSERT_EQUAL(3, socket.write(data,3));
delete acceptedSocket;
socket.close();
CPPUNIT_ASSERT_EQUAL(-1, socket.write(data, 3));
tc.start(&pcr,&socket);//connect
ts.start(&psr,&socketPair);//accept
ts.join();
tc.join();
acceptedSocket = socketPair.acceptedSocket;
acceptedSocket->setSoBlocking(false);
CPPUNIT_ASSERT(acceptedSocket);
acceptedSocket->shutdown();
CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(output, 10));
signal(SIGPIPE, SIG_IGN);
CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->write(data, 10));
/**
* @todo need to handle socket shutdown?
* CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->read(output, 10));
* CPPUNIT_ASSERT_EQUAL(-1, acceptedSocket->write(data, 10));
*/
socket.close();
delete acceptedSocket;
CPPUNIT_ASSERT(socket.createUDP());
CPPUNIT_ASSERT_EQUAL(-1, socket.write(data, 3));
CPPUNIT_ASSERT(socket.setAddress("localhost",22));
CPPUNIT_ASSERT(socket.connect());
CPPUNIT_ASSERT_EQUAL(5, socket.write(data, 5));
/**
* @todo need more UDP interface
* CPPUNIT_ASSERT_EQUAL(string("Need More"), string("UDP Interface"));
*/
socket.close();
serverSocket.close();
acceptedSocket->close();
}
void SocketTF::testConnect() {
char data[] = "Short Data";
char output[256];
Socket socket;
CPPUNIT_ASSERT(!socket.connect());
CPPUNIT_ASSERT(socket.setAddress("localhost",12346));
CPPUNIT_ASSERT(!socket.connect());
ServerSocket serverSocket;
ServerSocket serverSocket2;
CPPUNIT_ASSERT(!serverSocket.listen());
CPPUNIT_ASSERT(serverSocket.setAddress("localhost",12346));
CPPUNIT_ASSERT(serverSocket2.setAddress("localhost",12346));
CPPUNIT_ASSERT(serverSocket.listen());
CPPUNIT_ASSERT(serverSocket.setSoBlocking(false));
CPPUNIT_ASSERT(!serverSocket2.listen());
CPPUNIT_ASSERT(socket.connect());
CPPUNIT_ASSERT(socket.setSoBlocking(false));
/**
* @todo should we detect if no body accept()?
* CPPUNIT_ASSERT_EQUAL(-1, socket.write(data,3));
*/
CPPUNIT_ASSERT_EQUAL(3, socket.write(data,3));
Socket *acceptedSocket = serverSocket.accept();
CPPUNIT_ASSERT(acceptedSocket);
CPPUNIT_ASSERT(acceptedSocket->setSoBlocking(false));
ANET_LOG(DEBUG,"Before acceptedSocket->read(output,256)");
CPPUNIT_ASSERT_EQUAL(3, acceptedSocket->read(output,256));
ANET_LOG(DEBUG,"After acceptedSocket->read(output,256)");
CPPUNIT_ASSERT_EQUAL(string(data,3), string(output,3));
ANET_LOG(DEBUG,"Before serverSocket.accept()");
Socket *acceptedSocket2 = serverSocket.accept();
ANET_LOG(DEBUG,"After serverSocket.accept()");
CPPUNIT_ASSERT(!acceptedSocket2);
delete acceptedSocket;
acceptedSocket = NULL;
CPPUNIT_ASSERT(socket.reconnect());
acceptedSocket2 = serverSocket.accept();
CPPUNIT_ASSERT(acceptedSocket2);
CPPUNIT_ASSERT(acceptedSocket2->setSoBlocking(true));
Thread thread;
PlainReadRunnable readRunnable;
PlainReadArgs args;
args.socket = acceptedSocket2;
args.buffer = output;
args.bytes = 8;
thread.start(&readRunnable, &args);
socket.setTcpNoDelay(true);
sleep(1);
CPPUNIT_ASSERT_EQUAL(3, socket.write(data,3));
CPPUNIT_ASSERT_EQUAL(5, socket.write(data+3, 5));
thread.join();
/**Blocking read will be blocked when there is no data to read!
* So we should expect args.bytes > 0*/
CPPUNIT_ASSERT(args.bytesRead > 0);
CPPUNIT_ASSERT_EQUAL(string(data,args.bytesRead),
string(output,args.bytesRead));
delete acceptedSocket2;
}
void SocketTF::testListenZeroIPZeroPort() {
ANET_LOG(DEBUG, "testListenZeroIPZeroPort");
ServerSocket server;
CPPUNIT_ASSERT(server.setAddress("0.0.0.0", 0));
char result[32];
CPPUNIT_ASSERT(server.getAddr(result, 32));
CPPUNIT_ASSERT_EQUAL(string("0.0.0.0:0"), string(result));
CPPUNIT_ASSERT(!server.getAddr(result, 32, true));
CPPUNIT_ASSERT(server.listen());
CPPUNIT_ASSERT(server.getAddr(result, 32, true));
ANET_LOG(DEBUG, "active address: %s", result);
CPPUNIT_ASSERT(string("0.0.0.0:0") != string(result));
}
}
| 34.902542 | 74 | 0.697098 |
imyouxia
|
fb43d9eaafd6fd2a5e12f061ca4e99e77d7e947f
| 3,617 |
cpp
|
C++
|
src/structures/congruence_atom.cpp
|
Ezibenroc/satsolver
|
5f58b8f9502090f05cbc2351304a289530b74f63
|
[
"MIT"
] | 1 |
2017-11-29T00:46:23.000Z
|
2017-11-29T00:46:23.000Z
|
src/structures/congruence_atom.cpp
|
Ezibenroc/satsolver
|
5f58b8f9502090f05cbc2351304a289530b74f63
|
[
"MIT"
] | null | null | null |
src/structures/congruence_atom.cpp
|
Ezibenroc/satsolver
|
5f58b8f9502090f05cbc2351304a289530b74f63
|
[
"MIT"
] | null | null | null |
#include <sstream>
#include <cassert>
#include "structures/congruence_atom.h"
#define CA theorysolver::CongruenceAtom
#define SPCA std::shared_ptr<CA>
using namespace theorysolver;
Term::Term(unsigned int symbol_id) : type(Term::SYMBOL), symbol_id(symbol_id), function_name(), arguments() {
}
Term::Term(std::string function_name, std::vector<std::shared_ptr<Term>> arguments) : type(Term::FUNCTION), symbol_id(0), function_name(function_name), arguments(arguments) {
}
Term::Term(const Term &t) : type(t.type), symbol_id(t.symbol_id), function_name(t.function_name), arguments(t.arguments) {
}
std::string Term::to_string() const {
if (this->type == Term::SYMBOL)
return "x" + std::to_string(this->symbol_id);
else {
std::ostringstream oss;
oss << this->function_name + "(";
for (unsigned i=0; i<this->arguments.size(); i++) {
if (i)
oss << ", ";
oss << "x" + this->arguments[i]->to_string();
}
oss << ")";
return oss.str();
}
}
bool CongruenceAtom::is_atom_variable(std::string variable) {
return variable.c_str()[0] == '#';
}
bool CongruenceAtom::is_atom_literal(const std::map<int, std::string> &literal_to_name, unsigned int literal) {
return CongruenceAtom::is_atom_variable(literal_to_name.at(literal));
}
unsigned int CongruenceAtom::atom_id_from_literal(const std::map<int, std::string> &variable_to_name, unsigned int literal) {
unsigned int atom_id;
atom_id = atoi(variable_to_name.at(literal).c_str()+1);
return atom_id;
}
std::string CongruenceAtom::variable_name_from_atom_id(unsigned long int atom_id) {
return "#" + std::to_string(atom_id);
}
int CongruenceAtom::literal_from_atom_id(const std::map<std::string, int> &name_to_variable, unsigned int atom_id) {
return name_to_variable.at("#" + std::to_string(atom_id));
}
SPCA CongruenceAtom::SPCA_from_literal(const CA_list &literal_to_CA, std::map<int, std::string> &variable_to_name, unsigned int literal) {
unsigned int atom_id = CongruenceAtom::atom_id_from_literal(variable_to_name, literal);
assert(atom_id > 0);
assert(atom_id <= literal_to_CA.size());
return literal_to_CA[atom_id-1];
}
long unsigned int CongruenceAtom::add_CA(CA_list &literal_to_CA, Term &left, Operator op, Term &right) {
literal_to_CA.push_back(SPCA(new CA(std::shared_ptr<Term>(new Term(left)), op, std::shared_ptr<Term>(new Term(right)))));
return literal_to_CA.size();
}
std::shared_ptr<CongruenceAtom> CongruenceAtom::SPCA_from_variable(const CA_list &literal_to_CA, std::string variable) {
return literal_to_CA[atoi(variable.c_str()+1)-1];
}
bool Term::operator==(const Term &that) const {
if (this->type != that.type)
return false;
else if (this->type == Term::SYMBOL)
return this->symbol_id == that.symbol_id;
else if (this->type == Term::FUNCTION) {
if (this->arguments.size() != that.arguments.size())
return false;
if (this->function_name != that.function_name)
return false;
for (unsigned i=0; i<this->arguments.size(); i++)
if (!(this->arguments[i] == that.arguments[i]))
return false;
return true;
}
else
assert(false);
}
CongruenceAtom::CongruenceAtom(std::shared_ptr<Term> left, enum Operator op, std::shared_ptr<Term> right) : left(left), right(right), op(op), canonical(NULL) {
}
std::string CongruenceAtom::to_string() const {
return this->left->to_string() + (this->op == CongruenceAtom::EQUAL ? "=" : "!=") + this->right->to_string();
}
| 36.17 | 174 | 0.673763 |
Ezibenroc
|
fb440012eb7e1eb2fac399bc134e1987affba322
| 2,670 |
cpp
|
C++
|
tests/test.cpp
|
summersoul17/Lab-12-refactoring-summersoul
|
9d516191808f33ba41ce6ba7ecb2f4fea389f879
|
[
"MIT"
] | null | null | null |
tests/test.cpp
|
summersoul17/Lab-12-refactoring-summersoul
|
9d516191808f33ba41ce6ba7ecb2f4fea389f879
|
[
"MIT"
] | null | null | null |
tests/test.cpp
|
summersoul17/Lab-12-refactoring-summersoul
|
9d516191808f33ba41ce6ba7ecb2f4fea389f879
|
[
"MIT"
] | null | null | null |
// Copyright 2020 Your Name <your_email>
#include <gmock/gmock.h>
#include <page_container.hpp>
#include "stat_sender_test.hpp"
#include <used_memory.hpp>
TEST(MemoryUsage, MemUsingTest) {
std::vector<std::string> old_raw_data{ "first" },
new_raw_data {
"first", "second", "third", "fourth"
};
used_memory memory;
memory.on_raw_data_load(old_raw_data, new_raw_data);
EXPECT_EQ(memory.used(), 45);
memory.clear();
std::vector<item> old_data{},
new_data{
{1, "rand", 10},
{2, "rand", 20},
{3, "rand", 30}
};
memory.on_data_load(old_data, new_data);
EXPECT_EQ(memory.used(), 69);
}
void prepare_stringstream(std::stringstream& ss, size_t lines = 20){
for (size_t i = 0; i < lines; ++i) {
ss << (i + 1) << " cor " << (i < 6 ? 25 : 50) << '\n';
}
ss << 21 << " inc "
<< "ls" << '\n';
ss << 22 << " inc "
<< "la" << '\n';
}
TEST(PageContainer_Test, Data_Test) {
srand(time(nullptr));
std::stringstream ss{};
prepare_stringstream(ss);
page_container page;
page.load_raw_data(ss);
page.load_data(0);
EXPECT_EQ(page.data_size(), 20);
}
TEST(PageContainer_Test, AsyncSend_Test) {
using ::testing::_;
using ::testing::AtLeast;
srand(time(nullptr));
std::stringstream ss{};
prepare_stringstream(ss);
used_memory* used = new used_memory();
mock_stat_sender* sender = new mock_stat_sender();
page_container<mock_stat_sender> page(used, sender);
page.load_raw_data(ss);
EXPECT_CALL(*sender,
async_send(_, std::string_view{"/items/loaded"}))
.Times(2);
EXPECT_CALL(*sender,
async_send(_, std::string_view{"/items/skipped"}))
.Times(12);
page.load_data(0);
page.load_data(30);
}
TEST(PageContainer_Test, AlreadySeen){
std::stringstream ss{};
prepare_stringstream(ss);
ss << 20 << " cop " << 20 << '\n';
page_container page{};
page.load_raw_data(ss);
EXPECT_THROW(page.load_data(0), std::runtime_error);
}
TEST(PageContainer_Test, EmptyFile){
std::ifstream file_{"empty.txt"};
std::ofstream empty{"empty.txt"};
page_container page{};
EXPECT_THROW(page.load_raw_data(file_), std::runtime_error);
empty.close();
}
TEST(PageContainer_Test, CorruptedFile){
std::ifstream file_;
file_.close();
page_container page{};
EXPECT_THROW(page.load_raw_data(file_), std::runtime_error);
}
TEST(PageContainer_Test, TooSmallInputStream){
std::stringstream ss{};
prepare_stringstream(ss, 5);
page_container page{};
EXPECT_THROW(page.load_raw_data(ss), std::runtime_error);
}
TEST(PageContainer_Test, TooSmallInputStream_LoadData){
std::stringstream ss{};
prepare_stringstream(ss);
page_container page{};
page.load_raw_data(ss);
EXPECT_THROW(page.load_data(1000),std::runtime_error);
}
| 23.628319 | 68 | 0.693633 |
summersoul17
|
fb494cbd3333c238418b7175dbef8c17b8d67c33
| 179 |
cpp
|
C++
|
oj-noi-level1/1003.cpp
|
xiaji/noip-csp
|
7551478e848f3c3d2a4cc2d780d0efeedab67e6e
|
[
"MIT"
] | 1 |
2021-02-22T03:40:59.000Z
|
2021-02-22T03:40:59.000Z
|
oj-noi-level1/1003.cpp
|
xiaji/noip-csp
|
7551478e848f3c3d2a4cc2d780d0efeedab67e6e
|
[
"MIT"
] | null | null | null |
oj-noi-level1/1003.cpp
|
xiaji/noip-csp
|
7551478e848f3c3d2a4cc2d780d0efeedab67e6e
|
[
"MIT"
] | null | null | null |
/*
* guess number
*/
#include <iostream>
using namespace std;
int main() {
int input;
cin >> input;
input *= 1001;
input /= 7 * 11 * 13;
cout << input;
return 0;
}
| 11.933333 | 23 | 0.564246 |
xiaji
|
fb4a7a7be35a7eabb6eea80cd086885cc11ea557
| 2,633 |
hpp
|
C++
|
soccer/planning/primitives/PathSmoothing.hpp
|
kasohrab/robocup-software
|
73c92878baf960844b5a4b34c72804093f1ea459
|
[
"Apache-2.0"
] | null | null | null |
soccer/planning/primitives/PathSmoothing.hpp
|
kasohrab/robocup-software
|
73c92878baf960844b5a4b34c72804093f1ea459
|
[
"Apache-2.0"
] | null | null | null |
soccer/planning/primitives/PathSmoothing.hpp
|
kasohrab/robocup-software
|
73c92878baf960844b5a4b34c72804093f1ea459
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <Geometry2d/Point.hpp>
#include "planning/MotionConstraints.hpp"
namespace Planning {
/**
* @brief A spatial path with no time or angle information.
*/
class BezierPath {
public:
/**
* @brief Construct a bezier path for a curve with a given velocity, going
* through the specified points and with specified velocity at endpoints.
*
* @param points The points through which the final curve must pass. These
* will be used as the endpoints for consecutive Bezier segments. In
* total there will be points.size() - 1 curves. This must not be
* empty.
* @param vi The initial velocity, used as a tangent for the first curve.
* @param vf The final velocity, used as a tangent for the last curve.
* @param motion_constraints Linear constraints for motion. These are used
* to approximate the time between control points, which is later used
* to match up tangent vectors (approximately) with velocities.
*/
BezierPath(const std::vector<Geometry2d::Point>& points,
Geometry2d::Point vi, Geometry2d::Point vf,
MotionConstraints motion_constraints);
/**
* @brief Evaluate the path at a particular instant drawn from [0, 1].
* Calculates only those values requested (by passing in a non-null
* pointer).
*
* @param s The index to sample along, in the range of [0, 1].
* @param position Output parameter for the position at s, if non-null.
* @param tangent Output parameter for the tangent vector at s, if non-null.
* @param curvature Output parameter for the curvature at s, if non-null.
*/
void Evaluate(double s, Geometry2d::Point* position = nullptr,
Geometry2d::Point* tangent = nullptr,
double* curvature = nullptr) const;
/**
* @brief Whether or not this curve is empty.
*/
[[nodiscard]] bool empty() const { return control.empty(); }
/**
* @brief The number of cubic segments in this Bezier curve.
*/
[[nodiscard]] int size() const { return control.size(); }
/**
* @brief Control points for a Bezier curve.
*/
struct CubicBezierControlPoints {
Geometry2d::Point p0, p1, p2, p3;
CubicBezierControlPoints() = default;
CubicBezierControlPoints(Geometry2d::Point p0, Geometry2d::Point p1,
Geometry2d::Point p2, Geometry2d::Point p3)
: p0(p0), p1(p1), p2(p2), p3(p3) {}
};
private:
std::vector<CubicBezierControlPoints> control;
};
} // namespace Planning
| 35.581081 | 80 | 0.642993 |
kasohrab
|
fb4dcc170a16c5da307f59ff76b5678ecc8f51b6
| 5,209 |
cpp
|
C++
|
src/node_id.cpp
|
syoummer/boost.actor
|
58f35499bac8871b8f5b0b024246a467b63c6fb0
|
[
"BSL-1.0"
] | 2 |
2015-03-20T21:11:16.000Z
|
2020-01-20T08:05:41.000Z
|
src/node_id.cpp
|
syoummer/boost.actor
|
58f35499bac8871b8f5b0b024246a467b63c6fb0
|
[
"BSL-1.0"
] | null | null | null |
src/node_id.cpp
|
syoummer/boost.actor
|
58f35499bac8871b8f5b0b024246a467b63c6fb0
|
[
"BSL-1.0"
] | null | null | null |
/******************************************************************************\
* *
* ____ _ _ _ *
* | __ ) ___ ___ ___| |_ / \ ___| |_ ___ _ __ *
* | _ \ / _ \ / _ \/ __| __| / _ \ / __| __/ _ \| '__| *
* | |_) | (_) | (_) \__ \ |_ _ / ___ \ (__| || (_) | | *
* |____/ \___/ \___/|___/\__(_)_/ \_\___|\__\___/|_| *
* *
* *
* *
* Copyright (C) 2011 - 2014 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* *
* Distributed under the Boost Software License, Version 1.0. See *
* accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt *
\******************************************************************************/
#include <cstdio>
#include <cstring>
#include <sstream>
#include <unistd.h>
#include <sys/types.h>
#include "boost/actor/config.hpp"
#include "boost/actor/node_id.hpp"
#include "boost/actor/serializer.hpp"
#include "boost/actor/singletons.hpp"
#include "boost/actor/primitive_variant.hpp"
#include "boost/actor/io/middleman.hpp"
#include "boost/actor/detail/ripemd_160.hpp"
#include "boost/actor/detail/get_root_uuid.hpp"
#include "boost/actor/detail/get_mac_addresses.hpp"
#include "boost/actor/detail/safe_equal.hpp"
namespace {
std::uint8_t hex_char_value(char c) {
if (isdigit(c)) {
return static_cast<std::uint8_t>(c - '0');
}
else if (isalpha(c)) {
if (c >= 'a' && c <= 'f') {
return static_cast<std::uint8_t>((c - 'a') + 10);
}
else if (c >= 'A' && c <= 'F') {
return static_cast<std::uint8_t>((c - 'A') + 10);
}
}
throw std::invalid_argument(std::string("illegal character: ") + c);
}
} // namespace <anonymous>
namespace boost {
namespace actor {
void host_id_from_string(const std::string& hash,
node_id::host_id_type& node_id) {
if (hash.size() != (node_id.size() * 2)) {
throw std::invalid_argument("string argument is not a node id hash");
}
auto j = hash.c_str();
for (size_t i = 0; i < node_id.size(); ++i) {
// read two characters, each representing 4 bytes
auto& val = node_id[i];
val = static_cast<uint8_t>(hex_char_value(*j++) << 4);
val |= hex_char_value(*j++);
}
}
bool equal(const std::string& hash,
const node_id::host_id_type& node_id) {
if (hash.size() != (node_id.size() * 2)) {
return false;
}
auto j = hash.c_str();
try {
for (size_t i = 0; i < node_id.size(); ++i) {
// read two characters, each representing 4 bytes
std::uint8_t val;
val = static_cast<uint8_t>(hex_char_value(*j++) << 4);
val |= hex_char_value(*j++);
if (val != node_id[i]) {
return false;
}
}
}
catch (std::invalid_argument&) {
return false;
}
return true;
}
node_id::~node_id() { }
node_id::node_id(const node_id& other)
: super(), m_process_id(other.process_id()), m_host_id(other.host_id()) { }
node_id::node_id(std::uint32_t a, const std::string& b)
: m_process_id(a) {
host_id_from_string(b, m_host_id);
}
node_id::node_id(std::uint32_t a, const host_id_type& b)
: m_process_id(a), m_host_id(b) { }
std::string to_string(const node_id::host_id_type& node_id) {
std::ostringstream oss;
oss << std::hex;
oss.fill('0');
for (size_t i = 0; i < node_id::host_id_size; ++i) {
oss.width(2);
oss << static_cast<std::uint32_t>(node_id[i]);
}
return oss.str();
}
int node_id::compare(const node_id& other) const {
int tmp = strncmp(reinterpret_cast<const char*>(host_id().data()),
reinterpret_cast<const char*>(other.host_id().data()),
host_id_size);
if (tmp == 0) {
if (m_process_id < other.process_id()) return -1;
else if (m_process_id == other.process_id()) return 0;
return 1;
}
return tmp;
}
void node_id::serialize_invalid(serializer* sink) {
sink->write_value(static_cast<uint32_t>(0));
node_id::host_id_type zero;
std::fill(zero.begin(), zero.end(), 0);
sink->write_raw(node_id::host_id_size, zero.data());
}
std::string to_string(const node_id& what) {
std::ostringstream oss;
oss << what.process_id() << "@" << to_string(what.host_id());
return oss.str();
}
std::string to_string(const node_id_ptr& what) {
std::ostringstream oss;
oss << "@process_info(";
if (!what) oss << "null";
else oss << to_string(*what);
oss << ")";
return oss.str();
}
} // namespace actor
} // namespace boost
| 32.761006 | 80 | 0.499136 |
syoummer
|
fb4e3c7056c1607d4280b4d2aecb03f36860fcc7
| 3,355 |
cpp
|
C++
|
beowolf/graphics/DebugCube.cpp
|
JarateKing/Beowolf-Engine
|
b7ad1ed18ecb5ce7ca4e43d46ee96ed615300e85
|
[
"MIT"
] | 3 |
2019-01-21T15:18:41.000Z
|
2020-04-16T18:21:29.000Z
|
beowolf/graphics/DebugCube.cpp
|
JarateKing/Beowolf-Engine
|
b7ad1ed18ecb5ce7ca4e43d46ee96ed615300e85
|
[
"MIT"
] | 1 |
2020-03-10T18:22:08.000Z
|
2020-03-10T18:22:08.000Z
|
beowolf/graphics/DebugCube.cpp
|
JarateKing/Beowolf-Engine
|
b7ad1ed18ecb5ce7ca4e43d46ee96ed615300e85
|
[
"MIT"
] | 1 |
2021-12-30T11:38:36.000Z
|
2021-12-30T11:38:36.000Z
|
#include "DebugCube.h"
#include "W_RNG.h"
#include "W_ResourceLoader.h"
namespace wolf
{
static const Vertex cubeVertices[] = {
// Front
{ -0.5f, -0.5f, 0.5f, 255, 0, 0, 255, 0.0f, 0.0f },
{ -0.5f, 0.5f, 0.5f, 255, 0, 0, 255, 0.0f, 0.0f },
{ 0.5f, 0.5f, 0.5f, 255, 0, 0, 255, 0.0f, 0.0f },
{ 0.5f, 0.5f, 0.5f, 255, 0, 0, 255, 0.0f, 0.0f },
{ 0.5f, -0.5f, 0.5f, 255, 0, 0, 255, 0.0f, 0.0f },
{ -0.5f, -0.5f, 0.5f, 255, 0, 0, 255, 0.0f, 0.0f },
// Back
{ 0.5f, 0.5f,-0.5f, 128, 0, 0, 255, 0.0f, 0.0f },
{ -0.5f, 0.5f,-0.5f, 128, 0, 0, 255, 0.0f, 0.0f },
{ -0.5f, -0.5f,-0.5f, 128, 0, 0, 255, 0.0f, 0.0f },
{ -0.5f, -0.5f,-0.5f, 128, 0, 0, 255, 0.0f, 0.0f },
{ 0.5f, -0.5f,-0.5f, 128, 0, 0, 255, 0.0f, 0.0f },
{ 0.5f, 0.5f,-0.5f, 128, 0, 0, 255, 0.0f, 0.0f },
// Left
{ -0.5f, 0.5f,-0.5f, 0, 255, 0, 255, 0.0f, 0.0f },
{ -0.5f, 0.5f, 0.5f, 0, 255, 0, 255, 0.0f, 0.0f },
{ -0.5f, -0.5f, 0.5f, 0, 255, 0, 255, 0.0f, 0.0f },
{ -0.5f, -0.5f, 0.5f, 0, 255, 0, 255, 0.0f, 0.0f },
{ -0.5f, -0.5f,-0.5f, 0, 255, 0, 255, 0.0f, 0.0f },
{ -0.5f, 0.5f,-0.5f, 0, 255, 0, 255, 0.0f, 0.0f },
// Right
{ 0.5f, 0.5f, 0.5f, 0, 128, 0, 255, 0.0f, 0.0f },
{ 0.5f, 0.5f,-0.5f, 0, 128, 0, 255, 0.0f, 0.0f },
{ 0.5f, -0.5f,-0.5f, 0, 128, 0, 255, 0.0f, 0.0f },
{ 0.5f, -0.5f,-0.5f, 0, 128, 0, 255, 0.0f, 0.0f },
{ 0.5f, -0.5f, 0.5f, 0, 128, 0, 255, 0.0f, 0.0f },
{ 0.5f, 0.5f, 0.5f, 0, 128, 0, 255, 0.0f, 0.0f },
// Top
{ -0.5f, 0.5f, 0.5f, 0, 0, 255, 255, 0.0f, 0.0f },
{ -0.5f, 0.5f,-0.5f, 0, 0, 255, 255, 0.0f, 0.0f },
{ 0.5f, 0.5f,-0.5f, 0, 0, 255, 255, 0.0f, 0.0f },
{ 0.5f, 0.5f,-0.5f, 0, 0, 255, 255, 0.0f, 0.0f },
{ 0.5f, 0.5f, 0.5f, 0, 0, 255, 255, 0.0f, 0.0f },
{ -0.5f, 0.5f, 0.5f, 0, 0, 255, 255, 0.0f, 0.0f },
// Bottom
{ -0.5f, -0.5f, 0.5f, 0, 0, 128, 255, 0.0f, 0.0f },
{ 0.5f, -0.5f, 0.5f, 0, 0, 128, 255, 0.0f, 0.0f },
{ 0.5f, -0.5f,-0.5f, 0, 0, 128, 255, 0.0f, 0.0f },
{ 0.5f, -0.5f,-0.5f, 0, 0, 128, 255, 0.0f, 0.0f },
{ -0.5f, -0.5f,-0.5f, 0, 0, 128, 255, 0.0f, 0.0f },
{ -0.5f, -0.5f, 0.5f, 0, 0, 128, 255, 0.0f, 0.0f },
};
DebugCube::DebugCube()
{
setPos(glm::vec3(RNG::GetRandom(-10.0f, 10.0f), RNG::GetRandom(-0.5f, 0.5f), RNG::GetRandom(-10.0f, 10.0f)));
setScale(glm::vec3(RNG::GetRandom(0.75f, 1.5f), RNG::GetRandom(0.75f, 1.5f), RNG::GetRandom(0.75f, 1.5f)));
// set up rendering
g_pProgram = ProgramManager::CreateProgram(wolf::ResourceLoader::Instance().getShaders("cube"));
g_pVB = BufferManager::CreateVertexBuffer(cubeVertices, sizeof(Vertex) * 6 * 6);
g_pDecl = new VertexDeclaration();
g_pDecl->Begin();
Vertex::applyAttributes(g_pDecl);
g_pDecl->SetVertexBuffer(g_pVB);
g_pDecl->End();
}
DebugCube::~DebugCube()
{
}
void DebugCube::Update(float delta)
{
Node::Update(delta);
}
void DebugCube::Render(glm::mat4 projview)
{
Node::Render(projview);
g_pProgram->Bind();
// Bind Uniforms
g_pProgram->SetUniform("projection", projview);
g_pProgram->SetUniform("world", glm::translate(getPos()) * glm::scale(getScale()));
g_pProgram->SetUniform("view", glm::mat4());
// Set up source data
g_pDecl->Bind();
// Draw!
glDrawArrays(GL_TRIANGLES, 0, 6 * 6);
}
}
| 33.888889 | 111 | 0.504918 |
JarateKing
|
fb523d08972668a1932853bee5cc8631a527f9ae
| 3,905 |
cpp
|
C++
|
tests/src/helpers/cyclicbuffertestcase.cpp
|
MacroGu/log4cxx_gcc_4_8
|
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
|
[
"Apache-2.0"
] | 1 |
2016-10-06T20:09:32.000Z
|
2016-10-06T20:09:32.000Z
|
tests/src/helpers/cyclicbuffertestcase.cpp
|
MacroGu/log4cxx_gcc_4_8
|
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
|
[
"Apache-2.0"
] | null | null | null |
tests/src/helpers/cyclicbuffertestcase.cpp
|
MacroGu/log4cxx_gcc_4_8
|
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* 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 <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <log4cxx/logmanager.h>
#include <log4cxx/logger.h>
#include <log4cxx/helpers/cyclicbuffer.h>
#include <log4cxx/spi/loggingevent.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
#define MAX 1000
class CyclicBufferTestCase : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(CyclicBufferTestCase);
CPPUNIT_TEST(test0);
CPPUNIT_TEST(test1);
CPPUNIT_TEST(testResize);
CPPUNIT_TEST_SUITE_END();
LoggerPtr logger;
std::vector<LoggingEventPtr> e;
public:
void setUp()
{
logger = Logger::getLogger(_T("x"));
e.reserve(1000);
for (int i = 0; i < MAX; i++)
{
e.push_back(
new LoggingEvent(_T(""), logger, Level::DEBUG, _T("e")));
}
}
void tearDown()
{
LogManager::shutdown();
}
void test0()
{
int size = 2;
CyclicBuffer cb(size);
CPPUNIT_ASSERT_EQUAL(size, cb.getMaxSize());
cb.add(e[0]);
CPPUNIT_ASSERT_EQUAL(1, cb.length());
CPPUNIT_ASSERT_EQUAL(e[0], cb.get());
CPPUNIT_ASSERT_EQUAL(0, cb.length());
CPPUNIT_ASSERT(cb.get() == 0);
CPPUNIT_ASSERT_EQUAL(0, cb.length());
CyclicBuffer cb2(size);
cb2.add(e[0]);
cb2.add(e[1]);
CPPUNIT_ASSERT_EQUAL(2, cb2.length());
CPPUNIT_ASSERT_EQUAL(e[0], cb2.get());
CPPUNIT_ASSERT_EQUAL(1, cb2.length());
CPPUNIT_ASSERT_EQUAL(e[1], cb2.get());
CPPUNIT_ASSERT_EQUAL(0, cb2.length());
CPPUNIT_ASSERT(cb2.get() == 0);
CPPUNIT_ASSERT_EQUAL(0, cb2.length());
}
void test1()
{
for (int bufSize = 1; bufSize <= 128; bufSize *= 2)
doTest1(bufSize);
}
void doTest1(int size)
{
//System.out.println("Doing test with size = "+size);
CyclicBuffer cb(size);
CPPUNIT_ASSERT_EQUAL(size, cb.getMaxSize());
int i;
for (i = -(size + 10); i < (size + 10); i++)
{
CPPUNIT_ASSERT(cb.get(i) == 0);
}
for (i = 0; i < MAX; i++)
{
cb.add(e[i]);
int limit = (i < (size - 1)) ? i : (size - 1);
//System.out.println("\nLimit is " + limit + ", i="+i);
for (int j = limit; j >= 0; j--)
{
//System.out.println("i= "+i+", j="+j);
CPPUNIT_ASSERT_EQUAL(e[i - (limit - j)], cb.get(j));
}
CPPUNIT_ASSERT(cb.get(-1) == 0);
CPPUNIT_ASSERT(cb.get(limit + 1) == 0);
}
}
void testResize()
{
for (int isize = 1; isize <= 128; isize *= 2)
{
doTestResize(isize, (isize / 2) + 1, (isize / 2) + 1);
doTestResize(isize, (isize / 2) + 1, isize + 10);
doTestResize(isize, isize + 10, (isize / 2) + 1);
doTestResize(isize, isize + 10, isize + 10);
}
}
void doTestResize(int initialSize, int numberOfAdds, int newSize)
{
//System.out.println("initialSize = "+initialSize+", numberOfAdds="
// +numberOfAdds+", newSize="+newSize);
CyclicBuffer cb(initialSize);
for (int i = 0; i < numberOfAdds; i++)
{
cb.add(e[i]);
}
cb.resize(newSize);
int offset = numberOfAdds - initialSize;
if (offset < 0)
{
offset = 0;
}
int len = (newSize < numberOfAdds) ? newSize : numberOfAdds;
len = (len < initialSize) ? len : initialSize;
//System.out.println("Len = "+len+", offset="+offset);
for (int j = 0; j < len; j++)
{
CPPUNIT_ASSERT_EQUAL(e[offset + j], cb.get(j));
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(CyclicBufferTestCase);
| 23.383234 | 75 | 0.644814 |
MacroGu
|
fb5636875fada244e2d08b484c0ab9880a342d4f
| 516 |
cpp
|
C++
|
Advanced_programmation2/bart-dx-engine-a17/D3DEngine/Camera.cpp
|
Bigbell01/Portfolio
|
ec094a7f96239904ddec9d090bcba2c044eb6119
|
[
"MIT"
] | null | null | null |
Advanced_programmation2/bart-dx-engine-a17/D3DEngine/Camera.cpp
|
Bigbell01/Portfolio
|
ec094a7f96239904ddec9d090bcba2c044eb6119
|
[
"MIT"
] | null | null | null |
Advanced_programmation2/bart-dx-engine-a17/D3DEngine/Camera.cpp
|
Bigbell01/Portfolio
|
ec094a7f96239904ddec9d090bcba2c044eb6119
|
[
"MIT"
] | null | null | null |
#include "Camera.h"
Camera::Camera(float width, float height)
: up(0.f, -1.f, 0.f)
, target(0.f, 0.f, 0.f)
, width(width)
, height(height)
{
}
void Camera::Update()
{
D3DXMatrixLookAtLH(&view, &GetTransform()->GetPosition(), &target, &up);
D3DXMatrixOrthoLH(&proj, width, height, 0.01f, 1000.0f);
//D3DXMatrixPerspectiveFovLH(&proj, D3DX_PI/4, width/height, 0.01f, 1000.0f);
HR(gD3DDevice->SetTransform(D3DTS_VIEW, &view));
HR(gD3DDevice->SetTransform(D3DTS_PROJECTION, &proj));
}
Camera::~Camera()
{
}
| 21.5 | 78 | 0.684109 |
Bigbell01
|
fb5999b595f1be057f00c9b3612db9300ea761cc
| 4,968 |
cpp
|
C++
|
oactobjs32/piadata/PiaTable.cpp
|
codeforboston/anypia-emscripten
|
d4d1d154bae6b97acc619d5588d9a7515d220338
|
[
"CC0-1.0"
] | 1 |
2020-09-23T21:46:55.000Z
|
2020-09-23T21:46:55.000Z
|
oactobjs32/piadata/PiaTable.cpp
|
codeforboston/anypia-emscripten
|
d4d1d154bae6b97acc619d5588d9a7515d220338
|
[
"CC0-1.0"
] | 16 |
2020-05-07T18:53:55.000Z
|
2021-03-24T03:16:29.000Z
|
oactobjs32/piadata/PiaTable.cpp
|
codeforboston/anypia-emscripten
|
d4d1d154bae6b97acc619d5588d9a7515d220338
|
[
"CC0-1.0"
] | 6 |
2020-04-19T23:04:22.000Z
|
2021-03-17T01:40:10.000Z
|
// Functions for the <see cref="PiaTable"/> class to manage Pia Table pia
// calculations.
// $Id: PiaTable.cpp 1.45 2011/08/09 14:59:55EDT 044579 Development $
#include <fstream>
#include <utility> // for rel_ops
#include "PiaTable.h"
#include "oactcnst.h"
#include "PiaException.h"
#include "piaparms.h"
#include "DebugCase.h"
#if defined(DEBUGCASE)
#include <sstream>
#include "Trace.h"
#endif
using namespace std;
#if !defined(__SGI_STL_INTERNAL_RELOPS)
using namespace std::rel_ops;
#endif
/// <summary>Initializes this instance.</summary>
///
/// <remarks>Calls <see cref="initialize"/>.</remarks>
///
/// <param name="newWorkerData">Worker basic data.</param>
/// <param name="newPiaData">Pia calculation data.</param>
/// <param name="newPiaParams">Pia calculation parameters.</param>
/// <param name="newMaxyear">Maximum year of projection.</param>
PiaTable::PiaTable( const WorkerDataGeneral& newWorkerData,
const PiaData& newPiaData, const PiaParams& newPiaParams, int newMaxyear ) :
OldPia(newWorkerData, newPiaData, newPiaParams, newMaxyear,
"New-Start Calculation (pre-1977 Act)", PIA_TABLE)
{
initialize();
}
/// <summary>Destructor.</summary>
PiaTable::~PiaTable()
{ }
/// <summary>Determines applicability of method, using stored values.</summary>
///
/// <remarks>This version calls the static version with 3 arguments.</remarks>
///
/// <returns>True if method is applicable.</returns>
bool PiaTable::isApplicable()
{
if (isApplicable(workerData, piaData, getIoasdi())) {
setApplicable(APPLICABLE);
return(true);
}
return(false);
}
/// <summary>Determines applicability of method, using passed values.</summary>
///
/// <returns>True if method is applicable.</returns>
///
/// <param name="workerData">Worker basic data.</param>
/// <param name="piaData">Pia calculation data.</param>
/// <param name="ioasdi">Type of benefit.</param>
bool PiaTable::isApplicable( const WorkerDataGeneral& workerData,
const PiaData& piaData, WorkerDataGeneral::ben_type ioasdi )
{
return (piaData.getEligYear() < YEAR79 &&
workerData.getBenefitDate() >= PiaParams::amend52 &&
(ioasdi != WorkerDataGeneral::SURVIVOR ||
DateMoyr(workerData.getDeathDate()) >= PiaParams::amend52) );
}
/// <summary>Computes Pia Table PIA.</summary>
///
/// <exception cref="PiaException"><see cref="PiaException"/> of type
/// <see cref="PIA_IDS_PIATABLE1"/> if year of entitlement is out of range
/// (only in debug mode); of type <see cref="PIA_IDS_PIATABLE2"/> if year of
/// benefit is out of range (only in debug mode).</exception>
void PiaTable::calculate()
{
#if defined(DEBUGCASE)
if (isDebugPid(workerData.getIdNumber())) {
Trace::writeLine(workerData.getIdString() +
": Starting PiaTable::calculate");
}
#endif
DateMoyr dateMoyr = (getIoasdi() == WorkerDataGeneral::SURVIVOR) ?
DateMoyr(workerData.getDeathDate()) : workerData.getEntDate();
#if !defined(NDEBUG)
if (dateMoyr.getYear() < YEAR37)
throw PiaException(PIA_IDS_PIATABLE1);
#endif
int i1 = dateMoyr.getYear();
yearCpi[YEAR_ENT] = (i1 < YEAR51) ? i1 :
(static_cast<int>(dateMoyr.getMonth()) >=
piaParams.getMonthBeninc(i1)) ? i1 : i1 - 1;
#if !defined(NDEBUG)
if (workerData.getBenefitDate().getYear() < YEAR37)
throw PiaException(PIA_IDS_PIATABLE2);
#endif
i1 = workerData.getBenefitDate().getYear();
yearCpi[YEAR_BEN] =
(static_cast<int>(workerData.getBenefitDate().getMonth()) >=
piaParams.getMonthBeninc(i1)) ? i1 : i1 - 1;
yearCpi[FIRST_YEAR] = 1975;
const AverageWage& earnings = workerData.getTotalize() ?
piaData.earnTotalizedLimited : piaData.earnOasdiLimited;
i1 = piaData.getEarn50(PiaData::EARN_WITH_TOTALIZATION);
const int i4 = piaData.getEarnYear();
for (int i2 = i1; i2 <= i4; i2++) {
if (!piaData.freezeYears.isFreezeYear(i2))
earnIndexed[i2] = earnings[i2];
}
const int i3 = piaData.compPeriodNew.getN();
orderEarnings(i1, i4, i3);
totalEarnCal(i1, i4, i3);
#if defined(DEBUGCASE)
if (isDebugPid(workerData.getIdNumber())) {
ostringstream strm;
strm << workerData.getIdString() << ", ame " << getAme()
<< ": After totalEarnCal";
Trace::writeLine(strm.str());
}
#endif
if (workerData.getBenefitDate() < PiaParams::amend742) {
setTableNum(oldPiaCal());
}
else {
setTableNum(cpiBase(workerData.getBenefitDate(), false, getAme(),
!workerData.getTotalize()));
}
piaEnt.set(piasub);
mfbEnt.set(mfbsub);
if (workerData.getTotalize()) {
piaElig[yearCpi[FIRST_YEAR]] = piaEnt.get();
prorate();
piaEnt.set(piaElig[yearCpi[FIRST_YEAR]]);
static_cast<void>(mfbOldCal(true));
}
setDirty();
#if defined(DEBUGCASE)
if (isDebugPid(workerData.getIdNumber())) {
Trace::writeLine(workerData.getIdString() +
": Returning from PiaTable::calculate");
}
#endif
}
| 33.567568 | 80 | 0.680354 |
codeforboston
|
fb5fe129bec2cb3a0dae0336ca0f4cebcca7a46b
| 136 |
cpp
|
C++
|
bin/maxPlugin/renElemPch.cpp
|
HonzaMD/Krkal2
|
e53e9b096d89d1441ec472deb6d695c45bcae41f
|
[
"OLDAP-2.5"
] | 1 |
2018-04-01T16:47:52.000Z
|
2018-04-01T16:47:52.000Z
|
bin/maxPlugin/renElemPch.cpp
|
HonzaMD/Krkal2
|
e53e9b096d89d1441ec472deb6d695c45bcae41f
|
[
"OLDAP-2.5"
] | null | null | null |
bin/maxPlugin/renElemPch.cpp
|
HonzaMD/Krkal2
|
e53e9b096d89d1441ec472deb6d695c45bcae41f
|
[
"OLDAP-2.5"
] | null | null | null |
////////////////////////////////////////////////////////////////
// precompiled header for render elements
//
#include "renElemPch.h"
| 34 | 65 | 0.382353 |
HonzaMD
|
fb60cb73416b98fa31239668e0c09f2b4179a8fb
| 1,453 |
cpp
|
C++
|
Blik2D/element/blik_vector.cpp
|
BonexGu/Blik2D
|
8e0592787e5c8e8a28682d0e1826b8223eae5983
|
[
"MIT"
] | 13 |
2017-02-22T02:20:06.000Z
|
2018-06-06T04:18:03.000Z
|
Blik2D/element/blik_vector.cpp
|
BonexGu/Blik2D
|
8e0592787e5c8e8a28682d0e1826b8223eae5983
|
[
"MIT"
] | null | null | null |
Blik2D/element/blik_vector.cpp
|
BonexGu/Blik2D
|
8e0592787e5c8e8a28682d0e1826b8223eae5983
|
[
"MIT"
] | null | null | null |
#include <blik.hpp>
#include "blik_vector.hpp"
namespace BLIK
{
Vector::Vector()
{
x = 0;
y = 0;
vx = 0;
vy = 0;
}
Vector::Vector(const Vector& rhs)
{
operator=(rhs);
}
Vector::Vector(float x, float y, float vx, float vy)
{
this->x = x;
this->y = y;
this->vx = vx;
this->vy = vy;
}
Vector::Vector(const Point& pos, const Point& vec)
{
x = pos.x;
y = pos.y;
vx = vec.x;
vy = vec.y;
}
Vector::~Vector()
{
}
Vector& Vector::operator=(const Vector& rhs)
{
x = rhs.x;
y = rhs.y;
vx = rhs.vx;
vy = rhs.vy;
return *this;
}
Vector& Vector::operator+=(const Point& rhs)
{
x += rhs.x;
y += rhs.y;
return *this;
}
Vector Vector::operator+(const Point& rhs) const
{
return Vector(*this).operator+=(rhs);
}
Vector& Vector::operator-=(const Point& rhs)
{
x -= rhs.x;
y -= rhs.y;
return *this;
}
Vector Vector::operator-(const Point& rhs) const
{
return Vector(*this).operator-=(rhs);
}
bool Vector::operator==(const Vector& rhs) const
{
return (x == rhs.x && y == rhs.y && vx == rhs.vx && vy == rhs.vy);
}
bool Vector::operator!=(const Vector& rhs) const
{
return !operator==(rhs);
}
}
| 17.719512 | 74 | 0.461115 |
BonexGu
|
fb67c730b2abd3f5e99a285548babd7aeac2a417
| 9,248 |
cpp
|
C++
|
CPSC314/ass2/visual_studio_project/P2_demo/Solar.cpp
|
AmanSharma1997/school
|
60f19dce52f6fb8e416df73c924132da6ac7fa01
|
[
"BSD-3-Clause"
] | 87 |
2016-09-07T06:25:59.000Z
|
2022-03-22T18:02:58.000Z
|
CPSC314/ass2/visual_studio_project/P2_demo/Solar.cpp
|
orklann/school
|
60f19dce52f6fb8e416df73c924132da6ac7fa01
|
[
"BSD-3-Clause"
] | null | null | null |
CPSC314/ass2/visual_studio_project/P2_demo/Solar.cpp
|
orklann/school
|
60f19dce52f6fb8e416df73c924132da6ac7fa01
|
[
"BSD-3-Clause"
] | 30 |
2015-03-22T19:07:37.000Z
|
2022-01-11T22:23:13.000Z
|
#include "Solar.h"
Solar::Solar(void)
{
geo = false;
DEG2RAD = 3.14159/180;
velocity = 1;
Mer = 0.0, Ven = 0.0, Ear = 0.0, Moo = 0.0, Moo2 = 0.0, Mar = 0.0, Jup = 0.0, Sat = 0.0, Ura = 0.0, Nep = 0.0, Plu = 0.0;
shine[0] = 10;
mooCol[0]=2.3, mooCol[1]=2.3, mooCol[2]=2.3;
moo2Col[0]=0.93,moo2Col[1]=0.93,moo2Col[2]=0.93;
merCol[0]=2.05, merCol[1]=1.90, merCol[0]=1.12;
venCol[0]=1.39, venCol[1]=0.54, venCol[2]=0.26;
earCol[0]=0.0, earCol[1]=0.3, earCol[2]=0.6;
marCol[0]=1.39, marCol[1]=0.26, marCol[2]=0.0;
jupCol[0]=0.80, jupCol[1]=0.53, jupCol[2]=0.25;
satCol[0]=0.6, satCol[1]=0.5, satCol[2]=0.09;
uraCol[0]=0.40, uraCol[1]=0.900,uraCol[2]=1.0;
nepCol[0]=0.135,nepCol[1]=0.115,nepCol[2]=0.85;
pluCol[0]=0.7, pluCol[1]=0.8, pluCol[2]=1.00;
eyex=80.0, eyey=10.0, eyez= 10.0;
centerx=0.0, centery=0.0, centerz=0.0;
upx=0.0, upy=1.0, upz=0.0;
}
Solar::~Solar(void)
{
}
void Solar::incVelocity() {
velocity++;
}
void Solar::decVelocity() {
velocity--;
}
float Solar::getVelocity() {
return velocity;
}
void Solar::spin() {
Mer += 16.0 * velocity;
if(Mer > 360.0)
Mer = Mer - 360.0;
Ven += 12.0 * velocity;
if(Ven > 360.0)
Ven = Ven - 360.0;
Ear += 10.0 * velocity;
if(Ear > 360.0)
Ear = Ear - 360.0;
Moo += 2.0 * velocity;
if(Moo > 360.0)
Moo = Moo - 360.0;
Moo2 += 1.0 * velocity;
if(Moo2 > 360.0)
Moo2 = Moo2 - 360.0;
Mar += 8.0 * velocity;
if(Mar > 360.0)
Mar = Mar - 360.0;
Jup += 5.0 * velocity;
if(Jup > 360.0)
Jup = Jup - 360.0;
Sat += 4.0 * velocity;
if(Sat > 360.0)
Sat = Sat - 360.0;
Ura += 3.0 * velocity;
if(Ura > 360.0)
Ura = Ura - 360.0;
Nep += 2.0 * velocity;
if(Nep > 360.0)
Nep = Nep - 360.0;
Plu += 1.0 * velocity;
if(Plu > 360.0)
Plu = Plu - 360.0;
}
void Solar::drawCircle(float radius) {
glBegin(GL_LINE_LOOP);
for (int i=0; i<=360; i++)
{
float degInRad = i*DEG2RAD;
glVertex2f(cos(degInRad)*radius,sin(degInRad)*radius);
}
glEnd();
}
void Solar::draw() {
GLfloat position[] = { 0.0, 0.0, 1.5, 1.0 };
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, shine);
glPushMatrix();
gluLookAt(eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz);
glPushMatrix();
glPushMatrix();
glRotatef(90,1,0,0);
drawCircle(4.9);
glPopMatrix();
glRotated((GLdouble) Mer, 0.0, 1.0, 0.0);
glTranslated(0.0, 0.0, 4.9);
glRotated((GLdouble) Mer, 0.0, 1.0, 0.0);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, merCol);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, merCol);
glutSolidSphere(0.049, 20, 20);
glDisable(GL_DIFFUSE);
if (geo) {
glPushMatrix();
glTranslated(0.1,0.0,0.1);
glRotated((GLdouble) Mer, 0.0, 1.0, 0.0);
glutSolidCone(0.1,0.4,10,10);
glPopMatrix();
}
glPopMatrix();
glPushMatrix();
glPushMatrix();
glRotatef(90,1,0,0);
drawCircle(5.2);
glPopMatrix();
glRotated((GLdouble) Ven, 0.0, 1.0, 0.0);
glTranslated(0.1, 0.0, 5.2);
glRotated((GLdouble) Ven - 1, 0.0, 1.0, 0.0); //Retrograde (Counter) Rotation
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, venCol);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, venCol);
glutSolidSphere(0.12, 20, 20);
glDisable(GL_DIFFUSE);
if (geo) {
glPushMatrix();
glTranslated(0.1,0.0,0.1);
glRotated((GLdouble) Ven, 0.0, 1.0, 0.0);
glutSolidCone(0.1,0.4,10,10);
glPopMatrix();
}
glPopMatrix();
glPushMatrix();
glPushMatrix();
glRotatef(90,1,0,0);
drawCircle(5.6);
glPopMatrix();
glRotated((GLdouble) Ear, 0.0, 1.0, 0.0);
glTranslated(0.1, 0.0, 5.6);
glRotated((GLdouble) Ear, 0.0, 1.0, 0.0);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, earCol);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, earCol);
glutSolidSphere(0.13, 20, 20);
glDisable(GL_DIFFUSE);
glPushMatrix();
if (geo) {
glPushMatrix();
glPushMatrix();
gluLookAt(0.1,0.0,0.1,0,0,0,0,1,0);
glPopMatrix();
glTranslated(0.1,0.0,0.1);
glRotated((GLdouble) Ear, 0.0, 1.0, 0.0);
glutSolidCone(0.1,0.4,10,10);
glPopMatrix();
}
glRotated((GLdouble) Moo, 0.0, 1.0, 0.0);
glTranslated(0.1, 0.0, 0.1);
glRotated((GLdouble) Moo, 0.0, 1.0, 0.0);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mooCol);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, mooCol);
glutSolidSphere(0.02, 20, 20);
glDisable(GL_DIFFUSE);
glPopMatrix();
glPopMatrix();
glPushMatrix();
glPushMatrix();
glRotatef(90,1,0,0);
drawCircle(6.0);
glPopMatrix();
glRotated((GLdouble) Mar, 0.0, 1.0, 0.0);
glTranslated(0.1, 0.0, 6.0);
glRotated((GLdouble) Mar, 0.0, 1.0, 0.0);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, marCol);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, marCol);
glutSolidSphere(0.067, 20, 20);
glDisable(GL_DIFFUSE);
if (geo) {
glPushMatrix();
glTranslated(0.1,0.0,0.1);
glRotated((GLdouble) Mar, 0.0, 1.0, 0.0);
glutSolidCone(0.1,0.4,10,10);
glPopMatrix();
}
glPushMatrix();
glRotated((GLdouble) Moo, 0.0, 1.0, 0.0);
glTranslated(0.0, 0.0, 0.1);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mooCol);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, mooCol);
glRotated((GLdouble) Moo, 0.0, 1.0, 0.0);
glutSolidSphere(0.015, 20, 10);
glPopMatrix();
glPushMatrix();
glRotated((GLdouble) Moo2, 0.0, 1.0, 0.0);
glTranslated(0.0, 0.0, 0.15);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, moo2Col);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, moo2Col);
glRotated((GLdouble) Moo2, 0.0, 1.0, 0.0);
glutSolidSphere(0.01, 20, 10);
glPopMatrix();
glPopMatrix();
glPushMatrix();
glPushMatrix();
glRotatef(90,1,0,0);
drawCircle(9.7);
glPopMatrix();
glRotated((GLdouble) Jup, 0.0, 1.0, 0.0);
glTranslated(0.1, 0.0, 9.7);
glRotated((GLdouble) Jup, 0.0, 1.0, 0.0);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, jupCol);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, jupCol);
glutSolidSphere(1.42, 20, 20);
glDisable(GL_DIFFUSE);
if (geo) {
glPushMatrix();
glTranslated(2,0.0,0.1);
glRotated((GLdouble) Jup, 0.0, 1.0, 0.0);
glutSolidCone(0.1,0.4,10,10);
glPopMatrix();
}
glPopMatrix();
glPushMatrix();
glPushMatrix();
glRotatef(90,1,0,0);
drawCircle(14.0);
glPopMatrix();
glRotated((GLdouble) Sat, 0.0, 1.0, 0.0);
glTranslated(0.1, 0.0, 14.0);
glRotated((GLdouble) Sat, 0.0, 1.0, 0.0);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, satCol);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, satCol);
glPushMatrix();
glRotatef(45,1,0,0);
for (float i=1.7;i<=2.5;i+=0.05) {
drawCircle(i);
//std::cout<<i<<std::endl;
}
glPopMatrix();
glutSolidSphere(1.20, 20, 20);
glDisable(GL_DIFFUSE);
if (geo) {
glPushMatrix();
glTranslated(2,0.0,0.1);
glRotated((GLdouble) Sat, 0.0, 1.0, 0.0);
glutSolidCone(0.1,0.4,10,10);
glPopMatrix();
}
glPopMatrix();
glPushMatrix();
glPushMatrix();
glRotatef(90,1,0,0);
drawCircle(23.5);
glPopMatrix();
glRotated((GLdouble) Ura, 0.0, 1.0, 0.0);
glTranslated(0.1, 0.0, 23.5);
glRotated((GLdouble) Ura - 1, 1.0, 0.0, 0.0); //Retrograde Rotation
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, uraCol);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, uraCol);
glutSolidSphere(0.51, 20, 20);
glDisable(GL_DIFFUSE);
if (geo) {
glPushMatrix();
glTranslated(1,0.0,0.1);
glRotated((GLdouble) Ura, 0.0, 1.0, 0.0);
glutSolidCone(0.1,0.4,10,10);
glPopMatrix();
}
glPopMatrix();
glPushMatrix();
glPushMatrix();
glRotatef(90,1,0,0);
drawCircle(34.5);
glPopMatrix();
glRotated((GLdouble) Nep, 0.0, 1.0, 0.0);
glTranslated(0.1, 0.0, 34.5);
glRotated((GLdouble) Nep, 1.0, 0.0, 0.0); //Rotates top to bottom
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, nepCol);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, nepCol);
glutSolidSphere(0.49, 20, 20);
glDisable(GL_DIFFUSE);
if (geo) {
glPushMatrix();
glTranslated(1,0.0,0.1);
glRotated((GLdouble) Ura, 0.0, 1.0, 0.0);
glutSolidCone(0.1,0.4,10,10);
glPopMatrix();
}
glPopMatrix();
glPushMatrix();
glPushMatrix();
glRotatef(90,1,0,0);
drawCircle(44.0);
glPopMatrix();
glRotated((GLdouble) Plu, 0.0, 1.0, 0.0);
glTranslated(0.1, 0.0, 44.0);
glRotated((GLdouble) Plu, 0.0, 1.0, 0.0);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, pluCol);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, pluCol);
glutSolidSphere(0.1, 20, 20);
glDisable(GL_DIFFUSE);
if (geo) {
glPushMatrix();
glTranslated(1,0.0,0.1);
glRotated((GLdouble) Plu, 0.0, 1.0, 0.0);
glutSolidCone(0.1,0.4,10,10);
glPopMatrix();
}
glPopMatrix();
glLightfv(GL_LIGHT0, GL_POSITION, position);
GLfloat global_ambient[] = {0.5f, 0.5f, 0.5f, 1.0f}; //Emission
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient); //Emission
glDisable(GL_LIGHTING);
glColor3f(1.0, 1.0, 0.0);
glRotated((GLdouble) Ear, 0.0, 1.0, 0.0);
glutSolidSphere(4.00, 20, 20);
glEnable(GL_LIGHTING);
glPopMatrix();
}
| 20.060738 | 122 | 0.610835 |
AmanSharma1997
|
fb6a9103018e519ff465f69fa6024c10161bce5e
| 4,099 |
cpp
|
C++
|
src/slider.cpp
|
bebuch/BitmapViewer
|
51259974e74859767982a363f419965e2396c513
|
[
"BSL-1.0"
] | null | null | null |
src/slider.cpp
|
bebuch/BitmapViewer
|
51259974e74859767982a363f419965e2396c513
|
[
"BSL-1.0"
] | null | null | null |
src/slider.cpp
|
bebuch/BitmapViewer
|
51259974e74859767982a363f419965e2396c513
|
[
"BSL-1.0"
] | null | null | null |
//-----------------------------------------------------------------------------
// Copyright (c) 2013-2018 Benjamin Buch
//
// https://github.com/bebuch/BitmapViewer
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
//-----------------------------------------------------------------------------
#include <BitmapViewer/slider.hpp>
#include <QMouseEvent>
#include <QPaintEvent>
#include <QWheelEvent>
#include <QPainter>
#include <cmath>
namespace bitmap_viewer{
constexpr double shift_range = std::numeric_limits< unsigned >::max() + 1.;
slider::slider(QWidget* parent):
QWidget(parent),
active_(false),
shift_(0),
startpos_(0),
startshift_(0)
{
setCursor(Qt::OpenHandCursor);
colors_.update.connect([this]{repaint();change();});
}
void slider::set_shift(unsigned s){
shift_ = colors_.pass_pos(s);
repaint();
shift_changed(s);
change();
}
void slider::set_strips(unsigned count){
colors_.set_strips(count);
set_shift(shift());
}
void slider::contrast_line(bool enable){
colors_.contrast_line(enable);
}
void slider::next_palette(){
colors_.next_palette();
}
unsigned slider::inc_step(unsigned step, int inc)const{
if(inc < 0){
inc = -inc % colors_.strips();
step += colors_.strips() - inc;
}else{
step += inc;
step %= colors_.strips();
}
return step;
}
void slider::right_shift(){
auto step_pos = colors_.step_pos(shift_);
step_pos = inc_step(step_pos, -1);
set_shift(colors_.pass_step_pos(step_pos));
}
void slider::left_shift(){
auto step_pos = colors_.step_pos(shift_);
step_pos = inc_step(step_pos, 1);
set_shift(colors_.pass_step_pos(step_pos));
}
void slider::fold_linear(){
colors_.set_fold(colors_.fold() + 1);
}
void slider::unfold_linear(){
colors_.set_fold(colors_.fold() - 1);
}
void slider::fold_exponential(){
colors_.set_fold(colors_.fold() << 1);
}
void slider::unfold_exponential(){
colors_.set_fold(colors_.fold() >> 1);
}
void slider::mouseMoveEvent(QMouseEvent* event){
if(!active_) return;
unsigned w = width();
set_shift(startshift_ + startpos_ - event->x() * (shift_range / w));
}
void slider::mousePressEvent(QMouseEvent* event){
if(event->button() != Qt::LeftButton) return;
active_ = true;
setCursor(Qt::ClosedHandCursor);
unsigned w = width();
startpos_ = event->x() * (shift_range / w);
startshift_ = shift_;
}
void slider::mouseReleaseEvent(QMouseEvent* event){
if(event->button() != Qt::LeftButton) return;
setCursor(Qt::OpenHandCursor);
active_ = false;
}
void slider::paintEvent(QPaintEvent*){
QPainter painter(this);
unsigned w = width();
for(unsigned i = 0; i < w; ++i){
painter.setPen(colors_(shift_ + i * (shift_range / w)));
painter.drawLine(i, 0, i, height());
}
auto text = QString("Pos: %1").arg(colors_.step_pos(shift_));
auto flags = Qt::AlignLeft | Qt::AlignVCenter;
auto fontfactor = 0.7;
auto fontsize = height() * fontfactor;
auto x_offset = height() * (1 - fontfactor) / 2;
auto p1 = QPointF(x_offset, 0);
auto p2 = QPointF(w - 2*x_offset, height());
QFont font;
font.setPixelSize(fontsize);
font.setStyleStrategy(QFont::PreferAntialias);
font.setStyleStrategy(QFont::PreferQuality);
painter.setRenderHint(QPainter::TextAntialiasing);
painter.setFont(font);
painter.setPen(Qt::white);
int range = 2;
for(int y = -range; y <= range; ++y){
for(int x = -range; x <= range; ++x){
painter.drawText(QRectF(p1 + QPointF(x, y), p2), text, flags);
}
}
painter.setPen(Qt::black);
painter.drawText(QRectF(p1, p2), text, flags);
}
void slider::wheelEvent(QWheelEvent* event){
auto step_pos = colors_.step_pos(shift_);
double factor = 1;
if(event->buttons() & Qt::LeftButton) factor = 0.25;
if(event->buttons() & Qt::RightButton) factor = 4;
step_pos = inc_step(
step_pos,
std::max(factor * colors_.strips() / 32, 1.) *
(event->angleDelta().y() > 0 ? 1 : -1)
);
set_shift(colors_.pass_step_pos(step_pos));
}
}
| 24.254438 | 79 | 0.647719 |
bebuch
|
fb6ce7d99eb2d5d25919416dbe37b55aa1bdef92
| 431 |
hpp
|
C++
|
src/Client/Input/Window.hpp
|
fqhd/BuildBattle
|
f85ec857aa232313f4678514aa317af73c37de10
|
[
"MIT"
] | 10 |
2021-08-17T20:55:52.000Z
|
2022-03-28T00:45:14.000Z
|
src/Client/Input/Window.hpp
|
fqhd/BuildBattle
|
f85ec857aa232313f4678514aa317af73c37de10
|
[
"MIT"
] | null | null | null |
src/Client/Input/Window.hpp
|
fqhd/BuildBattle
|
f85ec857aa232313f4678514aa317af73c37de10
|
[
"MIT"
] | 2 |
2021-07-05T18:49:56.000Z
|
2021-07-10T22:03:17.000Z
|
#pragma once
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <GL/glew.h>
#include "Math.hpp"
#include <iostream>
class Window {
public:
static void create(unsigned int _width, unsigned int _height, const char* _title, bool _resizable = false, bool _decorated = true);
static void clear();
static void update();
static void close();
static GLFWwindow* getWindowPtr();
private:
static GLFWwindow* m_window;
};
| 18.73913 | 132 | 0.737819 |
fqhd
|
fb81584a0290e80a06d56da0f6fd5d9c007ca880
| 1,980 |
cpp
|
C++
|
src/core/sample.cpp
|
BiRDLab-UMinho/trignoclient
|
507351e818b37199aa00aefedb124885dda1ea98
|
[
"MIT"
] | null | null | null |
src/core/sample.cpp
|
BiRDLab-UMinho/trignoclient
|
507351e818b37199aa00aefedb124885dda1ea98
|
[
"MIT"
] | null | null | null |
src/core/sample.cpp
|
BiRDLab-UMinho/trignoclient
|
507351e818b37199aa00aefedb124885dda1ea98
|
[
"MIT"
] | null | null | null |
#include <string>
#include <vector>
#include <iostream>
#include <cstring> // std::memcpy
#include "core/sample.hpp" // trigno::sample::ID
namespace trigno {
Sample::Sample(sensor::ID id, size_t n_channels, const char* raw_data) :
_id(id),
_data(n_channels) {
/* ... */
if (raw_data != nullptr) {
for (int ch = 0; ch < n_channels; ch++) {
std::memcpy(&_data[ch], raw_data, sizeof(_data[ch]));
}
}
}
Sample::Sample(sensor::ID id, const std::vector< float >& values) :
_id(id),
_data(values) {
/* ... */
}
sensor::ID Sample::id() const noexcept {
return _id;
}
size_t Sample::size() const noexcept {
return _data.size();
}
bool Sample::empty() const noexcept {
return _data.empty();
}
float& Sample::operator[](size_t channel) {
if (channel >= _data.size()) {
throw std::out_of_range("[" + std::string(__func__) + "] Invalid channel index!!");
}
return _data[channel];
}
const float& Sample::operator[](size_t channel) const {
if (channel >= _data.size()) {
throw std::out_of_range("[" + std::string(__func__) + "] Invalid channel index!!");
}
return _data[channel];
}
const Sample::Container& Sample::data() const {
return _data;
}
Sample::operator const Container&() const {
return _data;
}
Sample::operator const Sample::Value&() const noexcept {
return _data.front();
}
Sample::Value Sample::average() const {
auto avg = 0.0;
for (const auto& value : _data) {
avg += value;
}
return (avg/=size());
}
std::vector< float >::iterator Sample::begin() {
return _data.begin();
}
std::vector< float >::const_iterator Sample::begin() const {
return _data.begin();
}
std::vector< float >::iterator Sample::end() {
return _data.end();
}
std::vector< float >::const_iterator Sample::end() const {
return _data.end();
}
} // namespace trigno
| 16.923077 | 91 | 0.589394 |
BiRDLab-UMinho
|
fb81d82969cfe6877be8c84fb2a33d590bef3de3
| 4,050 |
cpp
|
C++
|
src/HoursMinutes.cpp
|
hartogjr/timecal
|
2c4607947b03a6fa8ee82fd3eeb6e2dc36cdd93b
|
[
"BSD-3-Clause"
] | null | null | null |
src/HoursMinutes.cpp
|
hartogjr/timecal
|
2c4607947b03a6fa8ee82fd3eeb6e2dc36cdd93b
|
[
"BSD-3-Clause"
] | null | null | null |
src/HoursMinutes.cpp
|
hartogjr/timecal
|
2c4607947b03a6fa8ee82fd3eeb6e2dc36cdd93b
|
[
"BSD-3-Clause"
] | null | null | null |
/* BSD 3-Clause License
*
* Copyright (c) 2020, Simon de Hartog <simon@dehartog.name>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER 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.
*
* vim:set ts=4 sw=4 noexpandtab: */
#include <cerrno>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include "HoursMinutes.h"
namespace SdH {
uint8_t HoursMinutes::parseChar(const char char_i)
{
if (char_i < '0' || char_i > '9') {
throw std::invalid_argument(
std::string("Invalid character '") + char_i + "' in time string"
);
}
return char_i - '0';
}
uint8_t HoursMinutes::parse(const std::string & str_i, const uint8_t max_i)
{
if (str_i.empty() || str_i == "0" || str_i == "00") return 0;
uint8_t rv = 0; // Return Value
switch (str_i.size()) {
case 2:
rv = parseChar(str_i[0]) * 10 + parseChar(str_i[1]);
break;
case 1:
rv = parseChar(str_i[0]);
break;
default:
throw std::invalid_argument("Integer string longer than two characters");
}
if (rv > max_i) {
std::ostringstream oss;
oss << "String value \"" << str_i << "\" is a valid integer but is larger than ";
oss << static_cast<uint16_t>(max_i);
throw std::overflow_error(oss.str());
}
return rv;
}
void HoursMinutes::set(const std::string & hm_i)
{
size_t pos = 0;
uint8_t tmphrs = 0;
uint8_t tmpmin = 0;
if (hm_i.empty() || hm_i == ":") {
reset();
return;
}
pos = hm_i.find(':');
if (pos == std::string::npos) {
// No hours specified, just minutes
tmpmin = parse(hm_i, 59);
hours_a = 0;
minutes_a = tmpmin;
return;
}
tmphrs = parse(hm_i.substr(0, pos), 23);
tmpmin = parse(hm_i.substr(pos+1), 59);
hours_a = tmphrs;
minutes_a = tmpmin;
}
void HoursMinutes::set(const time_t & time_i)
{
struct tm *tmptr = nullptr;
tmptr = localtime(&time_i);
if (tmptr == nullptr) {
throw std::runtime_error("Unable to break down time to parts");
}
hours_a = tmptr->tm_hour;
minutes_a = tmptr->tm_min;
}
HoursMinutes & HoursMinutes::operator+=(const HoursMinutes & rhs_i)
{
hours_a += rhs_i.hours_a;
minutes_a += rhs_i.minutes_a;
if (minutes_a > 59) {
hours_a++;
minutes_a %= 60;
}
if (hours_a > 23) hours_a %= 24;
return (*this);
}
} // SdH namespace
std::ostream & operator<<(std::ostream & os, const SdH::HoursMinutes & hm)
{
os << std::dec << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(hm.hours());
os << ':';
os << std::dec << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(hm.minutes());
return os;
}
| 27.739726 | 92 | 0.675062 |
hartogjr
|
fb8329526b43d2615bd1cedcaf9f5ab374b45723
| 3,592 |
hpp
|
C++
|
src/verbatim_vertex_buffer.hpp
|
trilkk/faemiyah-demoscene_2015-04_64k-intro_junamatkailuintro
|
fdd055871a95f99c9162bced542e6d08be47f7e8
|
[
"BSD-3-Clause"
] | 2 |
2015-05-25T02:22:41.000Z
|
2015-10-06T17:39:55.000Z
|
src/verbatim_vertex_buffer.hpp
|
faemiyah/faemiyah-demoscene_2015-04_64k-intro_junamatkailuintro
|
fdd055871a95f99c9162bced542e6d08be47f7e8
|
[
"BSD-3-Clause"
] | null | null | null |
src/verbatim_vertex_buffer.hpp
|
faemiyah/faemiyah-demoscene_2015-04_64k-intro_junamatkailuintro
|
fdd055871a95f99c9162bced542e6d08be47f7e8
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef VERBATIM_VERTEX_BUFFER
#define VERBATIM_VERTEX_BUFFER
#include "verbatim_array.hpp"
#include "verbatim_vertex.hpp"
// Forward declaration.
class Program;
/** Vertex buffer.
*/
class VertexBuffer
{
private:
/** Current vertex buffer. */
static const VertexBuffer* g_bound_vertex_buffer;
/** Currently programmed vertex buffer. */
static const VertexBuffer* g_programmed_vertex_buffer;
private:
/** OpenGL id. */
GLuint m_id_data[2];
/** Vertex array. */
Array<Vertex> m_vertices;
/** Index array. */
Array<uint16_t> m_indices;
private:
/** \brief Accessor.
*
* \return Vertex buffer OpenGL id.
*/
GLuint getVertexId() const
{
return m_id_data[0];
}
/** \brief Accessor.
*
* \return Index buffer OpenGL id.
*/
GLuint getIndexId() const
{
return m_id_data[1];
}
public:
/** \brief Accessor.
*
* \param idx Index of vertex to access.
* \return Vertex at given index.
*/
const Vertex& getVertex(size_t idx) const
{
return m_vertices[idx];
}
public:
/** \brief Constructor.
*/
VertexBuffer();
public:
/** \brief Add face to this vertex buffer.
*
* \param op Index to add.
*/
void addIndex(uint16_t op)
{
#if defined(USE_LD)
if(g_debug)
{
std::cout << op << std::endl;
}
#endif
m_indices.add(op);
}
/** \brief Add vertex to this vertex buffer.
*
* \param op Vertex to add.
*/
void addVertex(const Vertex &op)
{
#if defined(USE_LD)
if(g_debug)
{
std::cout << op << std::endl;
}
#endif
m_vertices.add(op);
}
/** \brief Tell if amount of vertices fits in this vertex buffer.
*
* \param op Number of offered vertices.
* \return True if fits, false if not.
*/
bool fitsVertices(size_t op)
{
return (65536 >= (m_vertices.getSize() + op));
}
/** \brief Accessor.
*
* \return Index count.
*/
size_t getIndexCount() const
{
return m_indices.getSize();
}
/** \brief Accessor.
*
* \return Vertex count.
*/
size_t getVertexCount() const
{
return m_vertices.getSize();
}
private:
/** \brief Bind this vertex buffer for rendering and/or modification.
*/
void bind() const;
public:
/** \brief Update this vertex buffer into the GPU.
*
* \param indicesEnabled Set to true (default) if index buffer is relevant and should be uploaded.
*/
void update(bool indicesEnabled = true);
/** \brief Use this vertex buffer for rendering.
*
* \param op Program to use.
*/
void use(const Program *op) const;
public:
/** \brief Reset programmed vertex buffer.
*
* Must be done when changing a program.
*/
static void reset_programmed_vertex_buffer()
{
g_programmed_vertex_buffer = NULL;
}
/** \brief Unbind vertex buffer.
*/
static void unbind()
{
dnload_glBindBuffer(GL_ARRAY_BUFFER, 0);
dnload_glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
g_bound_vertex_buffer = NULL;
reset_programmed_vertex_buffer();
}
#if defined(USE_LD)
public:
/** \brief Print operator.
*
* \param lhs Left-hand-side operand.
* \param rhs Right-hand-side operand.
*/
friend std::ostream& operator<<(std::ostream &lhs, const VertexBuffer &rhs)
{
return lhs << "VertexBuffer(" << &rhs << ')';
}
#endif
};
#endif
| 20.067039 | 102 | 0.587695 |
trilkk
|
fb86376e6ae741650d8de5fa5d2b561ba273006b
| 821 |
cpp
|
C++
|
src/homework/01_variables/main.cpp
|
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-derekoko
|
437f55150491c2b89eb4ef730ac73d55a6ed07a2
|
[
"MIT"
] | null | null | null |
src/homework/01_variables/main.cpp
|
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-derekoko
|
437f55150491c2b89eb4ef730ac73d55a6ed07a2
|
[
"MIT"
] | null | null | null |
src/homework/01_variables/main.cpp
|
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-derekoko
|
437f55150491c2b89eb4ef730ac73d55a6ed07a2
|
[
"MIT"
] | null | null | null |
//write include statements
#include"variables.h"
//write namespace using statement for cout
using std::cin; using std::cout;
/*
Call multiply_numbers with 10 and 10 parameter values and display function result
*/
int main()
{
double meal_amount;
double tip_rate;
double tip_amount;
double tax_amount;
double total;
cout<<"Enter your meal amount here: ";
cin>>meal_amount;
tax_amount = get_sales_tax(meal_amount);
cout<<"Enter the percent tip here without the percent sign decimals: ";
cin>>tip_rate;
tip_amount = get_tip_amount(meal_amount, tip_rate);
total = tax_amount + meal_amount + tip_amount;
cout<<"\n"<<"Your meal amount is: "<<meal_amount<<"\n";
cout<<"The sales tax is: "<<tax_amount<<"\n";
cout<<"Your tip amount is: "<<tip_amount<<"\n";
cout<<"Your total is: "<<total;
return 0;
}
| 22.189189 | 81 | 0.713764 |
acc-cosc-1337-spring-2021
|
fb89a1953bc4610bc385e74a72e348ffbd2d2d3c
| 6,080 |
cc
|
C++
|
src/tlv.cc
|
kisom/klogger
|
f020356a894978579dc17fbb37cc81b515b86341
|
[
"MIT"
] | null | null | null |
src/tlv.cc
|
kisom/klogger
|
f020356a894978579dc17fbb37cc81b515b86341
|
[
"MIT"
] | null | null | null |
src/tlv.cc
|
kisom/klogger
|
f020356a894978579dc17fbb37cc81b515b86341
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2016 K. Isom <coder@kyleisom.net>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* 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 <cstdint>
#include <cstring>
#include <ctime>
#include <map>
#include <ostream>
#include <sstream>
#include <string>
#include <klogger/tlv.hh>
namespace klog {
namespace tlv {
static const char hexlut[] = "0123456789ABCDEF";
std::string
hex_encode(const std::string& s)
{
size_t length = s.size();
std::string out;
out.reserve(2 * length);
for (size_t i = 0; i < length; i++) {
unsigned char c = s[i];
out.push_back(hexlut[c >> 4]);
out.push_back(hexlut[c & 0xF]);
}
return out;
}
std::string
hex_encode(const char *s, size_t length)
{
std::string out;
out.reserve(2 * length);
for (size_t i = 0; i < length; i++) {
unsigned char c = s[i];
out.push_back(hexlut[c >> 4]);
out.push_back(hexlut[c & 0xF]);
}
return out;
}
static inline void
write_tag(std::ostream& outs, std::uint8_t t)
{
outs.write(reinterpret_cast<const char *>(&t), 1);
}
static inline size_t
length_octets(size_t length)
{
std::uint8_t loct = 1;
if (length <= 0x7F) {
return loct;
}
for (size_t i = (sizeof(length) * 8) - 1; i >= 1; i--) {
size_t bits = 1;
bits <<= i;
if (0 == (length & bits)) {
continue;
}
loct = (i + 8) >> 3;
break;
}
return loct;
}
bool
write_length(std::ostream &outs, size_t length)
{
std::uint8_t loct = 1;
if (length <= 0x7F) {
outs.write(reinterpret_cast<const char *>(&length), 1);
}
else {
for (size_t i = (sizeof(length) * 8) - 1; i >= 1; i--) {
size_t bits = 1;
bits <<= i;
if (0 == (length & bits)) {
continue;
}
loct = (i + 8) >> 3;
break;
}
loct = 0x80 + loct;
outs.write(reinterpret_cast<const char *>(&loct), 1);
if (!outs.good()) {
return false;
}
char buf[8];
::memcpy(buf, &length, 8);
size_t sz = sizeof(length);
for (size_t i = 0; i < sz / 2; i++) {
char tmp = buf[i];
buf[i] = buf[sz-i-1];
buf[sz-i-1] = tmp;
}
size_t off = 0;
for (size_t i = 0; i < sz; i++) {
if (0 != (buf[i] & 0xFF)) {
off = i;
break;
}
}
outs.write(reinterpret_cast<const char *>(buf+off), sz-off);
if (!outs.good()) {
return false;
}
}
return outs.good();
}
bool
write_timestamp(std::ostream &outs, uint64_t t)
{
write_tag(outs, TTimestamp);
if (!outs.good()) {
return false;
}
if (!write_length(outs, sizeof(t))) {
return false;
}
char buf[8];
::memcpy(buf, &t, sizeof(t));
size_t sz = sizeof(t);
for (size_t i = 0; i < sz / 2; i++) {
char tmp = buf[i];
buf[i] = buf[sz-i-1];
buf[sz-i-1] = tmp;
}
outs.write(reinterpret_cast<const char *>(buf), sz);
return outs.good();
}
bool
write_loglevel(std::ostream &outs, std::uint8_t lvl)
{
write_tag(outs, TLevel);
if (!outs.good()) {
return false;
}
if (!write_length(outs, sizeof(lvl))) {
return false;
}
outs.write(reinterpret_cast<const char *>(&lvl), sizeof(lvl));
return outs.good();
}
bool
write_string(std::ostream &outs, std::string s)
{
size_t length = s.size();
write_tag(outs, TString);
if (!outs.good()) {
return false;
}
if (!write_length(outs, length)) {
return false;
}
outs.write(reinterpret_cast<const char *>(s.c_str()), length);
return outs.good();
}
bool
write_header(std::ostream& outs, std::uint8_t tag, std::uint64_t length)
{
write_tag(outs, tag);
if (!outs.good()) {
return false;
}
return write_length(outs, length);
}
static inline size_t
string_record_length(std::string s)
{
size_t slen = s.size();
size_t length;
length = sizeof(TString);
length += length_octets(slen);
length += slen;
return length;
}
static inline size_t
log_length(std::string actor, std::string event,
std::map<std::string, std::string> attrs)
{
// Timestamp record is 1 byte tag + 1 byte length + 8 byte
// value (10 bytes total); level record is 1 byte tag +
// 1 byte length + 1 byte value (3 bytes).
size_t length = 13;
length += string_record_length(actor);
length += string_record_length(event);
for (auto it = attrs.begin(); it != attrs.end(); it++) {
length += string_record_length(it->first);
length += string_record_length(it->second);
}
return length;
}
bool
write_tlv_log(std::ostream& outs, std::uint8_t lvl,
std::string actor, std::string event,
std::map<std::string, std::string> attrs)
{
std::time_t t = std::time(nullptr);
size_t l = log_length(actor, event, attrs);
if (!write_header(outs, TLogEntry, static_cast<std::uint64_t>(l))) {
return false;
}
if (!write_timestamp(outs, std::uint64_t(t))) {
return false;
}
else if (!write_loglevel(outs, lvl)) {
return false;
}
else if (!write_string(outs, actor)) {
return false;
}
else if (!write_string(outs, event)) {
return false;
}
for (auto it = attrs.begin(); it != attrs.end(); it++) {
if (!write_string(outs, it->first)) {
return false;
}
else if (!write_string(outs, it->second)) {
return false;
}
}
return outs.good();
}
} // namespace tlv
} // namespace klog
| 19.74026 | 79 | 0.639967 |
kisom
|
fb8dfdff0a5ce1a0d6951b35bf37fef581793740
| 3,865 |
cpp
|
C++
|
src/graphics/graphicstool.cpp
|
quizzmaster/chemkit
|
803e4688b514008c605cb5c7790f7b36e67b68fc
|
[
"BSD-3-Clause"
] | 34 |
2015-01-24T23:59:41.000Z
|
2020-11-12T13:48:01.000Z
|
src/graphics/graphicstool.cpp
|
soplwang/chemkit
|
d62b7912f2d724a05fa8be757f383776fdd5bbcb
|
[
"BSD-3-Clause"
] | 4 |
2015-12-28T20:29:16.000Z
|
2016-01-26T06:48:19.000Z
|
src/graphics/graphicstool.cpp
|
soplwang/chemkit
|
d62b7912f2d724a05fa8be757f383776fdd5bbcb
|
[
"BSD-3-Clause"
] | 17 |
2015-01-23T14:50:24.000Z
|
2021-06-10T15:43:50.000Z
|
/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** 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 chemkit project 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.
**
******************************************************************************/
#include "graphicstool.h"
#include "graphicsview.h"
namespace chemkit {
// === GraphicsToolPrivate ================================================= //
class GraphicsToolPrivate
{
public:
GraphicsView *view;
};
// === GraphicsTool ======================================================== //
/// \class GraphicsTool graphicstool.h chemkit/graphicstool.h
/// \ingroup chemkit-graphics
/// \brief The GraphicsTool class handles graphics events for a
/// GraphicsView.
// --- Construction and Destruction ---------------------------------------- //
/// Creates a new graphics tool.
GraphicsTool::GraphicsTool()
: d(new GraphicsToolPrivate)
{
d->view = 0;
}
/// Destroys the graphics tool.
GraphicsTool::~GraphicsTool()
{
delete d;
}
// --- Properties ---------------------------------------------------------- //
/// Sets the view to \p view.
void GraphicsTool::setView(GraphicsView *view)
{
d->view = view;
}
/// Returns the view the tool is a part of. Returns \c 0 if the tool
/// is not in any view.
GraphicsView* GraphicsTool::view() const
{
return d->view;
}
// --- Event Handling------------------------------------------------------- //
/// Handle a mouse press event.
void GraphicsTool::mousePressEvent(QMouseEvent *event)
{
Q_UNUSED(event);
}
/// Handle a mouse release event.
void GraphicsTool::mouseReleaseEvent(QMouseEvent *event)
{
Q_UNUSED(event);
}
/// Handle a mouse double click event.
void GraphicsTool::mouseDoubleClickEvent(QMouseEvent *event)
{
Q_UNUSED(event);
}
/// Handle a mouse move event.
void GraphicsTool::mouseMoveEvent(QMouseEvent *event)
{
Q_UNUSED(event);
}
/// Handle a mouse wheel event.
void GraphicsTool::wheelEvent(QWheelEvent *event)
{
Q_UNUSED(event);
}
/// This method is called when the current tool in the view changes.
///
/// \see GraphicsView::setTool()
void GraphicsTool::toolChanged(const boost::shared_ptr<GraphicsTool> &tool)
{
Q_UNUSED(tool);
}
} // end chemkit namespace
| 31.422764 | 79 | 0.647348 |
quizzmaster
|
fb8f7882f0a2584cc00c2e975e9f7bbb17b6914f
| 679 |
hpp
|
C++
|
TinySandbox/src/GLFW_Windows.hpp
|
yanagiragi/TinySandbox
|
71c46d293535d8584edfa203e3b60d1d26982d2f
|
[
"MIT"
] | null | null | null |
TinySandbox/src/GLFW_Windows.hpp
|
yanagiragi/TinySandbox
|
71c46d293535d8584edfa203e3b60d1d26982d2f
|
[
"MIT"
] | null | null | null |
TinySandbox/src/GLFW_Windows.hpp
|
yanagiragi/TinySandbox
|
71c46d293535d8584edfa203e3b60d1d26982d2f
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Windows.hpp"
#include <GLFW/glfw3.h>
#include <functional>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void ProcessInput(GLFWwindow *window);
namespace TinySandbox {
class GLFW_Windows : public Windows
{
public:
GLFW_Windows();
GLFW_Windows(int width, int height, const char* title, ::GLFWmonitor *monitor, ::GLFWwindow *share);
~GLFW_Windows();
bool ShouldClose();
void Loop();
void SetInputCallback(std::function<void(GLFWwindow*)> _inputCallback);
GLFWwindow* GetGLFWInstance();
private:
GLFWwindow *m_glfwInstance;
std::function<void(GLFWwindow*)> inputCallback;
};
}
| 22.633333 | 103 | 0.717231 |
yanagiragi
|
fb903c1742ac6f9e4c4b351b8e66212743bfb982
| 3,098 |
cpp
|
C++
|
emitter/riscv/riscvannot_printer.cpp
|
nandor/genm-opt
|
b3347d508fff707837d1dc8232487ebfe157fe2a
|
[
"MIT"
] | 13 |
2020-06-25T18:26:54.000Z
|
2021-02-16T03:14:38.000Z
|
emitter/riscv/riscvannot_printer.cpp
|
nandor/genm-opt
|
b3347d508fff707837d1dc8232487ebfe157fe2a
|
[
"MIT"
] | 3 |
2020-07-01T01:39:47.000Z
|
2022-01-24T23:47:12.000Z
|
emitter/riscv/riscvannot_printer.cpp
|
nandor/genm-opt
|
b3347d508fff707837d1dc8232487ebfe157fe2a
|
[
"MIT"
] | 2 |
2021-03-11T05:08:09.000Z
|
2021-07-17T23:36:17.000Z
|
// This file if part of the llir-opt project.
// Licensing information can be found in the LICENSE file.
// (C) 2018 Nandor Licker. All rights reserved.
#include <sstream>
#include <llvm/Target/RISCV/RISCVInstrInfo.h>
#include <llvm/Target/RISCV/MCTargetDesc/RISCVMCTargetDesc.h>
#include "emitter/riscv/riscvannot_printer.h"
namespace RISCV = llvm::RISCV;
namespace TargetOpcode = llvm::TargetOpcode;
using TargetInstrInfo = llvm::TargetInstrInfo;
using StackVal = llvm::FixedStackPseudoSourceValue;
// -----------------------------------------------------------------------------
char RISCVAnnotPrinter::ID;
// -----------------------------------------------------------------------------
static const char *kRegNames[] =
{
"x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13",
"x14", "x15", "x16", "x17", "x18", "x19", "x20", "x21", "x22",
"x23", "x24", "x25", "x26", "x27", "x28", "x29", "x30", "x31",
};
// -----------------------------------------------------------------------------
RISCVAnnotPrinter::RISCVAnnotPrinter(
llvm::MCContext *ctx,
llvm::MCStreamer *os,
const llvm::MCObjectFileInfo *objInfo,
const llvm::DataLayout &layout,
const ISelMapping &mapping,
bool shared)
: AnnotPrinter(ID, ctx, os, objInfo, layout, mapping, shared)
{
}
// -----------------------------------------------------------------------------
RISCVAnnotPrinter::~RISCVAnnotPrinter()
{
}
// -----------------------------------------------------------------------------
std::optional<unsigned> RISCVAnnotPrinter::GetRegisterIndex(llvm::Register reg)
{
switch (reg) {
case RISCV::X5: return 0;
case RISCV::X6: return 1;
case RISCV::X7: return 2;
case RISCV::X8: return 3;
case RISCV::X9: return 4;
case RISCV::X10: return 5;
case RISCV::X11: return 6;
case RISCV::X12: return 7;
case RISCV::X13: return 8;
case RISCV::X14: return 9;
case RISCV::X15: return 10;
case RISCV::X16: return 11;
case RISCV::X17: return 12;
case RISCV::X18: return 13;
case RISCV::X19: return 14;
case RISCV::X20: return 15;
case RISCV::X21: return 16;
case RISCV::X22: return 17;
case RISCV::X23: return 18;
case RISCV::X24: return 19;
case RISCV::X25: return 20;
case RISCV::X26: return 21;
case RISCV::X27: return 22;
case RISCV::X28: return 23;
case RISCV::X29: return 24;
case RISCV::X30: return 25;
case RISCV::X31: return 26;
default: return std::nullopt;
}
}
// -----------------------------------------------------------------------------
llvm::StringRef RISCVAnnotPrinter::GetRegisterName(unsigned reg)
{
assert((reg < (sizeof(kRegNames) / sizeof(kRegNames[0]))) && "invalid reg");
return kRegNames[reg];
}
// -----------------------------------------------------------------------------
llvm::Register RISCVAnnotPrinter::GetStackPointer()
{
return RISCV::X2;
}
// -----------------------------------------------------------------------------
llvm::StringRef RISCVAnnotPrinter::getPassName() const
{
return "LLIR RISCV Annotation Inserter";
}
| 30.98 | 80 | 0.529051 |
nandor
|
651e7fd08deaafa93314db5fbb4c11ee3e139a7c
| 3,257 |
cc
|
C++
|
be/src/exec/parquet-common.cc
|
twmarshall/impala
|
bdd904922a220c37326928ac674779acaef5f6fa
|
[
"Apache-2.0"
] | 1 |
2019-12-14T03:09:50.000Z
|
2019-12-14T03:09:50.000Z
|
be/src/exec/parquet-common.cc
|
twmarshall/impala
|
bdd904922a220c37326928ac674779acaef5f6fa
|
[
"Apache-2.0"
] | null | null | null |
be/src/exec/parquet-common.cc
|
twmarshall/impala
|
bdd904922a220c37326928ac674779acaef5f6fa
|
[
"Apache-2.0"
] | null | null | null |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "exec/parquet-common.h"
namespace impala {
/// Mapping of impala's internal types to parquet storage types. This is indexed by
/// PrimitiveType enum
const parquet::Type::type INTERNAL_TO_PARQUET_TYPES[] = {
parquet::Type::BOOLEAN, // Invalid
parquet::Type::BOOLEAN, // NULL type
parquet::Type::BOOLEAN,
parquet::Type::INT32,
parquet::Type::INT32,
parquet::Type::INT32,
parquet::Type::INT64,
parquet::Type::FLOAT,
parquet::Type::DOUBLE,
parquet::Type::INT96, // Timestamp
parquet::Type::BYTE_ARRAY, // String
parquet::Type::BYTE_ARRAY, // Date, NYI
parquet::Type::BYTE_ARRAY, // DateTime, NYI
parquet::Type::BYTE_ARRAY, // Binary NYI
parquet::Type::FIXED_LEN_BYTE_ARRAY, // Decimal
parquet::Type::BYTE_ARRAY, // VARCHAR(N)
parquet::Type::BYTE_ARRAY, // CHAR(N)
};
const int INTERNAL_TO_PARQUET_TYPES_SIZE =
sizeof(INTERNAL_TO_PARQUET_TYPES) / sizeof(INTERNAL_TO_PARQUET_TYPES[0]);
/// Mapping of Parquet codec enums to Impala enums
const THdfsCompression::type PARQUET_TO_IMPALA_CODEC[] = {
THdfsCompression::NONE,
THdfsCompression::SNAPPY,
THdfsCompression::GZIP,
THdfsCompression::LZO
};
const int PARQUET_TO_IMPALA_CODEC_SIZE =
sizeof(PARQUET_TO_IMPALA_CODEC) / sizeof(PARQUET_TO_IMPALA_CODEC[0]);
/// Mapping of Impala codec enums to Parquet enums
const parquet::CompressionCodec::type IMPALA_TO_PARQUET_CODEC[] = {
parquet::CompressionCodec::UNCOMPRESSED,
parquet::CompressionCodec::SNAPPY, // DEFAULT
parquet::CompressionCodec::GZIP, // GZIP
parquet::CompressionCodec::GZIP, // DEFLATE
parquet::CompressionCodec::SNAPPY,
parquet::CompressionCodec::SNAPPY, // SNAPPY_BLOCKED
parquet::CompressionCodec::LZO,
};
const int IMPALA_TO_PARQUET_CODEC_SIZE =
sizeof(IMPALA_TO_PARQUET_CODEC) / sizeof(IMPALA_TO_PARQUET_CODEC[0]);
parquet::Type::type ConvertInternalToParquetType(PrimitiveType type) {
DCHECK_GE(type, 0);
DCHECK_LT(type, INTERNAL_TO_PARQUET_TYPES_SIZE);
return INTERNAL_TO_PARQUET_TYPES[type];
}
THdfsCompression::type ConvertParquetToImpalaCodec(
parquet::CompressionCodec::type codec) {
DCHECK_GE(codec, 0);
DCHECK_LT(codec, PARQUET_TO_IMPALA_CODEC_SIZE);
return PARQUET_TO_IMPALA_CODEC[codec];
}
parquet::CompressionCodec::type ConvertImpalaToParquetCodec(
THdfsCompression::type codec) {
DCHECK_GE(codec, 0);
DCHECK_LT(codec, IMPALA_TO_PARQUET_CODEC_SIZE);
return IMPALA_TO_PARQUET_CODEC[codec];
}
}
| 35.402174 | 83 | 0.753454 |
twmarshall
|
65201e989d10d77f9dfcfecc527d957232c2fa49
| 25,386 |
cpp
|
C++
|
ODFAEG/src/odfaeg/Graphics/GUI/filedialog.cpp
|
Mechap/ODFAEG
|
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
|
[
"Zlib"
] | null | null | null |
ODFAEG/src/odfaeg/Graphics/GUI/filedialog.cpp
|
Mechap/ODFAEG
|
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
|
[
"Zlib"
] | 1 |
2020-02-14T14:19:44.000Z
|
2020-12-04T17:39:17.000Z
|
ODFAEG/src/odfaeg/Graphics/GUI/filedialog.cpp
|
Mechap/ODFAEG
|
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
|
[
"Zlib"
] | 2 |
2021-05-23T13:45:28.000Z
|
2021-07-24T13:36:13.000Z
|
#include "../../../../include/odfaeg/Graphics/GUI/filedialog.hpp"
#include "../../../../include/odfaeg/Math/maths.h"
#include <filesystem>
namespace odfaeg {
namespace graphic {
namespace gui {
FileDialog::FileDialog(math::Vec3f position, math::Vec3f size, const Font* font) :
rw(sf::VideoMode(size.x, size.y), "File Dialog", sf::Style::Default, window::ContextSettings(0, 0, 0, 3, 0)),
LightComponent (rw, position, size, size * 0.5),
font(font) {
std::cout<<"position : "<<getPosition()<<std::endl;
rw.setPosition(sf::Vector2i(position.x, position.y));
pTop = new Panel (rw, position, size);
pBottom = new Panel (rw, position, size);
pDirectories = new Panel (rw, position, size);
pFiles = new Panel (rw, position, size);
lTop = new Label (rw, position, size, font, "", 15);
bChoose = new Button (position, size, font, "Choose", 15, rw);
bCancel = new Button (position, size, font, "Cancel", 15, rw);
pTop->setRelPosition(0.f, 0.f);
pTop->setRelSize(1.f, 0.1f);
pDirectories->setRelPosition(0.f, 0.1f);
pDirectories->setRelSize(0.5f, 0.8f);
pFiles->setRelPosition(0.5f, 0.1f);
pFiles->setRelSize(0.5f, 0.8f);
pBottom->setRelPosition(0.f, 0.9f);
pBottom->setRelSize(1.f, 0.1f);
pTop->setParent(this);
pBottom->setParent(this);
pDirectories->setParent(this);
pFiles->setParent(this);
addChild(pTop);
addChild(pBottom);
addChild(pDirectories);
addChild(pFiles);
lTop->setParent(pTop);
bChoose->setParent(pBottom);
bCancel->setParent(pBottom);
bChoose->addActionListener(this);
bCancel->addActionListener(this);
std::string currentPath = std::filesystem::current_path();
lTop->setRelPosition(0.f, 0.f);
lTop->setRelSize(1.f, 1.f);
lTop->setForegroundColor(sf::Color::Black);
pTop->addChild(lTop);
lTop->setText(currentPath);
lTop->setBackgroundColor(sf::Color::Red);
appliDir = lTop->getText();
std::string textDir;
#if defined (ODFAEG_SYSTEM_LINUX)
if (DIR* root = opendir("/")) {
dirent* ent;
unsigned int i = 0;
while((ent = readdir(root)) != NULL) {
if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) {
textDir = std::string(ent->d_name);
Label* lDirectory = new Label(rw, position, size, font, "",15);
//lDirectory->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255));
lDirectory->setParent(pDirectories);
lDirectory->setRelPosition(0.f, 0.04f * i);
lDirectory->setRelSize(1, 0.04f);
pDirectories->addChild(lDirectory);
lDirectory->setText(sf::String(textDir));
core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left);
core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lDirectory), core::FastDelegate<void>(&FileDialog::onDirSelected, this, lDirectory));
if(ent->d_type == DT_DIR) {
lDirectory->setForegroundColor(sf::Color::Red);
getListener().connect("1d"+textDir, cmd);
} else {
getListener().connect("1f"+textDir, cmd);
}
i++;
}
}
}
currentPath = lTop->getText();
if (DIR* current = opendir(currentPath.c_str())) {
dirent *ent;
std::string fileNames;
unsigned int i = 0;
while ((ent = readdir(current)) != NULL) {
if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) {
fileNames = std::string(ent->d_name);
Label* lFile = new Label(rw, position, size, font, "",15);
//lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255));
lFile->setParent(pFiles);
lFile->setRelPosition(0.f, 0.04f * i);
lFile->setRelSize(1.f, 0.04f);
pFiles->addChild(lFile);
lFile->setText(sf::String(fileNames));
core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left);
core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile));
if(ent->d_type == DT_DIR) {
lFile->setForegroundColor(sf::Color::Red);
getListener().connect("2d"+fileNames, cmd);
} else {
getListener().connect("2f"+fileNames, cmd);
}
i++;
}
}
}
#else if defined(ODFAEG_SYSTEM_WINDOWS)
if (DIR* root = opendir("C:\\")) {
dirent* ent;
struct stat st;
unsigned int i = 0;
while((ent = readdir(root)) != NULL) {
if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) {
textDir = std::string(ent->d_name);
std::string fullPath = "C:\\" + textDir;
stat(fullPath.c_str(), &st);
Label* lDirectory = new Label(rw, position, size, font, "",15);
//lDirectory->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255));
lDirectory->setParent(pDirectories);
lDirectory->setRelPosition(0.f, 0.04f * i);
lDirectory->setRelSize(1, 0.04f);
pDirectories->addChild(lDirectory);
lDirectory->setText(textDir);
core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left);
core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lDirectory), core::FastDelegate<void>(&FileDialog::onDirSelected, this, lDirectory));
if(S_ISDIR(st.st_mode)) {
lDirectory->setForegroundColor(sf::Color::Red);
getListener().connect("1d"+textDir, cmd);
} else {
lDirectory->setForegroundColor(sf::Color::Black);
getListener().connect("1f"+textDir, cmd);
}
i++;
}
}
}
currentPath = lTop->getText();
if (DIR* current = opendir(currentPath.c_str())) {
dirent *ent;
struct stat st;
std::string fileNames;
unsigned int i = 0;
while ((ent = readdir(current)) != NULL) {
if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) {
fileNames = std::string(ent->d_name);
stat(fileNames.c_str(), &st);
Label* lFile = new Label(rw, position, size, font, "",15);
//lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255));
lFile->setParent(pFiles);
lFile->setRelPosition(0.f, 0.04f * i);
lFile->setRelSize(1.f, 0.04f);
pFiles->addChild(lFile);
lFile->setText(fileNames);
core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left);
core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile));
if(S_ISDIR(st.st_mode)) {
lFile->setForegroundColor(sf::Color::Red);
getListener().connect("2d"+fileNames, cmd);
} else {
lFile->setForegroundColor(sf::Color::Black);
getListener().connect("2f"+fileNames, cmd);
}
i++;
}
}
}
#endif
bChoose->setRelPosition(0.7f, 0.1f);
bChoose->setRelSize(0.1f, 0.8f);
bChoose->setParent(pBottom);
pBottom->addChild(bChoose);
bCancel->setRelPosition(0.85f, 0.1f);
bCancel->setRelSize(0.1f, 0.8f);
bCancel->setParent(pBottom);
pBottom->addChild(bCancel);
setRelPosition(0, 0);
setRelSize(1, 1);
setAutoResized(true);
}
void FileDialog::clear() {
rw.clear();
pTop->clear();
pBottom->clear();
pDirectories->clear();
pFiles->clear();
}
void FileDialog::onDraw(RenderTarget& target, RenderStates states) {
//if (rw.isOpen()) {
target.draw(*pTop, states);
target.draw(*pDirectories, states);
target.draw(*pFiles, states);
target.draw(*pBottom, states);
//}
}
void FileDialog::onDirSelected(Label* label) {
for (unsigned int i = 0; i < pFiles->getChildren().size(); i++) {
if (static_cast<Label*>(pFiles->getChildren()[i])->getForegroundColor() == sf::Color::Red) {
getListener().removeCommand("2d"+static_cast<Label*>(pFiles->getChildren()[i])->getText());
} else {
getListener().removeCommand("2f"+static_cast<Label*>(pFiles->getChildren()[i])->getText());
}
}
pFiles->removeAll();
for (unsigned int i = 0; i < pDirectories->getChildren().size(); i++) {
static_cast<Label*>(pDirectories->getChildren()[i])->setBackgroundColor(sf::Color::Black);
}
std::string dirName;
#if defined (ODFAEG_SYSTEM_LINUX)
dirName = "/" + label->getText();
#else if defined (ODFAEG_SYSTEM_WINDOWS)
dirName = "C:\\" + label->getText();
#endif // if
std::string currentDir = dirName;
lTop->setText(currentDir);
label->setBackgroundColor(sf::Color::Blue);
if (label->getForegroundColor() == sf::Color::Red) {
#if defined (ODFAEG_SYSTEM_LINUX)
if (DIR* current = opendir(dirName.c_str())) {
dirent *ent;
std::string fileNames;
unsigned int i = 0;
while ((ent = readdir(current)) != NULL) {
if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) {
fileNames = std::string(ent->d_name);
Label* lFile = new Label(rw, getPosition(), getSize(), font, "",15);
//lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255));
lFile->setParent(pFiles);
lFile->setRelPosition(0.f, 0.04f * i);
lFile->setRelSize(1.f, 0.04f);
pFiles->addChild(lFile);
lFile->setText(fileNames);
core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left);
core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile));
if(ent->d_type == DT_DIR) {
lFile->setForegroundColor(sf::Color::Red);
getListener().connect("2d"+fileNames, cmd);
} else {
getListener().connect("2f"+fileNames, cmd);
}
i++;
}
}
closedir(current);
}
#else if defined (ODFAEG_SYSTEM_WINDOWS)
if (DIR* current = opendir(dirName.c_str())) {
dirent *ent;
struct stat st;
std::string fileNames;
unsigned int i = 0;
while ((ent = readdir(current)) != NULL) {
if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) {
fileNames = std::string(ent->d_name);
std::string fullPath = currentDir + "\\" + fileNames;
stat(fullPath.c_str(), &st);
Label* lFile = new Label(rw, getPosition(), getSize(), font, "",15);
//lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255));
lFile->setParent(pFiles);
lFile->setRelPosition(0.f, 0.04f * i);
lFile->setRelSize(1.f, 0.04f);
lFile->setName("LFILE");
pFiles->addChild(lFile);
lFile->setText(fileNames);
core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left);
core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile));
if(S_ISDIR(st.st_mode)) {
lFile->setForegroundColor(sf::Color::Red);
getListener().connect("2d"+fileNames, cmd);
} else {
lFile->setForegroundColor(sf::Color::Black);
getListener().connect("2f"+fileNames, cmd);
}
i++;
}
}
closedir(current);
}
#endif
}
setAutoResized(true);
}
void FileDialog::onFileSelected(Label* label) {
std::string fileName = label->getText();
sf::Color color = label->getForegroundColor();
if (color == sf::Color::Red) {
for (unsigned int i = 0; i < pFiles->getChildren().size(); i++) {
if (static_cast<Label*>(pFiles->getChildren()[i])->getForegroundColor() == sf::Color::Red) {
if (static_cast<Label*>(pFiles->getChildren()[i])->getText() == label->getText())
getListener().removeLater("2d"+static_cast<Label*>(pFiles->getChildren()[i])->getText());
else
getListener().removeCommand("2d"+static_cast<Label*>(pFiles->getChildren()[i])->getText());
} else {
if (static_cast<Label*>(pFiles->getChildren()[i])->getText() == label->getText())
getListener().removeLater("2f"+static_cast<Label*>(pFiles->getChildren()[i])->getText());
else
getListener().removeCommand("2f"+static_cast<Label*>(pFiles->getChildren()[i])->getText());
}
}
pFiles->removeAll();
std::string currentDir = lTop->getText();
#if defined (ODFAEG_SYSTEM_LINUX)
currentDir += "/"+fileName;
#else if defined (ODFAEG_SYSTEM_WINDOWS)
currentDir += "\\"+fileName;
#endif // if
lTop->setText(currentDir);
#if defined (ODFAEG_SYSTEM_LINUX)
if (DIR* current = opendir(currentDir.c_str())) {
dirent *ent;
std::string fileNames;
unsigned int i = 0;
while ((ent = readdir(current)) != NULL) {
if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) {
fileNames = std::string(ent->d_name);
Label* lFile = new Label(rw, getPosition(), getSize(), font, "",15);
//lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255));
lFile->setParent(pFiles);
lFile->setRelPosition(0.f, 0.04f * i);
lFile->setRelSize(1.f, 0.04f);
pFiles->addChild(lFile);
lFile->setText(fileNames);
core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left);
core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile));
if(ent->d_type == DT_DIR) {
lFile->setForegroundColor(sf::Color::Red);
getListener().connect("2d"+fileNames, cmd);
} else {
getListener().connect("2f"+fileNames, cmd);
}
i++;
}
}
closedir(current);
}
#else if defined (ODFAEG_SYSTEM_WINDOWS)
if (DIR* current = opendir(currentDir.c_str())) {
dirent *ent;
struct stat st;
std::string fileNames;
unsigned int i = 0;
while ((ent = readdir(current)) != NULL) {
if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) {
fileNames = std::string(ent->d_name);
std::string fullPath = currentDir + "\\" + fileNames;
stat(fullPath.c_str(), &st);
Label* lFile = new Label(rw, getPosition(), getSize(), font, "",15);
//lFile->setBackgroundColor(sf::Color(math::Math::random(0, 255),math::Math::random(0, 255), math::Math::random(0, 255), 255));
lFile->setParent(pFiles);
lFile->setRelPosition(0.f, 0.04f * i);
lFile->setRelSize(1.f, 0.04f);
pFiles->addChild(lFile);
lFile->setText(fileNames);
lFile->setName("LFILE");
core::Action a (core::Action::EVENT_TYPE::MOUSE_BUTTON_PRESSED_ONCE, window::IMouse::Left);
core::Command cmd (a, core::FastDelegate<bool>(&Label::isMouseInside, lFile), core::FastDelegate<void>(&FileDialog::onFileSelected, this, lFile));
if(S_ISDIR(st.st_mode)) {
lFile->setForegroundColor(sf::Color::Red);
getListener().connect("2d"+fileNames, cmd);
} else {
lFile->setForegroundColor(sf::Color::Black);
getListener().connect("2f"+fileNames, cmd);
}
i++;
}
}
closedir(current);
}
#endif
} else {
for (unsigned int i = 0; i < pFiles->getChildren().size(); i++) {
static_cast<Label*>(pFiles->getChildren()[i])->setBackgroundColor(sf::Color::Black);
}
label->setBackgroundColor(sf::Color::Blue);
}
setAutoResized(true);
}
std::string FileDialog::getPathChosen() {
std::string path = pathChosen;
pathChosen = "";
return path;
}
std::string FileDialog::getAppiDir() {
return appliDir;
}
void FileDialog::onEventPushed(window::IEvent event, RenderWindow& window) {
if (event.type == window::IEvent::WINDOW_EVENT
&& event.mouseButton.type == window::IEvent::WINDOW_EVENT_CLOSED) {
rw.setVisible(false);
}
/*for (unsigned int i = 0; i < pDirectories.getChildren().size(); i++) {
pDirectories.getChildren()[i]->onUpdate(&getWindow(), event);
}
for (unsigned int i = 0; i < pFiles.getChildren().size(); i++) {
pFiles.getChildren()[i]->onUpdate(&getWindow(), event);
}
bChoose.onUpdate(&getWindow(), event);
bCancel.onUpdate(&getWindow(), event);
getListener().pushEvent(event);
bChoose.getListener().pushEvent(event);
bCancel.getListener().pushEvent(event);*/
}
void FileDialog::onVisibilityChanged(bool visible) {
rw.setVisible(visible);
}
void FileDialog::actionPerformed(Button* button) {
if (button->getText() == "Choose") {
for (unsigned int i = 0; i < pDirectories->getChildren().size(); i++) {
Label* label = static_cast<Label*>(pDirectories->getChildren()[i]);
if (label->getForegroundColor() == sf::Color::Black
&& label->getBackgroundColor() == sf::Color::Blue) {
pathChosen = lTop->getText();
return;
}
}
for (unsigned int i = 0; i < pFiles->getChildren().size(); i++) {
Label* label = static_cast<Label*>(pFiles->getChildren()[i]);
if (label->getForegroundColor() == sf::Color::Black
&& label->getBackgroundColor() == sf::Color::Blue) {
#if defined (ODFAEG_SYSTEM_LINUX)
pathChosen = lTop->getText()+"/"+label->getText();
#else if defined (ODFAEG_SYSTEM_WINDOWS)
pathChosen = lTop->getText()+"\\"+label->getText();
#endif // if
}
}
} else if (button->getText() == "Cancel") {
rw.setVisible(false);
}
}
}
}
}
| 59.174825 | 183 | 0.430986 |
Mechap
|
65268449db5d310967a2853f69e9940460ebe922
| 1,271 |
cpp
|
C++
|
Mragpp/Paths.cpp
|
codecat/MragPP
|
96c1c5474ea552f364e6c04da7cc72923fdade0a
|
[
"MIT"
] | 1 |
2017-06-26T20:44:44.000Z
|
2017-06-26T20:44:44.000Z
|
Mragpp/Paths.cpp
|
codecat/MragPP
|
96c1c5474ea552f364e6c04da7cc72923fdade0a
|
[
"MIT"
] | null | null | null |
Mragpp/Paths.cpp
|
codecat/MragPP
|
96c1c5474ea552f364e6c04da7cc72923fdade0a
|
[
"MIT"
] | null | null | null |
#include "StdH.h"
#include "Paths.h"
MRAGPP_NAMESPACE_BEGIN;
CPaths::CPaths()
{
ps_iIterator = 0;
}
CPaths::~CPaths()
{
ps_aPaths.Clear();
}
CPath& CPaths::Create(const Vector2f &vPos1, const Vector2f &vPos2, int iTotalFrameCount,
mragPathsOnUpdateFunction onUpdate, mragPathsOnFinishFunction onFinish)
{
CPath &newPath = ps_aPaths.Push();
newPath.p_pPaths = this;
newPath.p_vPos1 = vPos1;
newPath.p_vPos2 = vPos2;
newPath.p_iTotalFrameCount = iTotalFrameCount;
newPath.p_pOnUpdate = onUpdate;
newPath.p_pOnFinish = onFinish;
return newPath;
}
CPath& CPaths::Create(const Vector2f &vPos1, const Vector2f &vPos2, float fSeconds,
mragPathsOnUpdateFunction onUpdate, mragPathsOnFinishFunction onFinish)
{
return Create(vPos1, vPos2, (int)ceil(fSeconds / 0.0166667f), onUpdate, onFinish);
}
void CPaths::Update()
{
for(int i=0; i<ps_aPaths.Count(); i++) {
ps_aPaths[i].p_bReady = true;
}
for(ps_iIterator=0; ps_iIterator<ps_aPaths.Count(); ps_iIterator++) {
if(!ps_aPaths[ps_iIterator].p_bReady) {
continue;
}
ps_aPaths[ps_iIterator].Update();
}
}
void CPaths::Render()
{
for(ps_iIterator=0; ps_iIterator<ps_aPaths.Count(); ps_iIterator++) {
ps_aPaths[ps_iIterator].Render();
}
}
MRAGPP_NAMESPACE_END;
| 22.298246 | 89 | 0.721479 |
codecat
|
65292232ffd58a136fbded3f7dca65106452dc4d
| 5,051 |
cpp
|
C++
|
src/nao_speech.cpp
|
sheosi/nao_auto_bridge
|
d5593219abacc56684c537f042d24ef89fcc94d3
|
[
"BSD-3-Clause"
] | null | null | null |
src/nao_speech.cpp
|
sheosi/nao_auto_bridge
|
d5593219abacc56684c537f042d24ef89fcc94d3
|
[
"BSD-3-Clause"
] | null | null | null |
src/nao_speech.cpp
|
sheosi/nao_auto_bridge
|
d5593219abacc56684c537f042d24ef89fcc94d3
|
[
"BSD-3-Clause"
] | null | null | null |
#include "nao_auto_bridge.h"
#include <boost/algorithm/string/join.hpp>
#include <iostream>
#include <vector>
#include <ros/ros.h>
#include <actionlib/server/simple_action_server.h>
#include <naoqi_bridge_msgs/SpeechWithFeedbackAction.h>
#include <naoqi_bridge_msgs/SetSpeechVocabularyAction.h>
#include <naoqi_bridge_msgs/WordRecognized.h>
#include <std_msgs/String.h>
#include <std_srvs/Empty.h>
using std::string;
void SimulatedNao::OnSpeechActionGoal(const string& text) {
//Note: We could replicate behaviour
ROS_INFO("Nao said: %s", text.c_str());
}
void SimulatedNao::OnSpeechVocabularyAction(const std::vector<string>& words) {
//Note: We could replicate behaviour
const string joined = boost::algorithm::join(words, ",");
ROS_INFO("Words recognized set: %s", joined.c_str());
}
void SimulatedNao::OnSpeech(const string& text) {
//Note: We could replicate behaviour
ROS_INFO("Nao said: %s", text.c_str());
}
void SimulatedNao::OnReconfigure() {
//Note: We could replicate behaviour
ROS_INFO("Speech reconfigured");
}
void SimulatedNao::OnStartRecognition() {
//Note: We could replicate behaviour
if (!this->speech_data.recognition_started) {
ROS_INFO("Recognition started");
this->speech_data.recognition_started = true;
}
else {
ROS_INFO("Tried to start recognition, but it was already started by another node");
}
}
void SimulatedNao::OnStopRecognition() {
//Note: We could replicate behaviour
if (this->speech_data.recognition_started) {
ROS_INFO("Recognition stopped");
this->speech_data.recognition_started = false;
}
else {
ROS_INFO("Tried top stop recognition, but it is already stopped");
}
}
namespace BridgeNaoSpeech {
std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SpeechWithFeedbackAction>> act_srv_speech_action_goal;
std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SetSpeechVocabularyAction>> act_srv_speech_vocabulary_action;
ros::Subscriber sub_speech;
ros::ServiceServer srv_reconfigure,
srv_start_recognition,
srv_stop_recognition;
void on_speech_action_goal(
const naoqi_bridge_msgs::SpeechWithFeedbackGoalConstPtr &goal
) {
nao_connection.OnSpeechActionGoal(goal->say);
naoqi_bridge_msgs::SpeechWithFeedbackResult result;
act_srv_speech_action_goal->setSucceeded(result);
}
void on_speech_vocabulary_action(
const naoqi_bridge_msgs::SetSpeechVocabularyGoalConstPtr &goal
) {
nao_connection.OnSpeechVocabularyAction(goal->words);
naoqi_bridge_msgs::SetSpeechVocabularyResult result;
act_srv_speech_vocabulary_action->setSucceeded(result);
}
void on_speech(
const std_msgs::StringConstPtr &msg
) {
nao_connection.OnSpeech(msg->data);
}
bool on_reconfigure(
std_srvs::Empty::Request &req,
std_srvs::Empty::Response &resp
){
nao_connection.OnReconfigure();
return true;
}
bool on_start_recognition(
std_srvs::Empty::Request &req,
std_srvs::Empty::Response &resp
){
nao_connection.OnStartRecognition();
return true;
}
bool on_stop_recognition(
std_srvs::Empty::Request &req,
std_srvs::Empty::Response &resp
){
nao_connection.OnStopRecognition();
return true;
}
void init(ros::NodeHandle &n) {
std::string voice, language;
float volume;
std::vector<std::string> vocabulary;
bool enable_audio_expression, enable_visual_expression, word_spoting;
n.param("voice", voice, std::string(""));
n.param("language", language, std::string(""));
n.param("volume", volume, 0.0f);
n.param("vocabulary", vocabulary, std::vector<std::string>());
n.param("enable_audio_expression", enable_audio_expression, false);
n.param("enable_visual_expression", enable_visual_expression, false);
n.param("word_spoting", word_spoting, false);
act_srv_speech_action_goal =
std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SpeechWithFeedbackAction>>(
new actionlib::SimpleActionServer<naoqi_bridge_msgs::SpeechWithFeedbackAction>(n, "speech_action/goal", on_speech_action_goal, true));
act_srv_speech_vocabulary_action =
std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SetSpeechVocabularyAction>>(
new actionlib::SimpleActionServer<naoqi_bridge_msgs::SetSpeechVocabularyAction>(n, "/speech_vocabulary_action/goal", on_speech_vocabulary_action, true));
sub_speech = n.subscribe("speech", 1000, on_speech);
srv_reconfigure = n.advertiseService("reconfigure", on_reconfigure);
srv_start_recognition = n.advertiseService("start_recognition", on_start_recognition);
srv_stop_recognition = n.advertiseService("stop_recognition", on_stop_recognition);
}
}
| 35.076389 | 165 | 0.703623 |
sheosi
|
652d3e39002c919df906a77e8bbecd68705eaaa1
| 141,050 |
cpp
|
C++
|
src/editor.cpp
|
TijmenUU/VVVVVV
|
ce6c07c800f3dce98e0bd40f32311b98a01a4cd6
|
[
"RSA-MD"
] | null | null | null |
src/editor.cpp
|
TijmenUU/VVVVVV
|
ce6c07c800f3dce98e0bd40f32311b98a01a4cd6
|
[
"RSA-MD"
] | null | null | null |
src/editor.cpp
|
TijmenUU/VVVVVV
|
ce6c07c800f3dce98e0bd40f32311b98a01a4cd6
|
[
"RSA-MD"
] | null | null | null |
#include <Entity.hpp>
#include <Graphics.hpp>
#include <KeyPoll.hpp>
#include <Map.hpp>
#include <Music.hpp>
#include <Script.hpp>
#include <editor.hpp>
//#include "UtilityClass.h"
#include <Enums.hpp>
#include <FileSystemUtils.hpp>
#include <ctime>
#include <string>
#include <tinyxml/tinyxml.hpp>
edlevelclass::edlevelclass()
{
tileset = 0;
tilecol = 0;
roomname = "";
warpdir = 0;
platx1 = 0;
platy1 = 0;
platx2 = 320;
platy2 = 240;
platv = 4;
enemyx1 = 0;
enemyy1 = 0;
enemyx2 = 320;
enemyy2 = 240;
enemytype = 0;
directmode = 0;
}
editorclass::editorclass()
{
maxwidth = 20;
maxheight = 20;
//We create a blank map
for(int j = 0; j < 30 * maxwidth; j++)
{
for(int i = 0; i < 40 * maxheight; i++)
{
contents.push_back(0);
}
}
for(int j = 0; j < 30; j++)
{
for(int i = 0; i < 40; i++)
{
swapmap.push_back(0);
}
}
for(int i = 0; i < 30 * maxheight; i++)
{
vmult.push_back(int(i * 40 * maxwidth));
}
reset();
}
// comparison, not case sensitive.
bool compare_nocase(std::string first, std::string second)
{
unsigned int i = 0;
while((i < first.length()) && (i < second.length()))
{
if(tolower(first[i]) < tolower(second[i]))
return true;
else if(tolower(first[i]) > tolower(second[i]))
return false;
++i;
}
if(first.length() < second.length())
return true;
else
return false;
}
void editorclass::getDirectoryData()
{
ListOfMetaData.clear();
directoryList.clear();
directoryList = FILESYSTEM_getLevelDirFileNames();
for(size_t i = 0; i < directoryList.size(); i++)
{
LevelMetaData temp;
if(getLevelMetaData(directoryList[i], temp))
{
ListOfMetaData.push_back(temp);
}
}
for(size_t i = 0; i < ListOfMetaData.size(); i++)
{
for(size_t k = 0; k < ListOfMetaData.size(); k++)
{
if(compare_nocase(ListOfMetaData[i].title, ListOfMetaData[k].title))
{
std::swap(ListOfMetaData[i], ListOfMetaData[k]);
std::swap(directoryList[i], directoryList[k]);
}
}
}
}
bool editorclass::getLevelMetaData(std::string & _path, LevelMetaData & _data)
{
unsigned char * mem = NULL;
FILESYSTEM_loadFileToMemory(_path.c_str(), &mem, NULL);
if(mem == NULL)
{
printf("Level %s not found :(\n", _path.c_str());
return false;
}
TiXmlDocument doc;
doc.Parse((const char *)mem);
FILESYSTEM_freeMemory(&mem);
TiXmlHandle hDoc(&doc);
TiXmlElement * pElem;
TiXmlHandle hRoot(0);
{
pElem = hDoc.FirstChildElement().Element();
// should always have a valid root but handle gracefully if it does
if(!pElem)
{
printf("No valid root! Corrupt level file?\n");
}
// save this for later
hRoot = TiXmlHandle(pElem);
}
for(pElem = hRoot.FirstChild("Data").FirstChild().Element(); pElem; pElem = pElem->NextSiblingElement())
{
std::string pKey(pElem->Value());
const char * pText = pElem->GetText();
if(pText == NULL)
{
pText = "";
}
if(pKey == "MetaData")
{
for(TiXmlElement * subElem = pElem->FirstChildElement(); subElem; subElem = subElem->NextSiblingElement())
{
std::string pKey(subElem->Value());
const char * pText = subElem->GetText();
if(pText == NULL)
{
pText = "";
}
_data.filename = _path;
if(pKey == "Created")
{
_data.timeCreated = pText;
}
if(pKey == "Creator")
{
_data.creator = pText;
}
if(pKey == "Title")
{
_data.title = pText;
}
if(pKey == "Modified")
{
_data.timeModified = pText;
}
if(pKey == "Modifiers")
{
_data.modifier = pText;
}
if(pKey == "Desc1")
{
_data.Desc1 = pText;
}
if(pKey == "Desc2")
{
_data.Desc2 = pText;
}
if(pKey == "Desc3")
{
_data.Desc3 = pText;
}
if(pKey == "website")
{
_data.website = pText;
}
}
}
}
return (_data.filename != "");
}
void editorclass::reset()
{
version = 2; //New smaller format change is 2
mapwidth = 5;
mapheight = 5;
EditorData::GetInstance().title = "Untitled Level";
EditorData::GetInstance().creator = "Unknown";
Desc1 = "";
Desc2 = "";
Desc3 = "";
website = "";
roomnamehide = 0;
zmod = false;
xmod = false;
spacemod = false;
spacemenu = 0;
shiftmenu = false;
shiftkey = false;
saveandquit = false;
note = "";
notedelay = 0;
roomnamemod = false;
textentry = false;
savemod = false;
loadmod = false;
deletekeyheld = false;
titlemod = false;
creatormod = false;
desc1mod = false;
desc2mod = false;
desc3mod = false;
websitemod = false;
settingsmod = false;
warpmod = false; //Two step process
warpent = -1;
boundarymod = 0;
boundarytype = 0;
boundx1 = 0;
boundx2 = 0;
boundy1 = 0;
boundy2 = 0;
scripttextmod = false;
scripttextent = 0;
scripttexttype = 0;
drawmode = 0;
dmtile = 0;
dmtileeditor = 0;
entcol = 0;
tilex = 0;
tiley = 0;
levx = 0;
levy = 0;
keydelay = 0;
lclickdelay = 0;
savekey = false;
loadkey = false;
updatetiles = true;
changeroom = true;
levmusic = 0;
entframe = 0;
entframedelay = 0;
numtrinkets = 0;
numcrewmates = 0;
EditorData::GetInstance().numedentities = 0;
levmusic = 0;
roomtextmod = false;
roomtextent = 0;
for(int j = 0; j < maxheight; j++)
{
for(int i = 0; i < maxwidth; i++)
{
level[i + (j * maxwidth)].tileset = 0;
level[i + (j * maxwidth)].tilecol = (i + j) % 32;
level[i + (j * maxwidth)].roomname = "";
level[i + (j * maxwidth)].warpdir = 0;
level[i + (j * maxwidth)].platx1 = 0;
level[i + (j * maxwidth)].platy1 = 0;
level[i + (j * maxwidth)].platx2 = 320;
level[i + (j * maxwidth)].platy2 = 240;
level[i + (j * maxwidth)].platv = 4;
level[i + (j * maxwidth)].enemyx1 = 0;
level[i + (j * maxwidth)].enemyy1 = 0;
level[i + (j * maxwidth)].enemyx2 = 320;
level[i + (j * maxwidth)].enemyy2 = 240;
}
}
for(int j = 0; j < 30 * maxwidth; j++)
{
for(int i = 0; i < 40 * maxheight; i++)
{
contents[i + (j * 30 * maxwidth)] = 0;
}
}
if(numhooks > 0)
{
for(int i = 0; i < numhooks; i++)
{
removehook(hooklist[i]);
}
}
for(int i = 0; i < 500; i++)
{
sb[i] = "";
}
for(int i = 0; i < 500; i++)
{
hooklist[i] = "";
}
clearscriptbuffer();
sblength = 1;
sbx = 0;
sby = 0;
pagey = 0;
scripteditmod = false;
sbscript = "null";
scripthelppage = 0;
scripthelppagedelay = 0;
hookmenupage = 0;
hookmenu = 0;
numhooks = 0;
script.customscript.clear();
}
void editorclass::weirdloadthing(std::string t)
{
//Stupid pointless function because I hate C++ and everything to do with it
//It's even stupider now that I don't need to append .vvvvvv anymore! bah, whatever
//t=t+".vvvvvv";
load(t);
}
void editorclass::gethooks()
{
//Scan through the script and create a hooks list based on it
numhooks = 0;
std::string tstring;
std::string tstring2;
for(size_t i = 0; i < script.customscript.size(); i++)
{
tstring = script.customscript[i];
if((int)tstring.length() - 1 >= 0) // FIXME: This is sketchy. -flibit
{
tstring = tstring[tstring.length() - 1];
}
else
{
tstring = "";
}
if(tstring == ":")
{
tstring2 = "";
tstring = script.customscript[i];
for(size_t j = 0; j < tstring.length() - 1; j++)
{
tstring2 += tstring[j];
}
hooklist[numhooks] = tstring2;
numhooks++;
}
}
}
void editorclass::loadhookineditor(std::string t)
{
//Find hook t in the scriptclass, then load it into the editor
clearscriptbuffer();
std::string tstring;
bool removemode = false;
for(size_t i = 0; i < script.customscript.size(); i++)
{
if(script.customscript[i] == t + ":")
{
removemode = true;
}
else if(removemode)
{
tstring = script.customscript[i];
if(tstring != "")
{
tstring = tstring[tstring.length() - 1];
}
if(tstring == ":")
{
//this is a hook
removemode = false;
}
else
{
//load in this line
sb[sblength - 1] = script.customscript[i];
sblength++;
}
}
}
if(sblength > 1)
sblength--;
}
void editorclass::addhooktoscript(std::string t)
{
//Adds hook+the scriptbuffer to the end of the scriptclass
removehookfromscript(t);
script.customscript.push_back(t + ":");
if(sblength >= 1)
{
for(int i = 0; i < sblength; i++)
{
script.customscript.push_back(sb[i]);
}
}
}
void editorclass::removehookfromscript(std::string t)
{
//Find hook t in the scriptclass, then removes it (and any other code with it)
std::string tstring;
bool removemode = false;
for(size_t i = 0; i < script.customscript.size(); i++)
{
if(script.customscript[i] == t + ":")
{
removemode = true;
//Remove this line
for(size_t j = i; j < script.customscript.size() - 1; j++)
{
script.customscript[j] = script.customscript[j + 1];
}
script.customscript.pop_back();
i--;
}
else if(removemode)
{
//If this line is not the start of a new hook, remove it!
tstring = script.customscript[i];
tstring = tstring[tstring.length() - 1];
if(tstring == ":")
{
//this is a hook
removemode = false;
}
else
{
//Remove this line
for(size_t j = i; j < script.customscript.size() - 1; j++)
{
script.customscript[j] = script.customscript[j + 1];
}
script.customscript.pop_back();
i--;
}
}
}
}
void editorclass::removehook(std::string t)
{
//Check the hooklist for the hook t. If it's there, remove it from here and the script
for(int i = 0; i < numhooks; i++)
{
if(hooklist[i] == t)
{
removehookfromscript(t);
for(int j = i; j < numhooks; j++)
{
hooklist[j] = hooklist[j + 1];
}
hooklist[numhooks] = "";
numhooks--;
i--;
}
}
}
void editorclass::addhook(std::string t)
{
//Add an empty function to the list in both editor and script
removehook(t);
hooklist[numhooks] = t;
numhooks++;
addhooktoscript(t);
}
bool editorclass::checkhook(std::string t)
{
//returns true if hook t already is in the list
for(int i = 0; i < numhooks; i++)
{
if(hooklist[i] == t)
return true;
}
return false;
}
void editorclass::clearscriptbuffer()
{
for(int i = 0; i < sblength + 1; i++)
{
sb[i] = "";
}
sblength = 1;
}
void editorclass::removeline(int t)
{
//Remove line t from the script
if(sblength > 0)
{
if(sblength == t)
{
sblength--;
}
else
{
for(int i = t; i < sblength; i++)
{
sb[i] = sb[i + 1];
}
sb[sblength] = "";
sblength--;
}
}
}
void editorclass::insertline(int t)
{
//insert a blank line into script at line t
for(int i = sblength; i >= t; i--)
{
sb[i + 1] = sb[i];
}
sb[t] = "";
sblength++;
}
void editorclass::loadlevel(int rxi, int ryi)
{
//Set up our buffer array to be picked up by mapclass
rxi -= 100;
ryi -= 100;
if(rxi < 0)
rxi += mapwidth;
if(ryi < 0)
ryi += mapheight;
if(rxi >= mapwidth)
rxi -= mapwidth;
if(ryi >= mapheight)
ryi -= mapheight;
for(int j = 0; j < 30; j++)
{
for(int i = 0; i < 40; i++)
{
swapmap[i + (j * 40)] = contents[i + (rxi * 40) + vmult[j + (ryi * 30)]];
}
}
}
int editorclass::getlevelcol(int t)
{
if(level[t].tileset == 0) //Space Station
{
return level[t].tilecol;
}
else if(level[t].tileset == 1) //Outside
{
return 32 + level[t].tilecol;
}
else if(level[t].tileset == 2) //Lab
{
return 40 + level[t].tilecol;
}
else if(level[t].tileset == 3) //Warp Zone
{
return 46 + level[t].tilecol;
}
else if(level[t].tileset == 4) //Ship
{
return 52 + level[t].tilecol;
}
return 0;
}
int editorclass::getenemycol(int t)
{
switch(t)
{
//RED
case 3:
case 7:
case 12:
case 23:
case 28:
case 34:
case 42:
case 48:
case 58:
return 6;
break;
//GREEN
case 5:
case 9:
case 22:
case 25:
case 29:
case 31:
case 38:
case 46:
case 52:
case 53:
return 7;
break;
//BLUE
case 1:
case 6:
case 14:
case 27:
case 33:
case 44:
case 50:
case 57:
return 12;
break;
//YELLOW
case 4:
case 17:
case 24:
case 30:
case 37:
case 45:
case 51:
case 55:
return 9;
break;
//PURPLE
case 2:
case 11:
case 15:
case 19:
case 32:
case 36:
case 49:
return 20;
break;
//CYAN
case 8:
case 10:
case 13:
case 18:
case 26:
case 35:
case 41:
case 47:
case 54:
return 11;
break;
//PINK
case 16:
case 20:
case 39:
case 43:
case 56:
return 8;
break;
//ORANGE
case 21:
case 40:
return 17;
break;
default:
return 6;
break;
}
return 0;
}
int editorclass::getwarpbackground(int rx, int ry)
{
int tmp = rx + (maxwidth * ry);
switch(level[tmp].tileset)
{
case 0: //Space Station
switch(level[tmp].tilecol)
{
case 0:
return 3;
break;
case 1:
return 2;
break;
case 2:
return 1;
break;
case 3:
return 4;
break;
case 4:
return 5;
break;
case 5:
return 3;
break;
case 6:
return 1;
break;
case 7:
return 0;
break;
case 8:
return 5;
break;
case 9:
return 0;
break;
case 10:
return 2;
break;
case 11:
return 1;
break;
case 12:
return 5;
break;
case 13:
return 0;
break;
case 14:
return 3;
break;
case 15:
return 2;
break;
case 16:
return 4;
break;
case 17:
return 0;
break;
case 18:
return 3;
break;
case 19:
return 1;
break;
case 20:
return 4;
break;
case 21:
return 5;
break;
case 22:
return 1;
break;
case 23:
return 4;
break;
case 24:
return 5;
break;
case 25:
return 0;
break;
case 26:
return 3;
break;
case 27:
return 1;
break;
case 28:
return 5;
break;
case 29:
return 4;
break;
case 30:
return 5;
break;
case 31:
return 2;
break;
default:
return 6;
break;
}
break;
case 1: //Outside
switch(level[tmp].tilecol)
{
case 0:
return 3;
break;
case 1:
return 1;
break;
case 2:
return 0;
break;
case 3:
return 2;
break;
case 4:
return 4;
break;
case 5:
return 5;
break;
case 6:
return 2;
break;
case 7:
return 4;
break;
default:
return 6;
break;
}
break;
case 2: //Lab
switch(level[tmp].tilecol)
{
case 0:
return 0;
break;
case 1:
return 1;
break;
case 2:
return 2;
break;
case 3:
return 3;
break;
case 4:
return 4;
break;
case 5:
return 5;
break;
case 6:
return 6;
break;
default:
return 6;
break;
}
break;
case 3: //Warp Zone
switch(level[tmp].tilecol)
{
case 0:
return 0;
break;
case 1:
return 1;
break;
case 2:
return 2;
break;
case 3:
return 3;
break;
case 4:
return 4;
break;
case 5:
return 5;
break;
case 6:
return 6;
break;
default:
return 6;
break;
}
break;
case 4: //Ship
switch(level[tmp].tilecol)
{
case 0:
return 5;
break;
case 1:
return 0;
break;
case 2:
return 4;
break;
case 3:
return 2;
break;
case 4:
return 3;
break;
case 5:
return 1;
break;
case 6:
return 6;
break;
default:
return 6;
break;
}
break;
case 5: //Tower
return 6;
break;
default:
return 6;
break;
}
}
int editorclass::getenemyframe(int t)
{
switch(t)
{
case 0:
return 78;
break;
case 1:
return 88;
break;
case 2:
return 36;
break;
case 3:
return 164;
break;
case 4:
return 68;
break;
case 5:
return 48;
break;
case 6:
return 176;
break;
case 7:
return 168;
break;
case 8:
return 112;
break;
case 9:
return 114;
break;
default:
return 78;
break;
}
return 78;
}
void editorclass::placetile(int x, int y, int t)
{
if(x >= 0 && y >= 0 && x < mapwidth * 40 && y < mapheight * 30)
{
contents[x + (levx * 40) + vmult[y + (levy * 30)]] = t;
}
}
void editorclass::placetilelocal(int x, int y, int t)
{
if(x >= 0 && y >= 0 && x < 40 && y < 30)
{
contents[x + (levx * 40) + vmult[y + (levy * 30)]] = t;
}
updatetiles = true;
}
int editorclass::base(int x, int y)
{
//Return the base tile for the given tileset and colour
temp = x + (y * maxwidth);
if(level[temp].tileset == 0) //Space Station
{
if(level[temp].tilecol >= 22)
{
return 483 + ((level[temp].tilecol - 22) * 3);
}
else if(level[temp].tilecol >= 11)
{
return 283 + ((level[temp].tilecol - 11) * 3);
}
else
{
return 83 + (level[temp].tilecol * 3);
}
}
else if(level[temp].tileset == 1) //Outside
{
return 480 + (level[temp].tilecol * 3);
}
else if(level[temp].tileset == 2) //Lab
{
return 280 + (level[temp].tilecol * 3);
}
else if(level[temp].tileset == 3) //Warp Zone/Intermission
{
return 80 + (level[temp].tilecol * 3);
}
else if(level[temp].tileset == 4) //SHIP
{
return 101 + (level[temp].tilecol * 3);
}
return 0;
}
int editorclass::backbase(int x, int y)
{
//Return the base tile for the background of the given tileset and colour
temp = x + (y * maxwidth);
if(level[temp].tileset == 0) //Space Station
{
//Pick depending on tilecol
switch(level[temp].tilecol)
{
case 0:
case 5:
case 26:
return 680; //Blue
break;
case 3:
case 16:
case 23:
return 683; //Yellow
break;
case 9:
case 12:
case 21:
return 686; //Greeny Cyan
break;
case 4:
case 8:
case 24:
case 28:
case 30:
return 689; //Green
break;
case 20:
case 29:
return 692; //Orange
break;
case 2:
case 6:
case 11:
case 22:
case 27:
return 695; //Red
break;
case 1:
case 10:
case 15:
case 19:
case 31:
return 698; //Pink
break;
case 14:
case 18:
return 701; //Dark Blue
break;
case 7:
case 13:
case 17:
case 25:
return 704; //Cyan
break;
default:
return 680;
break;
}
}
else if(level[temp].tileset == 1) //outside
{
return 680 + (level[temp].tilecol * 3);
}
else if(level[temp].tileset == 2) //Lab
{
return 0;
}
else if(level[temp].tileset == 3) //Warp Zone/Intermission
{
return 120 + (level[temp].tilecol * 3);
}
else if(level[temp].tileset == 4) //SHIP
{
return 741 + (level[temp].tilecol * 3);
}
return 0;
}
int editorclass::at(int x, int y)
{
if(x < 0)
return at(0, y);
if(y < 0)
return at(x, 0);
if(x >= 40)
return at(39, y);
if(y >= 30)
return at(x, 29);
if(x >= 0 && y >= 0 && x < 40 && y < 30)
{
return contents[x + (levx * 40) + vmult[y + (levy * 30)]];
}
return 0;
}
int editorclass::freewrap(int x, int y)
{
if(x < 0)
return freewrap(x + (mapwidth * 40), y);
if(y < 0)
return freewrap(x, y + (mapheight * 30));
if(x >= (mapwidth * 40))
return freewrap(x - (mapwidth * 40), y);
if(y >= (mapheight * 30))
return freewrap(x, y - (mapheight * 30));
if(x >= 0 && y >= 0 && x < (mapwidth * 40) && y < (mapheight * 30))
{
if(contents[x + vmult[y]] == 0)
{
return 0;
}
else
{
if(contents[x + vmult[y]] >= 2 && contents[x + vmult[y]] < 80)
{
return 0;
}
if(contents[x + vmult[y]] >= 680)
{
return 0;
}
}
}
return 1;
}
int editorclass::backonlyfree(int x, int y)
{
//Returns 1 if tile is a background tile, 0 otherwise
if(x < 0)
return backonlyfree(0, y);
if(y < 0)
return backonlyfree(x, 0);
if(x >= 40)
return backonlyfree(39, y);
if(y >= 30)
return backonlyfree(x, 29);
if(x >= 0 && y >= 0 && x < 40 && y < 30)
{
if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] >= 680)
{
return 1;
}
}
return 0;
}
int editorclass::backfree(int x, int y)
{
//Returns 0 if tile is not a block or background tile, 1 otherwise
if(x < 0)
return backfree(0, y);
if(y < 0)
return backfree(x, 0);
if(x >= 40)
return backfree(39, y);
if(y >= 30)
return backfree(x, 29);
if(x >= 0 && y >= 0 && x < 40 && y < 30)
{
if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] == 0)
{
return 0;
}
else
{
//if(contents[x+(levx*40)+vmult[y+(levy*30)]]>=2 && contents[x+(levx*40)+vmult[y+(levy*30)]]<80){
// return 0;
//}
}
}
return 1;
}
int editorclass::spikefree(int x, int y)
{
//Returns 0 if tile is not a block or spike, 1 otherwise
if(x == -1)
return free(0, y);
if(y == -1)
return free(x, 0);
if(x == 40)
return free(39, y);
if(y == 30)
return free(x, 29);
if(x >= 0 && y >= 0 && x < 40 && y < 30)
{
if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] == 0)
{
return 0;
}
else
{
if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] >= 680)
{
return 0;
}
}
}
return 1;
}
int editorclass::free(int x, int y)
{
//Returns 0 if tile is not a block, 1 otherwise
if(x == -1)
return free(0, y);
if(y == -1)
return free(x, 0);
if(x == 40)
return free(39, y);
if(y == 30)
return free(x, 29);
if(x >= 0 && y >= 0 && x < 40 && y < 30)
{
if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] == 0)
{
return 0;
}
else
{
if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] >= 2
&& contents[x + (levx * 40) + vmult[y + (levy * 30)]] < 80)
{
return 0;
}
if(contents[x + (levx * 40) + vmult[y + (levy * 30)]] >= 680)
{
return 0;
}
}
}
return 1;
}
int editorclass::absfree(int x, int y)
{
//Returns 0 if tile is not a block, 1 otherwise, abs on grid
if(x >= 0 && y >= 0 && x < mapwidth * 40 && y < mapheight * 30)
{
if(contents[x + vmult[y]] == 0)
{
return 0;
}
else
{
if(contents[x + vmult[y]] >= 2 && contents[x + vmult[y]] < 80)
{
return 0;
}
if(contents[x + vmult[y]] >= 680)
{
return 0;
}
}
}
return 1;
}
int editorclass::match(int x, int y)
{
if(free(x - 1, y) == 0 && free(x, y - 1) == 0 && free(x + 1, y) == 0 && free(x, y + 1) == 0)
return 0;
if(free(x - 1, y) == 0 && free(x, y - 1) == 0)
return 10;
if(free(x + 1, y) == 0 && free(x, y - 1) == 0)
return 11;
if(free(x - 1, y) == 0 && free(x, y + 1) == 0)
return 12;
if(free(x + 1, y) == 0 && free(x, y + 1) == 0)
return 13;
if(free(x, y - 1) == 0)
return 1;
if(free(x - 1, y) == 0)
return 2;
if(free(x, y + 1) == 0)
return 3;
if(free(x + 1, y) == 0)
return 4;
if(free(x - 1, y - 1) == 0)
return 5;
if(free(x + 1, y - 1) == 0)
return 6;
if(free(x - 1, y + 1) == 0)
return 7;
if(free(x + 1, y + 1) == 0)
return 8;
return 0;
}
int editorclass::warpzonematch(int x, int y)
{
if(free(x - 1, y) == 0 && free(x, y - 1) == 0 && free(x + 1, y) == 0 && free(x, y + 1) == 0)
return 0;
if(free(x - 1, y) == 0 && free(x, y - 1) == 0)
return 10;
if(free(x + 1, y) == 0 && free(x, y - 1) == 0)
return 11;
if(free(x - 1, y) == 0 && free(x, y + 1) == 0)
return 12;
if(free(x + 1, y) == 0 && free(x, y + 1) == 0)
return 13;
if(free(x, y - 1) == 0)
return 1;
if(free(x - 1, y) == 0)
return 2;
if(free(x, y + 1) == 0)
return 3;
if(free(x + 1, y) == 0)
return 4;
if(free(x - 1, y - 1) == 0)
return 5;
if(free(x + 1, y - 1) == 0)
return 6;
if(free(x - 1, y + 1) == 0)
return 7;
if(free(x + 1, y + 1) == 0)
return 8;
return 0;
}
int editorclass::outsidematch(int x, int y)
{
if(backonlyfree(x - 1, y) == 0 && backonlyfree(x + 1, y) == 0)
return 2;
if(backonlyfree(x, y - 1) == 0 && backonlyfree(x, y + 1) == 0)
return 1;
return 0;
}
int editorclass::backmatch(int x, int y)
{
//Returns the first position match for a border
// 5 1 6
// 2 X 4
// 7 3 8
/*
if(at(x-1,y)>=80 && at(x,y-1)>=80) return 10;
if(at(x+1,y)>=80 && at(x,y-1)>=80) return 11;
if(at(x-1,y)>=80 && at(x,y+1)>=80) return 12;
if(at(x+1,y)>=80 && at(x,y+1)>=80) return 13;
if(at(x,y-1)>=80) return 1;
if(at(x-1,y)>=80) return 2;
if(at(x,y+1)>=80) return 3;
if(at(x+1,y)>=80) return 4;
if(at(x-1,y-1)>=80) return 5;
if(at(x+1,y-1)>=80) return 6;
if(at(x-1,y+1)>=80) return 7;
if(at(x+1,y+1)>=80) return 8;
*/
if(backfree(x - 1, y) == 0 && backfree(x, y - 1) == 0 && backfree(x + 1, y) == 0 && backfree(x, y + 1) == 0)
return 0;
if(backfree(x - 1, y) == 0 && backfree(x, y - 1) == 0)
return 10;
if(backfree(x + 1, y) == 0 && backfree(x, y - 1) == 0)
return 11;
if(backfree(x - 1, y) == 0 && backfree(x, y + 1) == 0)
return 12;
if(backfree(x + 1, y) == 0 && backfree(x, y + 1) == 0)
return 13;
if(backfree(x, y - 1) == 0)
return 1;
if(backfree(x - 1, y) == 0)
return 2;
if(backfree(x, y + 1) == 0)
return 3;
if(backfree(x + 1, y) == 0)
return 4;
if(backfree(x - 1, y - 1) == 0)
return 5;
if(backfree(x + 1, y - 1) == 0)
return 6;
if(backfree(x - 1, y + 1) == 0)
return 7;
if(backfree(x + 1, y + 1) == 0)
return 8;
return 0;
}
int editorclass::edgetile(int x, int y)
{
switch(match(x, y))
{
case 14:
return 0;
break;
case 10:
return 80;
break;
case 11:
return 82;
break;
case 12:
return 160;
break;
case 13:
return 162;
break;
case 1:
return 81;
break;
case 2:
return 120;
break;
case 3:
return 161;
break;
case 4:
return 122;
break;
case 5:
return 42;
break;
case 6:
return 41;
break;
case 7:
return 2;
break;
case 8:
return 1;
break;
case 0:
default:
return 0;
break;
}
return 0;
}
int editorclass::warpzoneedgetile(int x, int y)
{
switch(backmatch(x, y))
{
case 14:
return 0;
break;
case 10:
return 80;
break;
case 11:
return 82;
break;
case 12:
return 160;
break;
case 13:
return 162;
break;
case 1:
return 81;
break;
case 2:
return 120;
break;
case 3:
return 161;
break;
case 4:
return 122;
break;
case 5:
return 42;
break;
case 6:
return 41;
break;
case 7:
return 2;
break;
case 8:
return 1;
break;
case 0:
default:
return 0;
break;
}
return 0;
}
int editorclass::outsideedgetile(int x, int y)
{
switch(outsidematch(x, y))
{
case 2:
return 0;
break;
case 1:
return 1;
break;
case 0:
default:
return 2;
break;
}
return 2;
}
int editorclass::backedgetile(int x, int y)
{
switch(backmatch(x, y))
{
case 14:
return 0;
break;
case 10:
return 80;
break;
case 11:
return 82;
break;
case 12:
return 160;
break;
case 13:
return 162;
break;
case 1:
return 81;
break;
case 2:
return 120;
break;
case 3:
return 161;
break;
case 4:
return 122;
break;
case 5:
return 42;
break;
case 6:
return 41;
break;
case 7:
return 2;
break;
case 8:
return 1;
break;
case 0:
default:
return 0;
break;
}
return 0;
}
int editorclass::labspikedir(int x, int y, int t)
{
// a slightly more tricky case
if(free(x, y + 1) == 1)
return 63 + (t * 2);
if(free(x, y - 1) == 1)
return 64 + (t * 2);
if(free(x - 1, y) == 1)
return 51 + (t * 2);
if(free(x + 1, y) == 1)
return 52 + (t * 2);
return 63 + (t * 2);
}
int editorclass::spikedir(int x, int y)
{
if(free(x, y + 1) == 1)
return 8;
if(free(x, y - 1) == 1)
return 9;
if(free(x - 1, y) == 1)
return 49;
if(free(x + 1, y) == 1)
return 50;
return 8;
}
void editorclass::findstartpoint(Game & game)
{
//Ok! Scan the room for the closest checkpoint
int testeditor = -1;
//First up; is there a start point on this screen?
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
//if() on screen
if(edentity[i].t == 16 && testeditor == -1)
{
testeditor = i;
}
}
if(testeditor == -1)
{
game.edsavex = 160;
game.edsavey = 120;
game.edsaverx = 100;
game.edsavery = 100;
game.edsavegc = 0;
game.edsavey--;
game.edsavedir = 1 - edentity[testeditor].p1;
}
else
{
//Start point spawn
int tx = (edentity[testeditor].x - (edentity[testeditor].x % 40)) / 40;
int ty = (edentity[testeditor].y - (edentity[testeditor].y % 30)) / 30;
game.edsavex = ((edentity[testeditor].x % 40) * 8) - 4;
game.edsavey = (edentity[testeditor].y % 30) * 8;
game.edsaverx = 100 + tx;
game.edsavery = 100 + ty;
game.edsavegc = 0;
game.edsavey--;
game.edsavedir = 1 - edentity[testeditor].p1;
}
}
void editorclass::saveconvertor()
{
//In the case of resizing breaking a level, this function can fix it
maxwidth = 20;
maxheight = 20;
int oldwidth = 10, oldheight = 10;
std::vector<int> tempcontents;
for(int j = 0; j < 30 * oldwidth; j++)
{
for(int i = 0; i < 40 * oldheight; i++)
{
tempcontents.push_back(contents[i + (j * 40 * oldwidth)]);
}
}
contents.clear();
for(int j = 0; j < 30 * maxheight; j++)
{
for(int i = 0; i < 40 * maxwidth; i++)
{
contents.push_back(0);
}
}
for(int j = 0; j < 30 * oldheight; j++)
{
for(int i = 0; i < 40 * oldwidth; i++)
{
contents[i + (j * 40 * oldwidth)] = tempcontents[i + (j * 40 * oldwidth)];
}
}
tempcontents.clear();
for(int i = 0; i < 30 * maxheight; i++)
{
vmult.push_back(int(i * 40 * maxwidth));
}
for(int j = 0; j < maxheight; j++)
{
for(int i = 0; i < maxwidth; i++)
{
level[i + (j * maxwidth)].tilecol = (i + j) % 6;
}
}
contents.clear();
}
int editorclass::findtrinket(int t)
{
int ttrinket = 0;
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
if(i == t)
return ttrinket;
if(edentity[i].t == 9)
ttrinket++;
}
return 0;
}
int editorclass::findcrewmate(int t)
{
int ttrinket = 0;
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
if(i == t)
return ttrinket;
if(edentity[i].t == 15)
ttrinket++;
}
return 0;
}
int editorclass::findwarptoken(int t)
{
int ttrinket = 0;
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
if(i == t)
return ttrinket;
if(edentity[i].t == 13)
ttrinket++;
}
return 0;
}
void editorclass::countstuff()
{
numtrinkets = 0;
numcrewmates = 0;
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
if(edentity[i].t == 9)
numtrinkets++;
if(edentity[i].t == 15)
numcrewmates++;
}
}
void editorclass::load(std::string & _path)
{
reset();
unsigned char * mem = NULL;
static const char * levelDir = "levels/";
if(_path.compare(0, strlen(levelDir), levelDir) != 0)
{
_path = levelDir + _path;
}
FILESYSTEM_loadFileToMemory(_path.c_str(), &mem, NULL);
if(mem == NULL)
{
printf("No level %s to load :(\n", _path.c_str());
return;
}
TiXmlDocument doc;
doc.Parse((const char *)mem);
FILESYSTEM_freeMemory(&mem);
TiXmlHandle hDoc(&doc);
TiXmlElement * pElem;
TiXmlHandle hRoot(0);
version = 0;
{
pElem = hDoc.FirstChildElement().Element();
// should always have a valid root but handle gracefully if it does
if(!pElem)
{
printf("No valid root! Corrupt level file?\n");
}
pElem->QueryIntAttribute("version", &version);
// save this for later
hRoot = TiXmlHandle(pElem);
}
for(pElem = hRoot.FirstChild("Data").FirstChild().Element(); pElem; pElem = pElem->NextSiblingElement())
{
std::string pKey(pElem->Value());
const char * pText = pElem->GetText();
if(pText == NULL)
{
pText = "";
}
if(pKey == "MetaData")
{
for(TiXmlElement * subElem = pElem->FirstChildElement(); subElem; subElem = subElem->NextSiblingElement())
{
std::string pKey(subElem->Value());
const char * pText = subElem->GetText();
if(pText == NULL)
{
pText = "";
}
if(pKey == "Creator")
{
EditorData::GetInstance().creator = pText;
}
if(pKey == "Title")
{
EditorData::GetInstance().title = pText;
}
if(pKey == "Desc1")
{
Desc1 = pText;
}
if(pKey == "Desc2")
{
Desc2 = pText;
}
if(pKey == "Desc3")
{
Desc3 = pText;
}
if(pKey == "website")
{
website = pText;
}
}
}
if(pKey == "mapwidth")
{
mapwidth = atoi(pText);
}
if(pKey == "mapheight")
{
mapheight = atoi(pText);
}
if(pKey == "levmusic")
{
levmusic = atoi(pText);
}
if(pKey == "contents")
{
std::string TextString = (pText);
if(TextString.length())
{
std::vector<std::string> values = split(TextString, ',');
//contents.clear();
for(size_t i = 0; i < contents.size(); i++)
{
contents[i] = 0;
}
int x = 0;
int y = 0;
for(size_t i = 0; i < values.size(); i++)
{
contents[x + (maxwidth * 40 * y)] = atoi(values[i].c_str());
x++;
if(x == mapwidth * 40)
{
x = 0;
y++;
}
}
}
}
/*else if(version==1){
if (pKey == "contents")
{
std::string TextString = (pText);
if(TextString.length())
{
std::vector<std::string> values = split(TextString,',');
contents.clear();
for(int i = 0; i < values.size(); i++)
{
contents.push_back(atoi(values[i].c_str()));
}
}
}
//}
*/
if(pKey == "edEntities")
{
int i = 0;
for(TiXmlElement * edEntityEl = pElem->FirstChildElement(); edEntityEl;
edEntityEl = edEntityEl->NextSiblingElement())
{
std::string pKey(edEntityEl->Value());
//const char* pText = edEntityEl->GetText() ;
if(edEntityEl->GetText() != NULL)
{
edentity[i].scriptname = std::string(edEntityEl->GetText());
}
edEntityEl->QueryIntAttribute("x", &edentity[i].x);
edEntityEl->QueryIntAttribute("y", &edentity[i].y);
edEntityEl->QueryIntAttribute("t", &edentity[i].t);
edEntityEl->QueryIntAttribute("p1", &edentity[i].p1);
edEntityEl->QueryIntAttribute("p2", &edentity[i].p2);
edEntityEl->QueryIntAttribute("p3", &edentity[i].p3);
edEntityEl->QueryIntAttribute("p4", &edentity[i].p4);
edEntityEl->QueryIntAttribute("p5", &edentity[i].p5);
edEntityEl->QueryIntAttribute("p6", &edentity[i].p6);
i++;
}
EditorData::GetInstance().numedentities = i;
}
if(pKey == "levelMetaData")
{
int i = 0;
for(TiXmlElement * edLevelClassElement = pElem->FirstChildElement(); edLevelClassElement;
edLevelClassElement = edLevelClassElement->NextSiblingElement())
{
std::string pKey(edLevelClassElement->Value());
if(edLevelClassElement->GetText() != NULL)
{
level[i].roomname = std::string(edLevelClassElement->GetText());
}
edLevelClassElement->QueryIntAttribute("tileset", &level[i].tileset);
edLevelClassElement->QueryIntAttribute("tilecol", &level[i].tilecol);
edLevelClassElement->QueryIntAttribute("platx1", &level[i].platx1);
edLevelClassElement->QueryIntAttribute("platy1", &level[i].platy1);
edLevelClassElement->QueryIntAttribute("platx2", &level[i].platx2);
edLevelClassElement->QueryIntAttribute("platy2", &level[i].platy2);
edLevelClassElement->QueryIntAttribute("platv", &level[i].platv);
edLevelClassElement->QueryIntAttribute("enemyx1", &level[i].enemyx1);
edLevelClassElement->QueryIntAttribute("enemyy1", &level[i].enemyy1);
edLevelClassElement->QueryIntAttribute("enemyx2", &level[i].enemyx2);
edLevelClassElement->QueryIntAttribute("enemyy2", &level[i].enemyy2);
edLevelClassElement->QueryIntAttribute("enemytype", &level[i].enemytype);
edLevelClassElement->QueryIntAttribute("directmode", &level[i].directmode);
edLevelClassElement->QueryIntAttribute("warpdir", &level[i].warpdir);
i++;
}
}
if(pKey == "script")
{
std::string TextString = (pText);
if(TextString.length())
{
std::vector<std::string> values = split(TextString, '|');
script.clearcustom();
for(size_t i = 0; i < values.size(); i++)
{
script.customscript.push_back(values[i]);
}
}
}
}
gethooks();
countstuff();
version = 2;
//saveconvertor();
}
void editorclass::save(std::string & _path)
{
TiXmlDocument doc;
TiXmlElement * msg;
TiXmlDeclaration * decl = new TiXmlDeclaration("1.0", "", "");
doc.LinkEndChild(decl);
TiXmlElement * root = new TiXmlElement("MapData");
root->SetAttribute("version", version);
doc.LinkEndChild(root);
TiXmlComment * comment = new TiXmlComment();
comment->SetValue(" Save file ");
root->LinkEndChild(comment);
TiXmlElement * data = new TiXmlElement("Data");
root->LinkEndChild(data);
msg = new TiXmlElement("MetaData");
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
std::string timeAndDate = asctime(timeinfo);
//timeAndDate += dateStr;
EditorData::GetInstance().timeModified = timeAndDate;
if(EditorData::GetInstance().timeModified == "")
{
EditorData::GetInstance().timeCreated = timeAndDate;
}
//getUser
TiXmlElement * meta = new TiXmlElement("Creator");
meta->LinkEndChild(new TiXmlText(EditorData::GetInstance().creator.c_str()));
msg->LinkEndChild(meta);
meta = new TiXmlElement("Title");
meta->LinkEndChild(new TiXmlText(EditorData::GetInstance().title.c_str()));
msg->LinkEndChild(meta);
meta = new TiXmlElement("Created");
meta->LinkEndChild(new TiXmlText(UtilityClass::String(version).c_str()));
msg->LinkEndChild(meta);
meta = new TiXmlElement("Modified");
meta->LinkEndChild(new TiXmlText(EditorData::GetInstance().modifier.c_str()));
msg->LinkEndChild(meta);
meta = new TiXmlElement("Modifiers");
meta->LinkEndChild(new TiXmlText(UtilityClass::String(version).c_str()));
msg->LinkEndChild(meta);
meta = new TiXmlElement("Desc1");
meta->LinkEndChild(new TiXmlText(Desc1.c_str()));
msg->LinkEndChild(meta);
meta = new TiXmlElement("Desc2");
meta->LinkEndChild(new TiXmlText(Desc2.c_str()));
msg->LinkEndChild(meta);
meta = new TiXmlElement("Desc3");
meta->LinkEndChild(new TiXmlText(Desc3.c_str()));
msg->LinkEndChild(meta);
meta = new TiXmlElement("website");
meta->LinkEndChild(new TiXmlText(website.c_str()));
msg->LinkEndChild(meta);
data->LinkEndChild(msg);
msg = new TiXmlElement("mapwidth");
msg->LinkEndChild(new TiXmlText(UtilityClass::String(mapwidth).c_str()));
data->LinkEndChild(msg);
msg = new TiXmlElement("mapheight");
msg->LinkEndChild(new TiXmlText(UtilityClass::String(mapheight).c_str()));
data->LinkEndChild(msg);
msg = new TiXmlElement("levmusic");
msg->LinkEndChild(new TiXmlText(UtilityClass::String(levmusic).c_str()));
data->LinkEndChild(msg);
//New save format
std::string contentsString = "";
for(int y = 0; y < mapheight * 30; y++)
{
for(int x = 0; x < mapwidth * 40; x++)
{
contentsString += UtilityClass::String(contents[x + (maxwidth * 40 * y)]) + ",";
}
}
msg = new TiXmlElement("contents");
msg->LinkEndChild(new TiXmlText(contentsString.c_str()));
data->LinkEndChild(msg);
//Old save format
/*
std::string contentsString;
for(int i = 0; i < contents.size(); i++ )
{
contentsString += UtilityClass::String(contents[i]) + ",";
}
msg = new TiXmlElement( "contents" );
msg->LinkEndChild( new TiXmlText( contentsString.c_str() ));
data->LinkEndChild( msg );
*/
msg = new TiXmlElement("edEntities");
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
TiXmlElement * edentityElement = new TiXmlElement("edentity");
edentityElement->SetAttribute("x", edentity[i].x);
edentityElement->SetAttribute("y", edentity[i].y);
edentityElement->SetAttribute("t", edentity[i].t);
edentityElement->SetAttribute("p1", edentity[i].p1);
edentityElement->SetAttribute("p2", edentity[i].p2);
edentityElement->SetAttribute("p3", edentity[i].p3);
edentityElement->SetAttribute("p4", edentity[i].p4);
edentityElement->SetAttribute("p5", edentity[i].p5);
edentityElement->SetAttribute("p6", edentity[i].p6);
edentityElement->LinkEndChild(new TiXmlText(edentity[i].scriptname.c_str()));
edentityElement->LinkEndChild(new TiXmlText(""));
msg->LinkEndChild(edentityElement);
}
data->LinkEndChild(msg);
msg = new TiXmlElement("levelMetaData");
for(int i = 0; i < 400; i++)
{
TiXmlElement * edlevelclassElement = new TiXmlElement("edLevelClass");
edlevelclassElement->SetAttribute("tileset", level[i].tileset);
edlevelclassElement->SetAttribute("tilecol", level[i].tilecol);
edlevelclassElement->SetAttribute("platx1", level[i].platx1);
edlevelclassElement->SetAttribute("platy1", level[i].platy1);
edlevelclassElement->SetAttribute("platx2", level[i].platx2);
edlevelclassElement->SetAttribute("platy2", level[i].platy2);
edlevelclassElement->SetAttribute("platv", level[i].platv);
edlevelclassElement->SetAttribute("enemyx1", level[i].enemyx1);
edlevelclassElement->SetAttribute("enemyy1", level[i].enemyy1);
edlevelclassElement->SetAttribute("enemyx2", level[i].enemyx2);
edlevelclassElement->SetAttribute("enemyy2", level[i].enemyy2);
edlevelclassElement->SetAttribute("enemytype", level[i].enemytype);
edlevelclassElement->SetAttribute("directmode", level[i].directmode);
edlevelclassElement->SetAttribute("warpdir", level[i].warpdir);
edlevelclassElement->LinkEndChild(new TiXmlText(level[i].roomname.c_str()));
msg->LinkEndChild(edlevelclassElement);
}
data->LinkEndChild(msg);
std::string scriptString;
for(size_t i = 0; i < script.customscript.size(); i++)
{
scriptString += script.customscript[i] + "|";
}
msg = new TiXmlElement("script");
msg->LinkEndChild(new TiXmlText(scriptString.c_str()));
data->LinkEndChild(msg);
doc.SaveFile((std::string(FILESYSTEM_getUserLevelDirectory()) + _path).c_str());
}
void addedentity(int xp,
int yp,
int tp,
int p1 /*=0*/,
int p2 /*=0*/,
int p3 /*=0*/,
int p4 /*=0*/,
int p5 /*=320*/,
int p6 /*=240*/)
{
edentity[EditorData::GetInstance().numedentities].x = xp;
edentity[EditorData::GetInstance().numedentities].y = yp;
edentity[EditorData::GetInstance().numedentities].t = tp;
edentity[EditorData::GetInstance().numedentities].p1 = p1;
edentity[EditorData::GetInstance().numedentities].p2 = p2;
edentity[EditorData::GetInstance().numedentities].p3 = p3;
edentity[EditorData::GetInstance().numedentities].p4 = p4;
edentity[EditorData::GetInstance().numedentities].p5 = p5;
edentity[EditorData::GetInstance().numedentities].p6 = p6;
edentity[EditorData::GetInstance().numedentities].scriptname = "";
EditorData::GetInstance().numedentities++;
}
void naddedentity(int xp,
int yp,
int tp,
int p1 /*=0*/,
int p2 /*=0*/,
int p3 /*=0*/,
int p4 /*=0*/,
int p5 /*=320*/,
int p6 /*=240*/)
{
edentity[EditorData::GetInstance().numedentities].x = xp;
edentity[EditorData::GetInstance().numedentities].y = yp;
edentity[EditorData::GetInstance().numedentities].t = tp;
edentity[EditorData::GetInstance().numedentities].p1 = p1;
edentity[EditorData::GetInstance().numedentities].p2 = p2;
edentity[EditorData::GetInstance().numedentities].p3 = p3;
edentity[EditorData::GetInstance().numedentities].p4 = p4;
edentity[EditorData::GetInstance().numedentities].p5 = p5;
edentity[EditorData::GetInstance().numedentities].p6 = p6;
edentity[EditorData::GetInstance().numedentities].scriptname = "";
}
void copyedentity(int a, int b)
{
edentity[a].x = edentity[b].x;
edentity[a].y = edentity[b].y;
edentity[a].t = edentity[b].t;
edentity[a].p1 = edentity[b].p1;
edentity[a].p2 = edentity[b].p2;
edentity[a].p3 = edentity[b].p3;
edentity[a].p4 = edentity[b].p4;
edentity[a].p5 = edentity[b].p5;
edentity[a].p6 = edentity[b].p6;
edentity[a].scriptname = edentity[b].scriptname;
}
void removeedentity(int t)
{
if(t == EditorData::GetInstance().numedentities - 1)
{
EditorData::GetInstance().numedentities--;
}
else
{
for(int m = t; m < EditorData::GetInstance().numedentities; m++)
copyedentity(m, m + 1);
EditorData::GetInstance().numedentities--;
}
}
int edentat(int xp, int yp)
{
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
if(edentity[i].x == xp && edentity[i].y == yp)
return i;
}
return -1;
}
bool edentclear(int xp, int yp)
{
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
if(edentity[i].x == xp && edentity[i].y == yp)
return false;
}
return true;
}
void fillbox(Graphics & dwgfx, int x, int y, int x2, int y2, int c)
{
FillRect(dwgfx.backBuffer, x, y, x2 - x, 1, c);
FillRect(dwgfx.backBuffer, x, y2 - 1, x2 - x, 1, c);
FillRect(dwgfx.backBuffer, x, y, 1, y2 - y, c);
FillRect(dwgfx.backBuffer, x2 - 1, y, 1, y2 - y, c);
}
void fillboxabs(Graphics & dwgfx, int x, int y, int x2, int y2, int c)
{
FillRect(dwgfx.backBuffer, x, y, x2, 1, c);
FillRect(dwgfx.backBuffer, x, y + y2 - 1, x2, 1, c);
FillRect(dwgfx.backBuffer, x, y, 1, y2, c);
FillRect(dwgfx.backBuffer, x + x2 - 1, y, 1, y2, c);
}
extern editorclass ed;
extern edentities edentity[3000];
extern int temp;
extern scriptclass script;
void editorclass::generatecustomminimap(Graphics & dwgfx, mapclass & map)
{
map.customwidth = mapwidth;
map.customheight = mapheight;
map.customzoom = 1;
if(map.customwidth <= 10 && map.customheight <= 10)
map.customzoom = 2;
if(map.customwidth <= 5 && map.customheight <= 5)
map.customzoom = 4;
//Set minimap offsets
if(map.customzoom == 4)
{
map.custommmxoff = 24 * (5 - map.customwidth);
map.custommmxsize = 240 - (map.custommmxoff * 2);
map.custommmyoff = 18 * (5 - map.customheight);
map.custommmysize = 180 - (map.custommmyoff * 2);
}
else if(map.customzoom == 2)
{
map.custommmxoff = 12 * (10 - map.customwidth);
map.custommmxsize = 240 - (map.custommmxoff * 2);
map.custommmyoff = 9 * (10 - map.customheight);
map.custommmysize = 180 - (map.custommmyoff * 2);
}
else
{
map.custommmxoff = 6 * (20 - map.customwidth);
map.custommmxsize = 240 - (map.custommmxoff * 2);
map.custommmyoff = int(4.5 * (20 - map.customheight));
map.custommmysize = 180 - (map.custommmyoff * 2);
}
FillRect(dwgfx.images[12], dwgfx.getRGB(0, 0, 0));
int tm = 0;
int temp = 0;
//Scan over the map size
if(ed.mapheight <= 5 && ed.mapwidth <= 5)
{
//4x map
for(int j2 = 0; j2 < ed.mapheight; j2++)
{
for(int i2 = 0; i2 < ed.mapwidth; i2++)
{
//Ok, now scan over each square
tm = 196;
if(ed.level[i2 + (j2 * ed.maxwidth)].tileset == 1)
tm = 96;
for(int j = 0; j < 36; j++)
{
for(int i = 0; i < 48; i++)
{
temp = ed.absfree(int(i * 0.83) + (i2 * 40), int(j * 0.83) + (j2 * 30));
if(temp >= 1)
{
//Fill in this pixel
FillRect(dwgfx.images[12], (i2 * 48) + i, (j2 * 36) + j, 1, 1, dwgfx.getRGB(tm, tm, tm));
}
}
}
}
}
}
else if(ed.mapheight <= 10 && ed.mapwidth <= 10)
{
//2x map
for(int j2 = 0; j2 < ed.mapheight; j2++)
{
for(int i2 = 0; i2 < ed.mapwidth; i2++)
{
//Ok, now scan over each square
tm = 196;
if(ed.level[i2 + (j2 * ed.maxwidth)].tileset == 1)
tm = 96;
for(int j = 0; j < 18; j++)
{
for(int i = 0; i < 24; i++)
{
temp = ed.absfree(int(i * 1.6) + (i2 * 40), int(j * 1.6) + (j2 * 30));
if(temp >= 1)
{
//Fill in this pixel
FillRect(dwgfx.images[12], (i2 * 24) + i, (j2 * 18) + j, 1, 1, dwgfx.getRGB(tm, tm, tm));
}
}
}
}
}
}
else
{
for(int j2 = 0; j2 < ed.mapheight; j2++)
{
for(int i2 = 0; i2 < ed.mapwidth; i2++)
{
//Ok, now scan over each square
tm = 196;
if(ed.level[i2 + (j2 * ed.maxwidth)].tileset == 1)
tm = 96;
for(int j = 0; j < 9; j++)
{
for(int i = 0; i < 12; i++)
{
temp = ed.absfree(3 + (i * 3) + (i2 * 40), (j * 3) + (j2 * 30));
if(temp >= 1)
{
//Fill in this pixel
FillRect(dwgfx.images[12], (i2 * 12) + i, (j2 * 9) + j, 1, 1, dwgfx.getRGB(tm, tm, tm));
}
}
}
}
}
}
}
void editorrender(KeyPoll & key, Graphics & dwgfx, Game & game, mapclass & map, entityclass & obj, UtilityClass & help)
{
//TODO
//dwgfx.backbuffer.lock();
//Draw grid
FillRect(dwgfx.backBuffer, 0, 0, 320, 240, dwgfx.getRGB(0, 0, 0));
for(int j = 0; j < 30; j++)
{
for(int i = 0; i < 40; i++)
{
fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(8, 8, 8)); //a simple grid
if(i % 4 == 0)
fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(16, 16, 16));
if(j % 4 == 0)
fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(16, 16, 16));
//Minor guides
if(i == 9)
fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(24, 24, 24));
if(i == 30)
fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(24, 24, 24));
if(j == 6 || j == 7)
fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(24, 24, 24));
if(j == 21 || j == 22)
fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(24, 24, 24));
//Major guides
if(i == 20 || i == 19)
fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(32, 32, 32));
if(j == 14)
fillbox(dwgfx, i * 8, j * 8, (i * 8) + 7, (j * 8) + 7, dwgfx.getRGB(32, 32, 32));
}
}
//Or draw background
//dwgfx.drawbackground(1, map);
if(!ed.settingsmod)
{
switch(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir)
{
case 1:
dwgfx.rcol = ed.getwarpbackground(ed.levx, ed.levy);
dwgfx.drawbackground(3, map);
break;
case 2:
dwgfx.rcol = ed.getwarpbackground(ed.levx, ed.levy);
dwgfx.drawbackground(4, map);
break;
case 3:
dwgfx.rcol = ed.getwarpbackground(ed.levx, ed.levy);
dwgfx.drawbackground(5, map);
break;
default:
break;
}
}
//Draw map, in function
int temp;
if(ed.level[ed.levx + (ed.maxwidth * ed.levy)].tileset == 0
|| ed.level[ed.levx + (ed.maxwidth * ed.levy)].tileset == 10)
{
for(int j = 0; j < 30; j++)
{
for(int i = 0; i < 40; i++)
{
temp = ed.contents[i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]];
if(temp > 0)
dwgfx.drawtile(i * 8, j * 8, temp);
}
}
}
else
{
for(int j = 0; j < 30; j++)
{
for(int i = 0; i < 40; i++)
{
temp = ed.contents[i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)]];
if(temp > 0)
dwgfx.drawtile2(i * 8, j * 8, temp);
}
}
}
//Edge tile fix
//Buffer the sides of the new room with tiles from other rooms, to ensure no gap problems.
for(int j = 0; j < 30; j++)
{
//left edge
if(ed.freewrap((ed.levx * 40) - 1, j + (ed.levy * 30)) == 1)
{
FillRect(dwgfx.backBuffer, 0, j * 8, 2, 8, dwgfx.getRGB(255, 255, 255 - help.glow));
}
//right edge
if(ed.freewrap((ed.levx * 40) + 40, j + (ed.levy * 30)) == 1)
{
FillRect(dwgfx.backBuffer, 318, j * 8, 2, 8, dwgfx.getRGB(255, 255, 255 - help.glow));
}
}
for(int i = 0; i < 40; i++)
{
if(ed.freewrap((ed.levx * 40) + i, (ed.levy * 30) - 1) == 1)
{
FillRect(dwgfx.backBuffer, i * 8, 0, 8, 2, dwgfx.getRGB(255, 255, 255 - help.glow));
}
if(ed.freewrap((ed.levx * 40) + i, 30 + (ed.levy * 30)) == 1)
{
FillRect(dwgfx.backBuffer, i * 8, 238, 8, 2, dwgfx.getRGB(255, 255, 255 - help.glow));
}
}
//Draw entities
game.customcol = ed.getlevelcol(ed.levx + (ed.levy * ed.maxwidth)) + 1;
ed.entcol = ed.getenemycol(game.customcol);
obj.customplatformtile = game.customcol * 12;
ed.temp = edentat(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30));
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
//if() on screen
int tx = (edentity[i].x - (edentity[i].x % 40)) / 40;
int ty = (edentity[i].y - (edentity[i].y % 30)) / 30;
point tpoint;
SDL_Rect drawRect;
if(tx == ed.levx && ty == ed.levy)
{
switch(edentity[i].t)
{
case 1: //Entities
//FillRect(dwgfx.backBuffer, (edentity[i].x*8)- (ed.levx*40*8),(edentity[i].y*8)- (ed.levy*30*8), 16,16, dwgfx.getRGB(64,32,64));
//dwgfx.drawsprite((edentity[i].x*8)- (ed.levx*40*8),(edentity[i].y*8)- (ed.levy*30*8),ed.getenemyframe(ed.level[ed.levx+(ed.levy*ed.maxwidth)].enemytype),164,48,48);
dwgfx.drawspritesetcol((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
ed.getenemyframe(ed.level[ed.levx + (ed.levy * ed.maxwidth)].enemytype),
ed.entcol,
help);
if(edentity[i].p1 == 0)
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4,
(edentity[i].y * 8) - (ed.levy * 30 * 8) + 4,
"V",
255,
255,
255 - help.glow,
false);
if(edentity[i].p1 == 1)
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4,
(edentity[i].y * 8) - (ed.levy * 30 * 8) + 4,
"^",
255,
255,
255 - help.glow,
false);
if(edentity[i].p1 == 2)
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4,
(edentity[i].y * 8) - (ed.levy * 30 * 8) + 4,
"<",
255,
255,
255 - help.glow,
false);
if(edentity[i].p1 == 3)
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4,
(edentity[i].y * 8) - (ed.levy * 30 * 8) + 4,
">",
255,
255,
255 - help.glow,
false);
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
16,
16,
dwgfx.getBGR(255, 164, 255));
break;
case 2: //Threadmills & platforms
tpoint.x = (edentity[i].x * 8) - (ed.levx * 40 * 8);
tpoint.y = (edentity[i].y * 8) - (ed.levy * 30 * 8);
drawRect = dwgfx.tiles_rect;
drawRect.x += tpoint.x;
drawRect.y += tpoint.y;
BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect);
drawRect.x += 8;
BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect);
drawRect.x += 8;
BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect);
drawRect.x += 8;
BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect);
if(edentity[i].p1 <= 4)
{
if(edentity[i].p1 == 0)
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 12,
(edentity[i].y * 8) - (ed.levy * 30 * 8),
"V",
255 - help.glow,
255 - help.glow,
255 - help.glow,
false);
if(edentity[i].p1 == 1)
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 12,
(edentity[i].y * 8) - (ed.levy * 30 * 8),
"^",
255 - help.glow,
255 - help.glow,
255 - help.glow,
false);
if(edentity[i].p1 == 2)
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 12,
(edentity[i].y * 8) - (ed.levy * 30 * 8),
"<",
255 - help.glow,
255 - help.glow,
255 - help.glow,
false);
if(edentity[i].p1 == 3)
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 12,
(edentity[i].y * 8) - (ed.levy * 30 * 8),
">",
255 - help.glow,
255 - help.glow,
255 - help.glow,
false);
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
32,
8,
dwgfx.getBGR(255, 255, 255));
}
if(edentity[i].p1 == 5)
{
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
">>>>",
255 - help.glow,
255 - help.glow,
255 - help.glow,
false);
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
32,
8,
dwgfx.getBGR(255, 255, 255));
}
else if(edentity[i].p1 == 6)
{
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
"<<<<",
255 - help.glow,
255 - help.glow,
255 - help.glow,
false);
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
32,
8,
dwgfx.getBGR(255, 255, 255));
}
if(edentity[i].p1 >= 7)
{
//FillRect(dwgfx.backBuffer, (edentity[i].x*8)- (ed.levx*40*8),(edentity[i].y*8)- (ed.levy*30*8), 32,8, dwgfx.getBGR(64,128,64));
tpoint.x = (edentity[i].x * 8) - (ed.levx * 40 * 8) + 32;
tpoint.y = (edentity[i].y * 8) - (ed.levy * 30 * 8);
drawRect = dwgfx.tiles_rect;
drawRect.x += tpoint.x;
drawRect.y += tpoint.y;
BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile],
NULL,
dwgfx.backBuffer,
&drawRect);
drawRect.x += 8;
BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile],
NULL,
dwgfx.backBuffer,
&drawRect);
drawRect.x += 8;
BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile],
NULL,
dwgfx.backBuffer,
&drawRect);
drawRect.x += 8;
BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile],
NULL,
dwgfx.backBuffer,
&drawRect);
}
if(edentity[i].p1 == 7)
{
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4,
(edentity[i].y * 8) - (ed.levy * 30 * 8),
"> > > > ",
255 - help.glow,
255 - help.glow,
255 - help.glow,
false);
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
64,
8,
dwgfx.getBGR(255, 255, 255));
}
else if(edentity[i].p1 == 8)
{
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) + 4,
(edentity[i].y * 8) - (ed.levy * 30 * 8),
"< < < < ",
255 - help.glow,
255 - help.glow,
255 - help.glow,
false);
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
64,
8,
dwgfx.getBGR(255, 255, 255));
}
break;
case 3: //Disappearing Platform
//FillRect(dwgfx.backBuffer, (edentity[i].x*8)- (ed.levx*40*8),(edentity[i].y*8)- (ed.levy*30*8), 32,8, dwgfx.getBGR(64,64,128));
tpoint.x = (edentity[i].x * 8) - (ed.levx * 40 * 8);
tpoint.y = (edentity[i].y * 8) - (ed.levy * 30 * 8);
drawRect = dwgfx.tiles_rect;
drawRect.x += tpoint.x;
drawRect.y += tpoint.y;
BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect);
drawRect.x += 8;
BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect);
drawRect.x += 8;
BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect);
drawRect.x += 8;
BlitSurfaceStandard(dwgfx.entcolours[obj.customplatformtile], NULL, dwgfx.backBuffer, &drawRect);
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
"////",
255 - help.glow,
255 - help.glow,
255 - help.glow,
false);
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
32,
8,
dwgfx.getBGR(255, 255, 255));
break;
case 9: //Shiny Trinket
dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
22,
196,
196,
196);
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
16,
16,
dwgfx.getRGB(164, 164, 255));
break;
case 10: //Checkpoints
if(edentity[i].p1 == 0) //From roof
{
dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
20,
196,
196,
196);
}
else if(edentity[i].p1 == 1) //From floor
{
dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
21,
196,
196,
196);
}
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
16,
16,
dwgfx.getRGB(164, 164, 255));
break;
case 11: //Gravity lines
if(edentity[i].p1 == 0) //Horizontal
{
int tx = edentity[i].x - (ed.levx * 40);
int tx2 = edentity[i].x - (ed.levx * 40);
int ty = edentity[i].y - (ed.levy * 30);
while(ed.spikefree(tx, ty) == 0)
tx--;
while(ed.spikefree(tx2, ty) == 0)
tx2++;
tx++;
FillRect(dwgfx.backBuffer,
(tx * 8),
(ty * 8) + 4,
(tx2 - tx) * 8,
1,
dwgfx.getRGB(194, 194, 194));
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
8,
8,
dwgfx.getRGB(164, 255, 164));
edentity[i].p2 = tx;
edentity[i].p3 = (tx2 - tx) * 8;
}
else //Vertical
{
int tx = edentity[i].x - (ed.levx * 40);
int ty = edentity[i].y - (ed.levy * 30);
int ty2 = edentity[i].y - (ed.levy * 30);
while(ed.spikefree(tx, ty) == 0)
ty--;
while(ed.spikefree(tx, ty2) == 0)
ty2++;
ty++;
FillRect(dwgfx.backBuffer,
(tx * 8) + 3,
(ty * 8),
1,
(ty2 - ty) * 8,
dwgfx.getRGB(194, 194, 194));
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
8,
8,
dwgfx.getRGB(164, 255, 164));
edentity[i].p2 = ty;
edentity[i].p3 = (ty2 - ty) * 8;
}
break;
case 13: //Warp tokens
dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
18 + (ed.entframe % 2),
196,
196,
196);
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
16,
16,
dwgfx.getRGB(164, 164, 255));
if(ed.temp == i)
{
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8) - 8,
"(" + help.String(((edentity[i].p1 - int(edentity[i].p1 % 40)) / 40) + 1) + ","
+ help.String(((edentity[i].p2 - int(edentity[i].p2 % 30)) / 30) + 1) + ")",
210,
210,
255);
}
else
{
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8) - 8,
help.String(ed.findwarptoken(i)),
210,
210,
255);
}
break;
case 15: //Crewmates
dwgfx.drawspritesetcol((edentity[i].x * 8) - (ed.levx * 40 * 8) - 4,
(edentity[i].y * 8) - (ed.levy * 30 * 8),
144,
obj.crewcolour(edentity[i].p1),
help);
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
16,
24,
dwgfx.getRGB(164, 164, 164));
break;
case 16: //Start
if(edentity[i].p1 == 0) //Left
{
dwgfx.drawspritesetcol((edentity[i].x * 8) - (ed.levx * 40 * 8) - 4,
(edentity[i].y * 8) - (ed.levy * 30 * 8),
0,
obj.crewcolour(0),
help);
}
else if(edentity[i].p1 == 1)
{
dwgfx.drawspritesetcol((edentity[i].x * 8) - (ed.levx * 40 * 8) - 4,
(edentity[i].y * 8) - (ed.levy * 30 * 8),
3,
obj.crewcolour(0),
help);
}
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
16,
24,
dwgfx.getRGB(164, 255, 255));
if(ed.entframe < 2)
{
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) - 12,
(edentity[i].y * 8) - (ed.levy * 30 * 8) - 8,
"START",
255,
255,
255);
}
else
{
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8) - 12,
(edentity[i].y * 8) - (ed.levy * 30 * 8) - 8,
"START",
196,
196,
196);
}
break;
case 17: //Roomtext
if(edentity[i].scriptname.length() < 1)
{
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
8,
8,
dwgfx.getRGB(96, 96, 96));
}
else
{
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
edentity[i].scriptname.length() * 8,
8,
dwgfx.getRGB(96, 96, 96));
}
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
edentity[i].scriptname,
196,
196,
255 - help.glow);
break;
case 18: //Terminals
dwgfx.drawsprite((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8) + 8,
17,
96,
96,
96);
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
16,
24,
dwgfx.getRGB(164, 164, 164));
if(ed.temp == i)
{
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8) - 8,
edentity[i].scriptname,
210,
210,
255);
}
break;
case 19: //Script Triggers
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
edentity[i].p1 * 8,
edentity[i].p2 * 8,
dwgfx.getRGB(255, 164, 255));
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
8,
8,
dwgfx.getRGB(255, 255, 255));
if(ed.temp == i)
{
dwgfx.Print((edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8) - 8,
edentity[i].scriptname,
210,
210,
255);
}
break;
case 50: //Warp lines
if(edentity[i].p1 >= 2) //Horizontal
{
int tx = edentity[i].x - (ed.levx * 40);
int tx2 = edentity[i].x - (ed.levx * 40);
int ty = edentity[i].y - (ed.levy * 30);
while(ed.free(tx, ty) == 0)
tx--;
while(ed.free(tx2, ty) == 0)
tx2++;
tx++;
fillboxabs(dwgfx, (tx * 8), (ty * 8) + 1, (tx2 - tx) * 8, 6, dwgfx.getRGB(255, 255, 194));
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
8,
8,
dwgfx.getRGB(255, 255, 164));
edentity[i].p2 = tx;
edentity[i].p3 = (tx2 - tx) * 8;
}
else //Vertical
{
int tx = edentity[i].x - (ed.levx * 40);
int ty = edentity[i].y - (ed.levy * 30);
int ty2 = edentity[i].y - (ed.levy * 30);
while(ed.free(tx, ty) == 0)
ty--;
while(ed.free(tx, ty2) == 0)
ty2++;
ty++;
fillboxabs(dwgfx, (tx * 8) + 1, (ty * 8), 6, (ty2 - ty) * 8, dwgfx.getRGB(255, 255, 194));
fillboxabs(dwgfx,
(edentity[i].x * 8) - (ed.levx * 40 * 8),
(edentity[i].y * 8) - (ed.levy * 30 * 8),
8,
8,
dwgfx.getRGB(255, 255, 164));
edentity[i].p2 = ty;
edentity[i].p3 = (ty2 - ty) * 8;
}
break;
}
}
//Need to also check warp point destinations
if(edentity[i].t == 13 && ed.warpent != i)
{
tx = (edentity[i].p1 - (edentity[i].p1 % 40)) / 40;
ty = (edentity[i].p2 - (edentity[i].p2 % 30)) / 30;
if(tx == ed.levx && ty == ed.levy)
{
dwgfx.drawsprite((edentity[i].p1 * 8) - (ed.levx * 40 * 8),
(edentity[i].p2 * 8) - (ed.levy * 30 * 8),
18 + (ed.entframe % 2),
64,
64,
64);
fillboxabs(dwgfx,
(edentity[i].p1 * 8) - (ed.levx * 40 * 8),
(edentity[i].p2 * 8) - (ed.levy * 30 * 8),
16,
16,
dwgfx.getRGB(64, 64, 96));
if(ed.tilex + (ed.levx * 40) == edentity[i].p1 && ed.tiley + (ed.levy * 30) == edentity[i].p2)
{
dwgfx.Print((edentity[i].p1 * 8) - (ed.levx * 40 * 8),
(edentity[i].p2 * 8) - (ed.levy * 30 * 8) - 8,
"(" + help.String(((edentity[i].x - int(edentity[i].x % 40)) / 40) + 1) + ","
+ help.String(((edentity[i].y - int(edentity[i].y % 30)) / 30) + 1) + ")",
190,
190,
225);
}
else
{
dwgfx.Print((edentity[i].p1 * 8) - (ed.levx * 40 * 8),
(edentity[i].p2 * 8) - (ed.levy * 30 * 8) - 8,
help.String(ed.findwarptoken(i)),
190,
190,
225);
}
}
}
}
if(ed.boundarymod > 0)
{
if(ed.boundarymod == 1)
{
fillboxabs(dwgfx,
ed.tilex * 8,
ed.tiley * 8,
8,
8,
dwgfx.getRGB(255 - (help.glow / 2), 191 + (help.glow), 210 + (help.glow / 2)));
fillboxabs(dwgfx,
(ed.tilex * 8) + 2,
(ed.tiley * 8) + 2,
4,
4,
dwgfx.getRGB(128 - (help.glow / 4), 100 + (help.glow / 2), 105 + (help.glow / 4)));
}
else if(ed.boundarymod == 2)
{
if((ed.tilex * 8) + 8 <= ed.boundx1 || (ed.tiley * 8) + 8 <= ed.boundy1)
{
fillboxabs(dwgfx,
ed.boundx1,
ed.boundy1,
8,
8,
dwgfx.getRGB(255 - (help.glow / 2), 191 + (help.glow), 210 + (help.glow / 2)));
fillboxabs(dwgfx,
ed.boundx1 + 2,
ed.boundy1 + 2,
4,
4,
dwgfx.getRGB(128 - (help.glow / 4), 100 + (help.glow / 2), 105 + (help.glow / 4)));
}
else
{
fillboxabs(dwgfx,
ed.boundx1,
ed.boundy1,
(ed.tilex * 8) + 8 - ed.boundx1,
(ed.tiley * 8) + 8 - ed.boundy1,
dwgfx.getRGB(255 - (help.glow / 2), 191 + (help.glow), 210 + (help.glow / 2)));
fillboxabs(dwgfx,
ed.boundx1 + 2,
ed.boundy1 + 2,
(ed.tilex * 8) + 8 - ed.boundx1 - 4,
(ed.tiley * 8) + 8 - ed.boundy1 - 4,
dwgfx.getRGB(128 - (help.glow / 4), 100 + (help.glow / 2), 105 + (help.glow / 4)));
}
}
}
else
{
//Draw boundaries
int tmp = ed.levx + (ed.levy * ed.maxwidth);
if(ed.level[tmp].enemyx1 != 0 && ed.level[tmp].enemyy1 != 0 && ed.level[tmp].enemyx2 != 320
&& ed.level[tmp].enemyy2 != 240)
{
fillboxabs(dwgfx,
ed.level[tmp].enemyx1,
ed.level[tmp].enemyy1,
ed.level[tmp].enemyx2 - ed.level[tmp].enemyx1,
ed.level[tmp].enemyy2 - ed.level[tmp].enemyy1,
dwgfx.getBGR(255 - (help.glow / 2), 64, 64));
}
if(ed.level[tmp].platx1 != 0 && ed.level[tmp].platy1 != 0 && ed.level[tmp].platx2 != 320
&& ed.level[tmp].platy2 != 240)
{
fillboxabs(dwgfx,
ed.level[tmp].platx1,
ed.level[tmp].platy1,
ed.level[tmp].platx2 - ed.level[tmp].platx1,
ed.level[tmp].platy2 - ed.level[tmp].platy1,
dwgfx.getBGR(64, 64, 255 - (help.glow / 2)));
}
}
//Draw connecting map guidelines
//TODO
//Draw Cursor
switch(ed.drawmode)
{
case 0:
case 1:
case 2:
case 9:
case 10:
case 12: //Single point
fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 8, 8, dwgfx.getRGB(200, 32, 32));
break;
case 3:
case 4:
case 8:
case 13: //2x2
fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 16, 16, dwgfx.getRGB(200, 32, 32));
break;
case 5:
case 6:
case 7: //Platform
fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 32, 8, dwgfx.getRGB(200, 32, 32));
break;
case 14: //X if not on edge
if(ed.tilex == 0 || ed.tilex == 39 || ed.tiley == 0 || ed.tiley == 29)
{
fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 8, 8, dwgfx.getRGB(200, 32, 32));
}
else
{
dwgfx.Print((ed.tilex * 8), (ed.tiley * 8), "X", 255, 0, 0);
}
break;
case 11:
case 15:
case 16: //2x3
fillboxabs(dwgfx, (ed.tilex * 8), (ed.tiley * 8), 16, 24, dwgfx.getRGB(200, 32, 32));
break;
}
if(ed.drawmode < 3)
{
if(ed.zmod && ed.drawmode < 2)
{
fillboxabs(dwgfx, (ed.tilex * 8) - 8, (ed.tiley * 8) - 8, 24, 24, dwgfx.getRGB(200, 32, 32));
}
else if(ed.xmod && ed.drawmode < 2)
{
fillboxabs(dwgfx, (ed.tilex * 8) - 16, (ed.tiley * 8) - 16, 24 + 16, 24 + 16, dwgfx.getRGB(200, 32, 32));
}
}
//If in directmode, show current directmode tile
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode == 1)
{
//Tile box for direct mode
int t2 = 0;
if(ed.dmtileeditor > 0)
{
ed.dmtileeditor--;
if(ed.dmtileeditor <= 4)
{
t2 = (4 - ed.dmtileeditor) * 12;
}
//Draw five lines of the editor
temp = ed.dmtile - (ed.dmtile % 40);
temp -= 80;
FillRect(dwgfx.backBuffer, 0, -t2, 320, 40, dwgfx.getRGB(0, 0, 0));
FillRect(dwgfx.backBuffer, 0, -t2 + 40, 320, 2, dwgfx.getRGB(255, 255, 255));
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0)
{
for(int i = 0; i < 40; i++)
{
dwgfx.drawtile(i * 8, 0 - t2, (temp + 1200 + i) % 1200);
dwgfx.drawtile(i * 8, 8 - t2, (temp + 1200 + 40 + i) % 1200);
dwgfx.drawtile(i * 8, 16 - t2, (temp + 1200 + 80 + i) % 1200);
dwgfx.drawtile(i * 8, 24 - t2, (temp + 1200 + 120 + i) % 1200);
dwgfx.drawtile(i * 8, 32 - t2, (temp + 1200 + 160 + i) % 1200);
}
}
else
{
for(int i = 0; i < 40; i++)
{
dwgfx.drawtile2(i * 8, 0 - t2, (temp + 1200 + i) % 1200);
dwgfx.drawtile2(i * 8, 8 - t2, (temp + 1200 + 40 + i) % 1200);
dwgfx.drawtile2(i * 8, 16 - t2, (temp + 1200 + 80 + i) % 1200);
dwgfx.drawtile2(i * 8, 24 - t2, (temp + 1200 + 120 + i) % 1200);
dwgfx.drawtile2(i * 8, 32 - t2, (temp + 1200 + 160 + i) % 1200);
}
}
//Highlight our little block
fillboxabs(dwgfx, ((ed.dmtile % 40) * 8) - 2, 16 - 2, 12, 12, dwgfx.getRGB(196, 196, 255 - help.glow));
fillboxabs(dwgfx, ((ed.dmtile % 40) * 8) - 1, 16 - 1, 10, 10, dwgfx.getRGB(0, 0, 0));
}
if(ed.dmtileeditor > 0 && t2 <= 30)
{
dwgfx.Print(2, 45 - t2, "Tile:", 196, 196, 255 - help.glow, false);
dwgfx.Print(58, 45 - t2, help.String(ed.dmtile), 196, 196, 255 - help.glow, false);
FillRect(dwgfx.backBuffer, 44, 44 - t2, 10, 10, dwgfx.getRGB(196, 196, 255 - help.glow));
FillRect(dwgfx.backBuffer, 45, 45 - t2, 8, 8, dwgfx.getRGB(0, 0, 0));
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0)
{
dwgfx.drawtile(45, 45 - t2, ed.dmtile);
}
else
{
dwgfx.drawtile2(45, 45 - t2, ed.dmtile);
}
}
else
{
dwgfx.Print(2, 12, "Tile:", 196, 196, 255 - help.glow, false);
dwgfx.Print(58, 12, help.String(ed.dmtile), 196, 196, 255 - help.glow, false);
FillRect(dwgfx.backBuffer, 44, 11, 10, 10, dwgfx.getRGB(196, 196, 255 - help.glow));
FillRect(dwgfx.backBuffer, 45, 12, 8, 8, dwgfx.getRGB(0, 0, 0));
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0)
{
dwgfx.drawtile(45, 12, ed.dmtile);
}
else
{
dwgfx.drawtile2(45, 12, ed.dmtile);
}
}
}
//Draw GUI
if(ed.boundarymod > 0)
{
if(ed.boundarymod == 1)
{
FillRect(dwgfx.backBuffer, 0, 230, 320, 240, dwgfx.getRGB(32, 32, 32));
FillRect(dwgfx.backBuffer, 0, 231, 320, 240, dwgfx.getRGB(0, 0, 0));
switch(ed.boundarytype)
{
case 0:
dwgfx.Print(4, 232, "SCRIPT BOX: Click on top left", 255, 255, 255, false);
break;
case 1:
dwgfx.Print(4, 232, "ENEMY BOUNDS: Click on top left", 255, 255, 255, false);
break;
case 2:
dwgfx.Print(4, 232, "PLATFORM BOUNDS: Click on top left", 255, 255, 255, false);
break;
case 3:
dwgfx.Print(4, 232, "COPY TILES: Click on top left", 255, 255, 255, false);
break;
default:
dwgfx.Print(4, 232, "Click on top left", 255, 255, 255, false);
break;
}
}
else if(ed.boundarymod == 2)
{
FillRect(dwgfx.backBuffer, 0, 230, 320, 240, dwgfx.getRGB(32, 32, 32));
FillRect(dwgfx.backBuffer, 0, 231, 320, 240, dwgfx.getRGB(0, 0, 0));
switch(ed.boundarytype)
{
case 0:
dwgfx.Print(4, 232, "SCRIPT BOX: Click on bottom right", 255, 255, 255, false);
break;
case 1:
dwgfx.Print(4, 232, "ENEMY BOUNDS: Click on bottom right", 255, 255, 255, false);
break;
case 2:
dwgfx.Print(4, 232, "PLATFORM BOUNDS: Click on bottom right", 255, 255, 255, false);
break;
case 3:
dwgfx.Print(4, 232, "COPY TILES: Click on bottom right", 255, 255, 255, false);
break;
default:
dwgfx.Print(4, 232, "Click on bottom right", 255, 255, 255, false);
break;
}
}
}
else if(ed.scripteditmod)
{
//Elaborate C64 BASIC menu goes here!
FillRect(dwgfx.backBuffer, 0, 0, 320, 240, dwgfx.getBGR(123, 111, 218));
FillRect(dwgfx.backBuffer, 14, 16, 292, 208, dwgfx.getRGB(162, 48, 61));
switch(ed.scripthelppage)
{
case 0:
dwgfx.Print(16, 28, "**** VVVVVV SCRIPT EDITOR ****", 123, 111, 218, true);
dwgfx.Print(16, 44, "PRESS ESC TO RETURN TO MENU", 123, 111, 218, true);
//dwgfx.Print(16,60,"READY.", 123, 111, 218, false);
if(ed.numhooks > 0)
{
for(int i = 0; i < 9; i++)
{
if(ed.hookmenupage + i < ed.numhooks)
{
if(ed.hookmenupage + i == ed.hookmenu)
{
std::string tstring
= "> " + ed.hooklist[(ed.numhooks - 1) - (ed.hookmenupage + i)] + " <";
std::transform(tstring.begin(), tstring.end(), tstring.begin(), ::toupper);
dwgfx.Print(16, 68 + (i * 16), tstring, 123, 111, 218, true);
}
else
{
dwgfx.Print(16,
68 + (i * 16),
ed.hooklist[(ed.numhooks - 1) - (ed.hookmenupage + i)],
123,
111,
218,
true);
}
}
}
}
else
{
dwgfx.Print(16, 110, "NO SCRIPT IDS FOUND", 123, 111, 218, true);
dwgfx.Print(16, 130, "CREATE A SCRIPT WITH EITHER", 123, 111, 218, true);
dwgfx.Print(16, 140, "THE TERMINAL OR SCRIPT BOX TOOLS", 123, 111, 218, true);
}
break;
case 1:
//Current scriptname
FillRect(dwgfx.backBuffer, 14, 226, 292, 12, dwgfx.getRGB(162, 48, 61));
dwgfx.Print(16, 228, "CURRENT SCRIPT: " + ed.sbscript, 123, 111, 218, true);
//Draw text
for(int i = 0; i < 25; i++)
{
if(i + ed.pagey < 500)
{
dwgfx.Print(16, 20 + (i * 8), ed.sb[i + ed.pagey], 123, 111, 218, false);
}
}
//Draw cursor
if(ed.entframe < 2)
{
dwgfx.Print(16 + (ed.sbx * 8), 20 + (ed.sby * 8), "_", 123, 111, 218, false);
}
break;
}
}
else if(ed.settingsmod)
{
if(!game.colourblindmode)
dwgfx.drawtowerbackgroundsolo(map);
int tr = map.r - (help.glow / 4) - int(fRandom() * 4);
int tg = map.g - (help.glow / 4) - int(fRandom() * 4);
int tb = map.b - (help.glow / 4) - int(fRandom() * 4);
if(tr < 0)
tr = 0;
if(tr > 255)
tr = 255;
if(tg < 0)
tg = 0;
if(tg > 255)
tg = 255;
if(tb < 0)
tb = 0;
if(tb > 255)
tb = 255;
if(game.currentmenuname == "ed_settings")
{
dwgfx.bigprint(-1, 75, "Map Settings", tr, tg, tb, true);
}
else if(game.currentmenuname == "ed_desc")
{
if(ed.titlemod)
{
if(ed.entframe < 2)
{
dwgfx.bigprint(-1, 35, key.keybuffer + "_", tr, tg, tb, true);
}
else
{
dwgfx.bigprint(-1, 35, key.keybuffer + " ", tr, tg, tb, true);
}
}
else
{
dwgfx.bigprint(-1, 35, EditorData::GetInstance().title, tr, tg, tb, true);
}
if(ed.creatormod)
{
if(ed.entframe < 2)
{
dwgfx.Print(-1, 60, "by " + key.keybuffer + "_", tr, tg, tb, true);
}
else
{
dwgfx.Print(-1, 60, "by " + key.keybuffer + " ", tr, tg, tb, true);
}
}
else
{
dwgfx.Print(-1, 60, "by " + EditorData::GetInstance().creator, tr, tg, tb, true);
}
if(ed.websitemod)
{
if(ed.entframe < 2)
{
dwgfx.Print(-1, 70, key.keybuffer + "_", tr, tg, tb, true);
}
else
{
dwgfx.Print(-1, 70, key.keybuffer + " ", tr, tg, tb, true);
}
}
else
{
dwgfx.Print(-1, 70, ed.website, tr, tg, tb, true);
}
if(ed.desc1mod)
{
if(ed.entframe < 2)
{
dwgfx.Print(-1, 90, key.keybuffer + "_", tr, tg, tb, true);
}
else
{
dwgfx.Print(-1, 90, key.keybuffer + " ", tr, tg, tb, true);
}
}
else
{
dwgfx.Print(-1, 90, ed.Desc1, tr, tg, tb, true);
}
if(ed.desc2mod)
{
if(ed.entframe < 2)
{
dwgfx.Print(-1, 100, key.keybuffer + "_", tr, tg, tb, true);
}
else
{
dwgfx.Print(-1, 100, key.keybuffer + " ", tr, tg, tb, true);
}
}
else
{
dwgfx.Print(-1, 100, ed.Desc2, tr, tg, tb, true);
}
if(ed.desc3mod)
{
if(ed.entframe < 2)
{
dwgfx.Print(-1, 110, key.keybuffer + "_", tr, tg, tb, true);
}
else
{
dwgfx.Print(-1, 110, key.keybuffer + " ", tr, tg, tb, true);
}
}
else
{
dwgfx.Print(-1, 110, ed.Desc3, tr, tg, tb, true);
}
}
else if(game.currentmenuname == "ed_music")
{
dwgfx.bigprint(-1, 65, "Map Music", tr, tg, tb, true);
dwgfx.Print(-1, 85, "Current map music:", tr, tg, tb, true);
switch(ed.levmusic)
{
case 0:
dwgfx.Print(-1, 120, "No background music", tr, tg, tb, true);
break;
case 1:
dwgfx.Print(-1, 120, "1: Pushing Onwards", tr, tg, tb, true);
break;
case 2:
dwgfx.Print(-1, 120, "2: Positive Force", tr, tg, tb, true);
break;
case 3:
dwgfx.Print(-1, 120, "3: Potential For Anything", tr, tg, tb, true);
break;
case 4:
dwgfx.Print(-1, 120, "4: Passion For Exploring", tr, tg, tb, true);
break;
case 6:
dwgfx.Print(-1, 120, "5: Presenting VVVVVV", tr, tg, tb, true);
break;
case 8:
dwgfx.Print(-1, 120, "6: Predestined Fate", tr, tg, tb, true);
break;
case 10:
dwgfx.Print(-1, 120, "7: Popular Potpourri", tr, tg, tb, true);
break;
case 11:
dwgfx.Print(-1, 120, "8: Pipe Dream", tr, tg, tb, true);
break;
case 12:
dwgfx.Print(-1, 120, "9: Pressure Cooker", tr, tg, tb, true);
break;
case 13:
dwgfx.Print(-1, 120, "10: Paced Energy", tr, tg, tb, true);
break;
case 14:
dwgfx.Print(-1, 120, "11: Piercing The Sky", tr, tg, tb, true);
break;
default:
dwgfx.Print(-1, 120, "?: something else", tr, tg, tb, true);
break;
}
}
else if(game.currentmenuname == "ed_quit")
{
dwgfx.bigprint(-1, 90, "Save before", tr, tg, tb, true);
dwgfx.bigprint(-1, 110, "quiting?", tr, tg, tb, true);
}
dwgfx.drawmenu(game, tr, tg, tb, 15);
/*
dwgfx.Print(4, 224, "Enter name to save map as:", 255,255,255, false);
if(ed.entframe<2){
dwgfx.Print(4, 232, ed.filename+"_", 196, 196, 255 - help.glow, true);
}else{
dwgfx.Print(4, 232, ed.filename+" ", 196, 196, 255 - help.glow, true);
}
*/
}
else if(ed.scripttextmod)
{
FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32));
FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0));
dwgfx.Print(4, 224, "Enter script id name:", 255, 255, 255, false);
if(ed.entframe < 2)
{
dwgfx.Print(4, 232, edentity[ed.scripttextent].scriptname + "_", 196, 196, 255 - help.glow, true);
}
else
{
dwgfx.Print(4, 232, edentity[ed.scripttextent].scriptname + " ", 196, 196, 255 - help.glow, true);
}
}
else if(ed.savemod)
{
FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32));
FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0));
dwgfx.Print(4, 224, "Enter filename to save map as:", 255, 255, 255, false);
if(ed.entframe < 2)
{
dwgfx.Print(4, 232, ed.filename + "_", 196, 196, 255 - help.glow, true);
}
else
{
dwgfx.Print(4, 232, ed.filename + " ", 196, 196, 255 - help.glow, true);
}
}
else if(ed.loadmod)
{
FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32));
FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0));
dwgfx.Print(4, 224, "Enter map filename to load:", 255, 255, 255, false);
if(ed.entframe < 2)
{
dwgfx.Print(4, 232, ed.filename + "_", 196, 196, 255 - help.glow, true);
}
else
{
dwgfx.Print(4, 232, ed.filename + " ", 196, 196, 255 - help.glow, true);
}
}
else if(ed.roomnamemod)
{
FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32));
FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0));
dwgfx.Print(4, 224, "Enter new room name:", 255, 255, 255, false);
if(ed.entframe < 2)
{
dwgfx.Print(4,
232,
ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname + "_",
196,
196,
255 - help.glow,
true);
}
else
{
dwgfx.Print(4,
232,
ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname + " ",
196,
196,
255 - help.glow,
true);
}
}
else if(ed.roomtextmod)
{
FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32));
FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0));
dwgfx.Print(4, 224, "Enter text string:", 255, 255, 255, false);
if(ed.entframe < 2)
{
dwgfx.Print(4, 232, edentity[ed.roomtextent].scriptname + "_", 196, 196, 255 - help.glow, true);
}
else
{
dwgfx.Print(4, 232, edentity[ed.roomtextent].scriptname + " ", 196, 196, 255 - help.glow, true);
}
}
else if(ed.warpmod)
{
//placing warp token
FillRect(dwgfx.backBuffer, 0, 221, 320, 240, dwgfx.getRGB(32, 32, 32));
FillRect(dwgfx.backBuffer, 0, 222, 320, 240, dwgfx.getRGB(0, 0, 0));
dwgfx.Print(4, 224, "Left click to place warp destination", 196, 196, 255 - help.glow, false);
dwgfx.Print(4, 232, "Right click to cancel", 196, 196, 255 - help.glow, false);
}
else
{
if(ed.spacemod)
{
FillRect(dwgfx.backBuffer, 0, 208, 320, 240, dwgfx.getRGB(32, 32, 32));
FillRect(dwgfx.backBuffer, 0, 209, 320, 240, dwgfx.getRGB(0, 0, 0));
//Draw little icons for each thingy
int tx = 6, ty = 211, tg = 32;
if(ed.spacemenu == 0)
{
for(int i = 0; i < 10; i++)
{
FillRect(dwgfx.backBuffer, 4 + (i * tg), 209, 20, 20, dwgfx.getRGB(32, 32, 32));
}
FillRect(dwgfx.backBuffer, 4 + (ed.drawmode * tg), 209, 20, 20, dwgfx.getRGB(64, 64, 64));
//0:
dwgfx.drawtile(tx, ty, 83);
dwgfx.drawtile(tx + 8, ty, 83);
dwgfx.drawtile(tx, ty + 8, 83);
dwgfx.drawtile(tx + 8, ty + 8, 83);
//1:
tx += tg;
dwgfx.drawtile(tx, ty, 680);
dwgfx.drawtile(tx + 8, ty, 680);
dwgfx.drawtile(tx, ty + 8, 680);
dwgfx.drawtile(tx + 8, ty + 8, 680);
//2:
tx += tg;
dwgfx.drawtile(tx + 4, ty + 4, 8);
//3:
tx += tg;
dwgfx.drawsprite(tx, ty, 22, 196, 196, 196);
//4:
tx += tg;
dwgfx.drawsprite(tx, ty, 21, 196, 196, 196);
//5:
tx += tg;
dwgfx.drawtile(tx, ty + 4, 3);
dwgfx.drawtile(tx + 8, ty + 4, 4);
//6:
tx += tg;
dwgfx.drawtile(tx, ty + 4, 24);
dwgfx.drawtile(tx + 8, ty + 4, 24);
//7:
tx += tg;
dwgfx.drawtile(tx, ty + 4, 1);
dwgfx.drawtile(tx + 8, ty + 4, 1);
//8:
tx += tg;
dwgfx.drawsprite(tx, ty, 78 + ed.entframe, 196, 196, 196);
//9:
tx += tg;
FillRect(dwgfx.backBuffer, tx + 2, ty + 8, 12, 1, dwgfx.getRGB(255, 255, 255));
for(int i = 0; i < 9; i++)
{
fillboxabs(dwgfx, 4 + (i * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96));
dwgfx.Print(22 + (i * tg) - 4, 225 - 4, help.String(i + 1), 164, 164, 164, false);
}
if(ed.drawmode == 9)
dwgfx.Print(22 + (ed.drawmode * tg) - 4, 225 - 4, "0", 255, 255, 255, false);
fillboxabs(dwgfx, 4 + (9 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96));
dwgfx.Print(22 + (9 * tg) - 4, 225 - 4, "0", 164, 164, 164, false);
fillboxabs(dwgfx, 4 + (ed.drawmode * tg), 209, 20, 20, dwgfx.getRGB(200, 200, 200));
if(ed.drawmode < 9)
{
dwgfx
.Print(22 + (ed.drawmode * tg) - 4, 225 - 4, help.String(ed.drawmode + 1), 255, 255, 255, false);
}
dwgfx.Print(4, 232, "1/2", 196, 196, 255 - help.glow, false);
}
else
{
for(int i = 0; i < 7; i++)
{
FillRect(dwgfx.backBuffer, 4 + (i * tg), 209, 20, 20, dwgfx.getRGB(32, 32, 32));
}
FillRect(dwgfx.backBuffer, 4 + ((ed.drawmode - 10) * tg), 209, 20, 20, dwgfx.getRGB(64, 64, 64));
//10:
dwgfx.Print(tx, ty, "A", 196, 196, 255 - help.glow, false);
dwgfx.Print(tx + 8, ty, "B", 196, 196, 255 - help.glow, false);
dwgfx.Print(tx, ty + 8, "C", 196, 196, 255 - help.glow, false);
dwgfx.Print(tx + 8, ty + 8, "D", 196, 196, 255 - help.glow, false);
//11:
tx += tg;
dwgfx.drawsprite(tx, ty, 17, 196, 196, 196);
//12:
tx += tg;
fillboxabs(dwgfx, tx + 4, ty + 4, 8, 8, dwgfx.getRGB(96, 96, 96));
//13:
tx += tg;
dwgfx.drawsprite(tx, ty, 18 + (ed.entframe % 2), 196, 196, 196);
//14:
tx += tg;
FillRect(dwgfx.backBuffer, tx + 6, ty + 2, 4, 12, dwgfx.getRGB(255, 255, 255));
//15:
tx += tg;
dwgfx.drawsprite(tx, ty, 186, 75, 75, 255 - help.glow / 4 - (fRandom() * 20));
//16:
tx += tg;
dwgfx
.drawsprite(tx, ty, 184, 160 - help.glow / 2 - (fRandom() * 20), 200 - help.glow / 2, 220 - help.glow);
if(ed.drawmode == 10)
dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "R", 255, 255, 255, false);
if(ed.drawmode == 11)
dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "T", 255, 255, 255, false);
if(ed.drawmode == 12)
dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "Y", 255, 255, 255, false);
if(ed.drawmode == 13)
dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "U", 255, 255, 255, false);
if(ed.drawmode == 14)
dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "I", 255, 255, 255, false);
if(ed.drawmode == 15)
dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "O", 255, 255, 255, false);
if(ed.drawmode == 16)
dwgfx.Print(22 + ((ed.drawmode - 10) * tg) - 4, 225 - 4, "P", 255, 255, 255, false);
fillboxabs(dwgfx, 4 + (0 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96));
dwgfx.Print(22 + (0 * tg) - 4, 225 - 4, "R", 164, 164, 164, false);
fillboxabs(dwgfx, 4 + (1 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96));
dwgfx.Print(22 + (1 * tg) - 4, 225 - 4, "T", 164, 164, 164, false);
fillboxabs(dwgfx, 4 + (2 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96));
dwgfx.Print(22 + (2 * tg) - 4, 225 - 4, "Y", 164, 164, 164, false);
fillboxabs(dwgfx, 4 + (3 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96));
dwgfx.Print(22 + (3 * tg) - 4, 225 - 4, "U", 164, 164, 164, false);
fillboxabs(dwgfx, 4 + (4 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96));
dwgfx.Print(22 + (4 * tg) - 4, 225 - 4, "I", 164, 164, 164, false);
fillboxabs(dwgfx, 4 + (5 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96));
dwgfx.Print(22 + (5 * tg) - 4, 225 - 4, "O", 164, 164, 164, false);
fillboxabs(dwgfx, 4 + (6 * tg), 209, 20, 20, dwgfx.getRGB(96, 96, 96));
dwgfx.Print(22 + (6 * tg) - 4, 225 - 4, "P", 164, 164, 164, false);
dwgfx.Print(4, 232, "2/2", 196, 196, 255 - help.glow, false);
}
dwgfx.Print(128, 232, "< and > keys change tool", 196, 196, 255 - help.glow, false);
FillRect(dwgfx.backBuffer, 0, 198, 120, 10, dwgfx.getRGB(32, 32, 32));
FillRect(dwgfx.backBuffer, 0, 199, 119, 9, dwgfx.getRGB(0, 0, 0));
switch(ed.drawmode)
{
case 0:
dwgfx.Print(2, 199, "1: Walls", 196, 196, 255 - help.glow);
break;
case 1:
dwgfx.Print(2, 199, "2: Backing", 196, 196, 255 - help.glow);
break;
case 2:
dwgfx.Print(2, 199, "3: Spikes", 196, 196, 255 - help.glow);
break;
case 3:
dwgfx.Print(2, 199, "4: Trinkets", 196, 196, 255 - help.glow);
break;
case 4:
dwgfx.Print(2, 199, "5: Checkpoint", 196, 196, 255 - help.glow);
break;
case 5:
dwgfx.Print(2, 199, "6: Disappear", 196, 196, 255 - help.glow);
break;
case 6:
dwgfx.Print(2, 199, "7: Conveyors", 196, 196, 255 - help.glow);
break;
case 7:
dwgfx.Print(2, 199, "8: Moving", 196, 196, 255 - help.glow);
break;
case 8:
dwgfx.Print(2, 199, "9: Enemies", 196, 196, 255 - help.glow);
break;
case 9:
dwgfx.Print(2, 199, "0: Grav Line", 196, 196, 255 - help.glow);
break;
case 10:
dwgfx.Print(2, 199, "R: Roomtext", 196, 196, 255 - help.glow);
break;
case 11:
dwgfx.Print(2, 199, "T: Terminal", 196, 196, 255 - help.glow);
break;
case 12:
dwgfx.Print(2, 199, "Y: Script Box", 196, 196, 255 - help.glow);
break;
case 13:
dwgfx.Print(2, 199, "U: Warp Token", 196, 196, 255 - help.glow);
break;
case 14:
dwgfx.Print(2, 199, "I: Warp Lines", 196, 196, 255 - help.glow);
break;
case 15:
dwgfx.Print(2, 199, "O: Crewmate", 196, 196, 255 - help.glow);
break;
case 16:
dwgfx.Print(2, 199, "P: Start Point", 196, 196, 255 - help.glow);
break;
}
FillRect(dwgfx.backBuffer, 260, 198, 80, 10, dwgfx.getRGB(32, 32, 32));
FillRect(dwgfx.backBuffer, 261, 199, 80, 9, dwgfx.getRGB(0, 0, 0));
dwgfx.Print(268,
199,
"(" + help.String(ed.levx + 1) + "," + help.String(ed.levy + 1) + ")",
196,
196,
255 - help.glow,
false);
}
else
{
//FillRect(dwgfx.backBuffer, 0,230,72,240, dwgfx.RGB(32,32,32));
//FillRect(dwgfx.backBuffer, 0,231,71,240, dwgfx.RGB(0,0,0));
if(ed.level[ed.levx + (ed.maxwidth * ed.levy)].roomname != "")
{
if(ed.tiley < 28)
{
if(ed.roomnamehide > 0)
ed.roomnamehide--;
FillRect(dwgfx.backBuffer, 0, 230 + ed.roomnamehide, 320, 10, dwgfx.getRGB(0, 0, 0));
dwgfx.Print(5,
231 + ed.roomnamehide,
ed.level[ed.levx + (ed.maxwidth * ed.levy)].roomname,
196,
196,
255 - help.glow,
true);
}
else
{
if(ed.roomnamehide < 12)
ed.roomnamehide++;
FillRect(dwgfx.backBuffer, 0, 230 + ed.roomnamehide, 320, 10, dwgfx.getRGB(0, 0, 0));
dwgfx.Print(5,
231 + ed.roomnamehide,
ed.level[ed.levx + (ed.maxwidth * ed.levy)].roomname,
196,
196,
255 - help.glow,
true);
}
dwgfx.Print(4, 222, "SPACE ^ SHIFT ^", 196, 196, 255 - help.glow, false);
dwgfx.Print(268,
222,
"(" + help.String(ed.levx + 1) + "," + help.String(ed.levy + 1) + ")",
196,
196,
255 - help.glow,
false);
}
else
{
dwgfx.Print(4, 232, "SPACE ^ SHIFT ^", 196, 196, 255 - help.glow, false);
dwgfx.Print(268,
232,
"(" + help.String(ed.levx + 1) + "," + help.String(ed.levy + 1) + ")",
196,
196,
255 - help.glow,
false);
}
}
if(ed.shiftmenu)
{
fillboxabs(dwgfx, 0, 127, 161 + 8, 140, dwgfx.getRGB(64, 64, 64));
FillRect(dwgfx.backBuffer, 0, 128, 160 + 8, 140, dwgfx.getRGB(0, 0, 0));
dwgfx.Print(4, 130, "F1: Change Tileset", 164, 164, 164, false);
dwgfx.Print(4, 140, "F2: Change Colour", 164, 164, 164, false);
dwgfx.Print(4, 150, "F3: Change Enemies", 164, 164, 164, false);
dwgfx.Print(4, 160, "F4: Enemy Bounds", 164, 164, 164, false);
dwgfx.Print(4, 170, "F5: Platform Bounds", 164, 164, 164, false);
dwgfx.Print(4, 190, "F10: Direct Mode", 164, 164, 164, false);
dwgfx.Print(4, 210, "W: Change Warp Dir", 164, 164, 164, false);
dwgfx.Print(4, 220, "E: Change Roomname", 164, 164, 164, false);
fillboxabs(dwgfx, 220, 207, 100, 60, dwgfx.getRGB(64, 64, 64));
FillRect(dwgfx.backBuffer, 221, 208, 160, 60, dwgfx.getRGB(0, 0, 0));
dwgfx.Print(224, 210, "S: Save Map", 164, 164, 164, false);
dwgfx.Print(224, 220, "L: Load Map", 164, 164, 164, false);
}
}
if(!ed.settingsmod && !ed.scripteditmod)
{
//Same as above, without borders
switch(ed.drawmode)
{
case 0:
dwgfx.Print(2, 2, "1: Walls", 196, 196, 255 - help.glow);
break;
case 1:
dwgfx.Print(2, 2, "2: Backing", 196, 196, 255 - help.glow);
break;
case 2:
dwgfx.Print(2, 2, "3: Spikes", 196, 196, 255 - help.glow);
break;
case 3:
dwgfx.Print(2, 2, "4: Trinkets", 196, 196, 255 - help.glow);
break;
case 4:
dwgfx.Print(2, 2, "5: Checkpoint", 196, 196, 255 - help.glow);
break;
case 5:
dwgfx.Print(2, 2, "6: Disappear", 196, 196, 255 - help.glow);
break;
case 6:
dwgfx.Print(2, 2, "7: Conveyors", 196, 196, 255 - help.glow);
break;
case 7:
dwgfx.Print(2, 2, "8: Moving", 196, 196, 255 - help.glow);
break;
case 8:
dwgfx.Print(2, 2, "9: Enemies", 196, 196, 255 - help.glow);
break;
case 9:
dwgfx.Print(2, 2, "0: Grav Line", 196, 196, 255 - help.glow);
break;
case 10:
dwgfx.Print(2, 2, "R: Roomtext", 196, 196, 255 - help.glow);
break;
case 11:
dwgfx.Print(2, 2, "T: Terminal", 196, 196, 255 - help.glow);
break;
case 12:
dwgfx.Print(2, 2, "Y: Script Box", 196, 196, 255 - help.glow);
break;
case 13:
dwgfx.Print(2, 2, "U: Warp Token", 196, 196, 255 - help.glow);
break;
case 14:
dwgfx.Print(2, 2, "I: Warp Lines", 196, 196, 255 - help.glow);
break;
case 15:
dwgfx.Print(2, 2, "O: Crewmate", 196, 196, 255 - help.glow);
break;
case 16:
dwgfx.Print(2, 2, "P: Start Point", 196, 196, 255 - help.glow);
break;
}
//dwgfx.Print(254, 2, "F1: HELP", 196, 196, 255 - help.glow, false);
}
/*
for(int i=0; i<script.customscript.size(); i++){
dwgfx.Print(0,i*8,script.customscript[i],255,255,255);
}
dwgfx.Print(0,8*script.customscript.size(),help.String(script.customscript.size()),255,255,255);
for(int i=0; i<ed.numhooks; i++){
dwgfx.Print(260,i*8,ed.hooklist[i],255,255,255);
}
dwgfx.Print(260,8*ed.numhooks,help.String(ed.numhooks),255,255,255);
*/
if(ed.notedelay > 0)
{
FillRect(dwgfx.backBuffer, 0, 115, 320, 18, dwgfx.getRGB(92, 92, 92));
FillRect(dwgfx.backBuffer, 0, 116, 320, 16, dwgfx.getRGB(0, 0, 0));
dwgfx.Print(0,
121,
ed.note,
196 - ((45 - ed.notedelay) * 4),
196 - ((45 - ed.notedelay) * 4),
196 - ((45 - ed.notedelay) * 4),
true);
}
if(game.test)
{
dwgfx.Print(5, 5, game.teststring, 196, 196, 255 - help.glow, false);
}
dwgfx.drawfade();
if(game.flashlight > 0 && !game.noflashingmode)
{
game.flashlight--;
dwgfx.flashlight();
}
if(game.screenshake > 0 && !game.noflashingmode)
{
game.screenshake--;
dwgfx.screenshake();
}
else
{
dwgfx.render();
}
//dwgfx.backbuffer.unlock();
}
void editorlogic(Graphics & dwgfx, Game & game, musicclass & music, mapclass & map, UtilityClass & help)
{
//Misc
help.updateglow();
map.bypos -= 2;
map.bscroll = -2;
ed.entframedelay--;
if(ed.entframedelay <= 0)
{
ed.entframe = (ed.entframe + 1) % 4;
ed.entframedelay = 8;
}
if(ed.notedelay > 0)
{
ed.notedelay--;
}
if(dwgfx.fademode == 1)
{
//Return to game
map.nexttowercolour();
map.colstate = 10;
game.gamestate = 1;
dwgfx.fademode = 4;
music.stopmusic();
music.play(6);
map.nexttowercolour();
ed.settingsmod = false;
dwgfx.backgrounddrawn = false;
game.createmenu("mainmenu");
}
}
void editorinput(KeyPoll & key,
Graphics & dwgfx,
Game & game,
mapclass & map,
entityclass & obj,
UtilityClass & help,
musicclass & music)
{
//TODO Mouse Input!
game.mx = (float)key.mx;
game.my = (float)key.my;
ed.tilex = (game.mx - (game.mx % 8)) / 8;
ed.tiley = (game.my - (game.my % 8)) / 8;
game.press_left = false;
game.press_right = false;
game.press_action = false;
game.press_map = false;
if(key.isDown(KEYBOARD_LEFT) || key.isDown(KEYBOARD_a))
{
game.press_left = true;
}
if(key.isDown(KEYBOARD_RIGHT) || key.isDown(KEYBOARD_d))
{
game.press_right = true;
}
if(key.isDown(KEYBOARD_z) || key.isDown(KEYBOARD_SPACE) || key.isDown(KEYBOARD_v))
{
// || key.isDown(KEYBOARD_UP) || key.isDown(KEYBOARD_DOWN)
game.press_action = true;
};
if(key.isDown(KEYBOARD_ENTER))
game.press_map = true;
if(key.isDown(27) && !ed.settingskey)
{
ed.settingskey = true;
if(ed.textentry)
{
key.disabletextentry();
ed.roomnamemod = false;
ed.loadmod = false;
ed.savemod = false;
ed.textentry = false;
ed.titlemod = false;
ed.desc1mod = false;
ed.desc2mod = false;
ed.desc3mod = false;
ed.websitemod = false;
ed.creatormod = false;
if(ed.scripttextmod)
{
ed.scripttextmod = false;
removeedentity(ed.scripttextmod);
}
ed.shiftmenu = false;
ed.shiftkey = false;
}
else if(ed.boundarymod > 0)
{
ed.boundarymod = 0;
}
else
{
ed.settingsmod = !ed.settingsmod;
dwgfx.backgrounddrawn = false;
game.createmenu("ed_settings");
map.nexttowercolour();
}
}
if(!key.isDown(27))
{
ed.settingskey = false;
}
if(key.keymap[SDLK_LCTRL] || key.keymap[SDLK_RCTRL])
{
if(key.leftbutton)
key.rightbutton = true;
}
if(ed.scripteditmod)
{
if(ed.scripthelppage == 0)
{
//hook select menu
if(ed.keydelay > 0)
ed.keydelay--;
if(key.keymap[SDLK_UP] && ed.keydelay <= 0)
{
ed.keydelay = 6;
ed.hookmenu--;
}
if(key.keymap[SDLK_DOWN] && ed.keydelay <= 0)
{
ed.keydelay = 6;
ed.hookmenu++;
}
if(ed.hookmenu >= ed.numhooks)
{
ed.hookmenu = ed.numhooks - 1;
}
if(ed.hookmenu < 0)
ed.hookmenu = 0;
if(ed.hookmenu < ed.hookmenupage)
{
ed.hookmenupage = ed.hookmenu;
}
if(ed.hookmenu >= ed.hookmenupage + 9)
{
ed.hookmenupage = ed.hookmenu + 8;
}
if(!key.keymap[SDLK_BACKSPACE])
ed.deletekeyheld = 0;
if(key.keymap[SDLK_BACKSPACE] && ed.deletekeyheld == 0)
{
ed.deletekeyheld = 1;
music.playef(2);
ed.removehook(ed.hooklist[(ed.numhooks - 1) - ed.hookmenu]);
}
if(!game.press_action && !game.press_left && !game.press_right && !key.keymap[SDLK_UP]
&& !key.keymap[SDLK_DOWN] && !key.isDown(27))
game.jumpheld = false;
if(!game.jumpheld)
{
if(game.press_action || game.press_left || game.press_right || game.press_map || key.keymap[SDLK_UP]
|| key.keymap[SDLK_DOWN] || key.isDown(27))
{
game.jumpheld = true;
}
if((game.press_action || game.press_map) && ed.numhooks > 0)
{
game.mapheld = true;
ed.scripthelppage = 1;
key.keybuffer = "";
ed.sbscript = ed.hooklist[(ed.numhooks - 1) - ed.hookmenu];
ed.loadhookineditor(ed.sbscript);
ed.sby = ed.sblength - 1;
ed.pagey = 0;
while(ed.sby >= 20)
{
ed.pagey++;
ed.sby--;
}
key.keybuffer = ed.sb[ed.pagey + ed.sby];
ed.sbx = ed.sb[ed.pagey + ed.sby].length();
}
if(key.isDown(27))
{
ed.scripteditmod = false;
ed.settingsmod = false;
}
}
}
else if(ed.scripthelppage == 1)
{
//Script editor!
if(key.isDown(27))
{
ed.scripthelppage = 0;
game.jumpheld = true;
//save the script for use again!
ed.addhook(ed.sbscript);
}
if(ed.keydelay > 0)
ed.keydelay--;
if(key.keymap[SDLK_UP] && ed.keydelay <= 0)
{
ed.keydelay = 6;
ed.sby--;
if(ed.sby <= 5)
{
if(ed.pagey > 0)
{
ed.pagey--;
ed.sby++;
}
else
{
if(ed.sby < 0)
ed.sby = 0;
}
}
key.keybuffer = ed.sb[ed.pagey + ed.sby];
}
if(key.keymap[SDLK_DOWN] && ed.keydelay <= 0)
{
ed.keydelay = 6;
if(ed.sby + ed.pagey < ed.sblength)
{
ed.sby++;
if(ed.sby >= 20)
{
ed.pagey++;
ed.sby--;
}
}
key.keybuffer = ed.sb[ed.pagey + ed.sby];
}
if(key.pressedbackspace && ed.sb[ed.pagey + ed.sby] == "")
{
//Remove this line completely
ed.removeline(ed.pagey + ed.sby);
ed.sby--;
if(ed.sby <= 5)
{
if(ed.pagey > 0)
{
ed.pagey--;
ed.sby++;
}
else
{
if(ed.sby < 0)
ed.sby = 0;
}
}
key.keybuffer = ed.sb[ed.pagey + ed.sby];
}
ed.sb[ed.pagey + ed.sby] = key.keybuffer;
ed.sbx = ed.sb[ed.pagey + ed.sby].length();
if(!game.press_map && !key.isDown(27))
game.mapheld = false;
if(!game.mapheld)
{
if(game.press_map)
{
game.mapheld = true;
//Continue to next line
if(ed.sby + ed.pagey >= ed.sblength) //we're on the last line
{
ed.sby++;
if(ed.sby >= 20)
{
ed.pagey++;
ed.sby--;
}
if(ed.sby + ed.pagey >= ed.sblength)
ed.sblength = ed.sby + ed.pagey;
key.keybuffer = ed.sb[ed.pagey + ed.sby];
ed.sbx = ed.sb[ed.pagey + ed.sby].length();
}
else
{
//We're not, insert a line instead
ed.sby++;
if(ed.sby >= 20)
{
ed.pagey++;
ed.sby--;
}
ed.insertline(ed.sby + ed.pagey);
key.keybuffer = "";
ed.sbx = 0;
}
}
}
}
}
else if(ed.textentry)
{
if(ed.roomnamemod)
{
ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname = key.keybuffer;
}
else if(ed.savemod)
{
ed.filename = key.keybuffer;
}
else if(ed.loadmod)
{
ed.filename = key.keybuffer;
}
else if(ed.roomtextmod)
{
edentity[ed.roomtextent].scriptname = key.keybuffer;
}
else if(ed.scripttextmod)
{
edentity[ed.scripttextent].scriptname = key.keybuffer;
}
else if(ed.titlemod)
{
EditorData::GetInstance().title = key.keybuffer;
}
else if(ed.creatormod)
{
EditorData::GetInstance().creator = key.keybuffer;
}
else if(ed.websitemod)
{
ed.website = key.keybuffer;
}
else if(ed.desc1mod)
{
ed.Desc1 = key.keybuffer;
}
else if(ed.desc2mod)
{
ed.Desc2 = key.keybuffer;
}
else if(ed.desc3mod)
{
ed.Desc3 = key.keybuffer;
}
if(!game.press_map && !key.isDown(27))
game.mapheld = false;
if(!game.mapheld)
{
if(game.press_map)
{
game.mapheld = true;
if(ed.roomnamemod)
{
ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname = key.keybuffer;
ed.roomnamemod = false;
}
else if(ed.savemod)
{
std::string savestring = ed.filename + ".vvvvvv";
ed.save(savestring);
ed.note = "[ Saved map: " + ed.filename + ".vvvvvv]";
ed.notedelay = 45;
ed.savemod = false;
ed.shiftmenu = false;
ed.shiftkey = false;
if(ed.saveandquit)
{
//quit editor
dwgfx.fademode = 2;
}
}
else if(ed.loadmod)
{
std::string loadstring = ed.filename + ".vvvvvv";
ed.load(loadstring);
ed.note = "[ Loaded map: " + ed.filename + ".vvvvvv]";
ed.notedelay = 45;
ed.loadmod = false;
ed.shiftmenu = false;
ed.shiftkey = false;
}
else if(ed.roomtextmod)
{
edentity[ed.roomtextent].scriptname = key.keybuffer;
ed.roomtextmod = false;
ed.shiftmenu = false;
ed.shiftkey = false;
}
else if(ed.scripttextmod)
{
edentity[ed.scripttextent].scriptname = key.keybuffer;
ed.scripttextmod = false;
ed.clearscriptbuffer();
if(!ed.checkhook(edentity[ed.scripttextent].scriptname))
{
ed.addhook(edentity[ed.scripttextent].scriptname);
}
}
else if(ed.titlemod)
{
EditorData::GetInstance().title = key.keybuffer;
ed.titlemod = false;
}
else if(ed.creatormod)
{
EditorData::GetInstance().creator = key.keybuffer;
ed.creatormod = false;
}
else if(ed.websitemod)
{
ed.website = key.keybuffer;
ed.websitemod = false;
}
else if(ed.desc1mod)
{
ed.Desc1 = key.keybuffer;
}
else if(ed.desc2mod)
{
ed.Desc2 = key.keybuffer;
}
else if(ed.desc3mod)
{
ed.Desc3 = key.keybuffer;
ed.desc3mod = false;
}
key.disabletextentry();
ed.textentry = false;
if(ed.desc1mod)
{
ed.desc1mod = false;
ed.textentry = true;
ed.desc2mod = true;
key.enabletextentry();
key.keybuffer = ed.Desc2;
}
else if(ed.desc2mod)
{
ed.desc2mod = false;
ed.textentry = true;
ed.desc3mod = true;
key.enabletextentry();
key.keybuffer = ed.Desc3;
}
}
}
}
else
{
if(ed.settingsmod)
{
if(!game.press_action && !game.press_left && !game.press_right && !key.keymap[SDLK_UP]
&& !key.keymap[SDLK_DOWN])
game.jumpheld = false;
if(!game.jumpheld)
{
if(game.press_action || game.press_left || game.press_right || game.press_map || key.keymap[SDLK_UP]
|| key.keymap[SDLK_DOWN])
{
game.jumpheld = true;
}
if(game.menustart)
{
if(game.press_left || key.keymap[SDLK_UP])
{
game.currentmenuoption--;
}
else if(game.press_right || key.keymap[SDLK_DOWN])
{
game.currentmenuoption++;
}
}
if(game.currentmenuoption < 0)
game.currentmenuoption = game.nummenuoptions - 1;
if(game.currentmenuoption >= game.nummenuoptions)
game.currentmenuoption = 0;
if(game.press_action)
{
if(game.currentmenuname == "ed_desc")
{
if(game.currentmenuoption == 0)
{
ed.textentry = true;
ed.titlemod = true;
key.enabletextentry();
key.keybuffer = EditorData::GetInstance().title;
}
else if(game.currentmenuoption == 1)
{
ed.textentry = true;
ed.creatormod = true;
key.enabletextentry();
key.keybuffer = EditorData::GetInstance().creator;
}
else if(game.currentmenuoption == 2)
{
ed.textentry = true;
ed.desc1mod = true;
key.enabletextentry();
key.keybuffer = ed.Desc1;
}
else if(game.currentmenuoption == 3)
{
ed.textentry = true;
ed.websitemod = true;
key.enabletextentry();
key.keybuffer = ed.website;
}
else if(game.currentmenuoption == 4)
{
music.playef(11);
game.createmenu("ed_settings");
map.nexttowercolour();
}
}
else if(game.currentmenuname == "ed_settings")
{
if(game.currentmenuoption == 0)
{
//Change level description stuff
music.playef(11);
game.createmenu("ed_desc");
map.nexttowercolour();
}
else if(game.currentmenuoption == 1)
{
//Enter script editormode
music.playef(11);
ed.scripteditmod = true;
ed.clearscriptbuffer();
key.enabletextentry();
key.keybuffer = "";
ed.hookmenupage = 0;
ed.hookmenu = 0;
ed.scripthelppage = 0;
ed.scripthelppagedelay = 0;
ed.sby = 0;
ed.sbx = 0, ed.pagey = 0;
}
else if(game.currentmenuoption == 2)
{
music.playef(11);
game.createmenu("ed_music");
map.nexttowercolour();
if(ed.levmusic > 0)
music.play(ed.levmusic);
}
else if(game.currentmenuoption == 3)
{
//Load level
ed.settingsmod = false;
dwgfx.backgrounddrawn = false;
map.nexttowercolour();
ed.loadmod = true;
ed.textentry = true;
key.enabletextentry();
key.keybuffer = ed.filename;
ed.keydelay = 6;
game.mapheld = true;
dwgfx.backgrounddrawn = false;
}
else if(game.currentmenuoption == 4)
{
//Save level
ed.settingsmod = false;
dwgfx.backgrounddrawn = false;
map.nexttowercolour();
ed.savemod = true;
ed.textentry = true;
key.enabletextentry();
key.keybuffer = ed.filename;
ed.keydelay = 6;
game.mapheld = true;
dwgfx.backgrounddrawn = false;
}
else if(game.currentmenuoption == 5)
{
music.playef(11);
game.createmenu("ed_quit");
map.nexttowercolour();
}
}
else if(game.currentmenuname == "ed_music")
{
if(game.currentmenuoption == 0)
{
ed.levmusic++;
if(ed.levmusic == 5)
ed.levmusic = 6;
if(ed.levmusic == 7)
ed.levmusic = 8;
if(ed.levmusic == 9)
ed.levmusic = 10;
if(ed.levmusic == 15)
ed.levmusic = 0;
if(ed.levmusic > 0)
{
music.play(ed.levmusic);
}
else
{
music.haltdasmusik();
}
music.playef(11);
}
else if(game.currentmenuoption == 1)
{
music.playef(11);
music.fadeout();
game.createmenu("ed_settings");
map.nexttowercolour();
}
}
else if(game.currentmenuname == "ed_quit")
{
if(game.currentmenuoption == 0)
{
//Saving and quit
ed.saveandquit = true;
ed.settingsmod = false;
dwgfx.backgrounddrawn = false;
map.nexttowercolour();
ed.savemod = true;
ed.textentry = true;
key.enabletextentry();
key.keybuffer = ed.filename;
ed.keydelay = 6;
game.mapheld = true;
dwgfx.backgrounddrawn = false;
}
else if(game.currentmenuoption == 1)
{
//Quit without saving
music.playef(11);
music.fadeout();
dwgfx.fademode = 2;
}
else if(game.currentmenuoption == 2)
{
//Go back to editor
music.playef(11);
game.createmenu("ed_settings");
map.nexttowercolour();
}
}
}
}
}
else
{
//Shortcut keys
//TO DO: make more user friendly
if(key.keymap[SDLK_F1] && ed.keydelay == 0)
{
ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset++;
dwgfx.backgrounddrawn = false;
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset >= 5)
ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset = 0;
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0)
{
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 32)
ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0;
}
else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 1)
{
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 8)
ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0;
}
else
{
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 6)
ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0;
}
ed.notedelay = 45;
switch(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset)
{
case 0:
ed.note = "Now using Space Station Tileset";
break;
case 1:
ed.note = "Now using Outside Tileset";
break;
case 2:
ed.note = "Now using Lab Tileset";
break;
case 3:
ed.note = "Now using Warp Zone Tileset";
break;
case 4:
ed.note = "Now using Ship Tileset";
break;
case 5:
ed.note = "Now using Tower Tileset";
break;
default:
ed.note = "Tileset Changed";
break;
}
ed.updatetiles = true;
ed.keydelay = 6;
}
if(key.keymap[SDLK_F2] && ed.keydelay == 0)
{
ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol++;
dwgfx.backgrounddrawn = false;
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 0)
{
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 32)
ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0;
}
else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset == 1)
{
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 8)
ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0;
}
else
{
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol >= 6)
ed.level[ed.levx + (ed.levy * ed.maxwidth)].tilecol = 0;
}
ed.updatetiles = true;
ed.keydelay = 6;
ed.notedelay = 45;
ed.note = "Tileset Colour Changed";
}
if(key.keymap[SDLK_F3] && ed.keydelay == 0)
{
ed.level[ed.levx + (ed.levy * ed.maxwidth)].enemytype
= (ed.level[ed.levx + (ed.levy * ed.maxwidth)].enemytype + 1) % 10;
ed.keydelay = 6;
ed.notedelay = 45;
ed.note = "Enemy Type Changed";
}
if(key.keymap[SDLK_F4] && ed.keydelay == 0)
{
ed.keydelay = 6;
ed.boundarytype = 1;
ed.boundarymod = 1;
}
if(key.keymap[SDLK_F5] && ed.keydelay == 0)
{
ed.keydelay = 6;
ed.boundarytype = 2;
ed.boundarymod = 1;
}
if(key.keymap[SDLK_F10] && ed.keydelay == 0)
{
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode == 1)
{
ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode = 0;
ed.note = "Direct Mode Disabled";
}
else
{
ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode = 1;
ed.note = "Direct Mode Enabled";
}
dwgfx.backgrounddrawn = false;
ed.notedelay = 45;
ed.updatetiles = true;
ed.keydelay = 6;
}
if(key.keymap[SDLK_1])
ed.drawmode = 0;
if(key.keymap[SDLK_2])
ed.drawmode = 1;
if(key.keymap[SDLK_3])
ed.drawmode = 2;
if(key.keymap[SDLK_4])
ed.drawmode = 3;
if(key.keymap[SDLK_5])
ed.drawmode = 4;
if(key.keymap[SDLK_6])
ed.drawmode = 5;
if(key.keymap[SDLK_7])
ed.drawmode = 6;
if(key.keymap[SDLK_8])
ed.drawmode = 7;
if(key.keymap[SDLK_9])
ed.drawmode = 8;
if(key.keymap[SDLK_0])
ed.drawmode = 9;
if(key.keymap[SDLK_r])
ed.drawmode = 10;
if(key.keymap[SDLK_t])
ed.drawmode = 11;
if(key.keymap[SDLK_y])
ed.drawmode = 12;
if(key.keymap[SDLK_u])
ed.drawmode = 13;
if(key.keymap[SDLK_i])
ed.drawmode = 14;
if(key.keymap[SDLK_o])
ed.drawmode = 15;
if(key.keymap[SDLK_p])
ed.drawmode = 16;
if(key.keymap[SDLK_w] && ed.keydelay == 0)
{
int j = 0, tx = 0, ty = 0;
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
if(edentity[i].t == 50)
{
tx = (edentity[i].p1 - (edentity[i].p1 % 40)) / 40;
ty = (edentity[i].p2 - (edentity[i].p2 % 30)) / 30;
if(tx == ed.levx && ty == ed.levy)
{
j++;
}
}
}
if(j > 0)
{
ed.note = "ERROR: Cannot have both warp types";
ed.notedelay = 45;
}
else
{
ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir
= (ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir + 1) % 4;
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir == 0)
{
ed.note = "Room warping disabled";
ed.notedelay = 45;
dwgfx.backgrounddrawn = false;
}
else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir == 1)
{
ed.note = "Room warps horizontally";
ed.notedelay = 45;
dwgfx.backgrounddrawn = false;
}
else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir == 2)
{
ed.note = "Room warps vertically";
ed.notedelay = 45;
dwgfx.backgrounddrawn = false;
}
else if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].warpdir == 3)
{
ed.note = "Room warps in all directions";
ed.notedelay = 45;
dwgfx.backgrounddrawn = false;
}
}
ed.keydelay = 6;
}
if(key.keymap[SDLK_e] && ed.keydelay == 0)
{
ed.roomnamemod = true;
ed.textentry = true;
key.enabletextentry();
key.keybuffer = ed.level[ed.levx + (ed.levy * ed.maxwidth)].roomname;
ed.keydelay = 6;
game.mapheld = true;
}
//Save and load
if(key.keymap[SDLK_s] && ed.keydelay == 0)
{
ed.savemod = true;
ed.textentry = true;
key.enabletextentry();
key.keybuffer = ed.filename;
ed.keydelay = 6;
game.mapheld = true;
dwgfx.backgrounddrawn = false;
}
if(key.keymap[SDLK_l] && ed.keydelay == 0)
{
ed.loadmod = true;
ed.textentry = true;
key.enabletextentry();
key.keybuffer = ed.filename;
ed.keydelay = 6;
game.mapheld = true;
dwgfx.backgrounddrawn = false;
}
if(!game.press_map)
game.mapheld = false;
if(!game.mapheld)
{
if(game.press_map)
{
game.mapheld = true;
//Ok! Scan the room for the closest checkpoint
int testeditor = -1;
int startpoint = 0;
//First up; is there a start point on this screen?
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
//if() on screen
if(edentity[i].t == 16 && testeditor == -1)
{
int tx = (edentity[i].x - (edentity[i].x % 40)) / 40;
int ty = (edentity[i].y - (edentity[i].y % 30)) / 30;
if(tx == ed.levx && ty == ed.levy)
{
testeditor = i;
startpoint = 1;
}
}
}
if(testeditor == -1)
{
//Ok, settle for a check point
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
//if() on screen
if(edentity[i].t == 10 && testeditor == -1)
{
int tx = (edentity[i].x - (edentity[i].x % 40)) / 40;
int ty = (edentity[i].y - (edentity[i].y % 30)) / 30;
if(tx == ed.levx && ty == ed.levy)
{
testeditor = i;
}
}
}
}
if(testeditor == -1)
{
ed.note = "ERROR: No checkpoint to spawn at";
ed.notedelay = 45;
}
else
{
if(startpoint == 0)
{
//Checkpoint spawn
int tx = (edentity[testeditor].x - (edentity[testeditor].x % 40)) / 40;
int ty = (edentity[testeditor].y - (edentity[testeditor].y % 30)) / 30;
game.edsavex = (edentity[testeditor].x % 40) * 8;
game.edsavey = (edentity[testeditor].y % 30) * 8;
game.edsaverx = 100 + tx;
game.edsavery = 100 + ty;
game.edsavegc = edentity[testeditor].p1;
if(game.edsavegc == 0)
{
game.edsavey--;
}
else
{
game.edsavey -= 8;
}
game.edsavedir = 0;
}
else
{
//Start point spawn
int tx = (edentity[testeditor].x - (edentity[testeditor].x % 40)) / 40;
int ty = (edentity[testeditor].y - (edentity[testeditor].y % 30)) / 30;
game.edsavex = ((edentity[testeditor].x % 40) * 8) - 4;
game.edsavey = (edentity[testeditor].y % 30) * 8;
game.edsaverx = 100 + tx;
game.edsavery = 100 + ty;
game.edsavegc = 0;
game.edsavey--;
game.edsavedir = 1 - edentity[testeditor].p1;
}
music.stopmusic();
dwgfx.backgrounddrawn = false;
script.startgamemode(21, dwgfx, game, map, obj, music);
}
//Return to game
//game.gamestate=GAMEMODE;
/*if(dwgfx.fademode==0)
{
dwgfx.fademode = 2;
music.fadeout();
}*/
}
}
if(key.keymap[SDLK_x])
{
ed.xmod = true;
}
else
{
ed.xmod = false;
}
if(key.keymap[SDLK_z])
{
ed.zmod = true;
}
else
{
ed.zmod = false;
}
//Keyboard shortcuts
if(ed.keydelay > 0)
{
ed.keydelay--;
}
else
{
if(key.keymap[SDLK_LSHIFT] || key.keymap[SDLK_RSHIFT])
{
if(key.keymap[SDLK_UP])
{
ed.keydelay = 6;
ed.mapheight--;
}
else if(key.keymap[SDLK_DOWN])
{
ed.keydelay = 6;
ed.mapheight++;
}
if(key.keymap[SDLK_LEFT])
{
ed.keydelay = 6;
ed.mapwidth--;
}
else if(key.keymap[SDLK_RIGHT])
{
ed.keydelay = 6;
ed.mapwidth++;
}
if(ed.keydelay == 6)
{
if(ed.mapwidth < 1)
ed.mapwidth = 1;
if(ed.mapheight < 1)
ed.mapheight = 1;
if(ed.mapwidth >= ed.maxwidth)
ed.mapwidth = ed.maxwidth;
if(ed.mapheight >= ed.maxheight)
ed.mapheight = ed.maxheight;
ed.note = "Mapsize is now [" + help.String(ed.mapwidth) + "," + help.String(ed.mapheight) + "]";
ed.notedelay = 45;
}
}
else
{
if(key.keymap[SDLK_COMMA])
{
ed.drawmode--;
ed.keydelay = 6;
}
else if(key.keymap[SDLK_PERIOD])
{
ed.drawmode++;
ed.keydelay = 6;
}
if(ed.drawmode < 0)
{
ed.drawmode = 16;
if(ed.spacemod)
ed.spacemenu = 0;
}
if(ed.drawmode > 16)
ed.drawmode = 0;
if(ed.drawmode > 9)
{
if(ed.spacemod)
ed.spacemenu = 1;
}
else
{
if(ed.spacemod)
ed.spacemenu = 0;
}
if(key.keymap[SDLK_LCTRL] || key.keymap[SDLK_RCTRL])
{
ed.dmtileeditor = 10;
if(key.keymap[SDLK_LEFT])
{
ed.dmtile--;
ed.keydelay = 3;
if(ed.dmtile < 0)
ed.dmtile += 1200;
}
else if(key.keymap[SDLK_RIGHT])
{
ed.dmtile++;
ed.keydelay = 3;
if(ed.dmtile >= 1200)
ed.dmtile -= 1200;
}
if(key.keymap[SDLK_UP])
{
ed.dmtile -= 40;
ed.keydelay = 3;
if(ed.dmtile < 0)
ed.dmtile += 1200;
}
else if(key.keymap[SDLK_DOWN])
{
ed.dmtile += 40;
ed.keydelay = 3;
if(ed.dmtile >= 1200)
ed.dmtile -= 1200;
}
}
else
{
if(key.keymap[SDLK_UP])
{
ed.keydelay = 6;
dwgfx.backgrounddrawn = false;
ed.levy--;
ed.updatetiles = true;
ed.changeroom = true;
}
else if(key.keymap[SDLK_DOWN])
{
ed.keydelay = 6;
dwgfx.backgrounddrawn = false;
ed.levy++;
ed.updatetiles = true;
ed.changeroom = true;
}
else if(key.keymap[SDLK_LEFT])
{
ed.keydelay = 6;
dwgfx.backgrounddrawn = false;
ed.levx--;
ed.updatetiles = true;
ed.changeroom = true;
}
else if(key.keymap[SDLK_RIGHT])
{
ed.keydelay = 6;
dwgfx.backgrounddrawn = false;
ed.levx++;
ed.updatetiles = true;
ed.changeroom = true;
}
}
if(ed.levx < 0)
ed.levx += ed.mapwidth;
if(ed.levx >= ed.mapwidth)
ed.levx -= ed.mapwidth;
if(ed.levy < 0)
ed.levy += ed.mapheight;
if(ed.levy >= ed.mapheight)
ed.levy -= ed.mapheight;
}
if(key.keymap[SDLK_SPACE])
{
ed.spacemod = !ed.spacemod;
ed.keydelay = 6;
}
if(key.keymap[SDLK_LSHIFT] || key.keymap[SDLK_RSHIFT])
{
if(!ed.shiftkey)
{
if(ed.shiftmenu)
{
ed.shiftmenu = false;
}
else
{
ed.shiftmenu = true;
}
}
ed.shiftkey = true;
}
else
{
ed.shiftkey = false;
}
}
}
if(!ed.settingsmod)
{
if(ed.boundarymod > 0)
{
if(key.leftbutton)
{
if(ed.lclickdelay == 0)
{
if(ed.boundarymod == 1)
{
ed.lclickdelay = 1;
ed.boundx1 = (ed.tilex * 8);
ed.boundy1 = (ed.tiley * 8);
ed.boundarymod = 2;
}
else if(ed.boundarymod == 2)
{
if((ed.tilex * 8) + 8 >= ed.boundx1 || (ed.tiley * 8) + 8 >= ed.boundy1)
{
ed.boundx2 = (ed.tilex * 8) + 8;
ed.boundy2 = (ed.tiley * 8) + 8;
}
else
{
ed.boundx2 = ed.boundx1 + 8;
ed.boundy2 = ed.boundy1 + 8;
}
if(ed.boundarytype == 0)
{
//Script trigger
ed.scripttextmod = true;
ed.scripttextent = EditorData::GetInstance().numedentities;
addedentity((ed.boundx1 / 8) + (ed.levx * 40),
(ed.boundy1 / 8) + (ed.levy * 30),
19,
(ed.boundx2 - ed.boundx1) / 8,
(ed.boundy2 - ed.boundy1) / 8);
ed.lclickdelay = 1;
ed.textentry = true;
key.enabletextentry();
key.keybuffer = "";
ed.lclickdelay = 1;
}
else if(ed.boundarytype == 1)
{
//Enemy bounds
int tmp = ed.levx + (ed.levy * ed.maxwidth);
ed.level[tmp].enemyx1 = ed.boundx1;
ed.level[tmp].enemyy1 = ed.boundy1;
ed.level[tmp].enemyx2 = ed.boundx2;
ed.level[tmp].enemyy2 = ed.boundy2;
}
else if(ed.boundarytype == 2)
{
//Platform bounds
int tmp = ed.levx + (ed.levy * ed.maxwidth);
ed.level[tmp].platx1 = ed.boundx1;
ed.level[tmp].platy1 = ed.boundy1;
ed.level[tmp].platx2 = ed.boundx2;
ed.level[tmp].platy2 = ed.boundy2;
}
else if(ed.boundarytype == 3)
{
//Copy
}
ed.boundarymod = 0;
ed.lclickdelay = 1;
}
}
}
else
{
ed.lclickdelay = 0;
}
if(key.rightbutton)
{
ed.boundarymod = 0;
}
}
else if(ed.warpmod)
{
//Placing warp token
if(key.leftbutton)
{
if(ed.lclickdelay == 0)
{
if(ed.free(ed.tilex, ed.tiley) == 0)
{
edentity[ed.warpent].p1 = ed.tilex + (ed.levx * 40);
edentity[ed.warpent].p2 = ed.tiley + (ed.levy * 30);
ed.warpmod = false;
ed.warpent = -1;
ed.lclickdelay = 1;
}
}
}
else
{
ed.lclickdelay = 0;
}
if(key.rightbutton)
{
removeedentity(ed.warpent);
ed.warpmod = false;
ed.warpent = -1;
}
}
else
{
//Mouse input
if(key.leftbutton)
{
if(ed.lclickdelay == 0)
{
//Depending on current mode, place something
if(ed.drawmode == 0)
{
//place tiles
//Are we in direct mode?
if(ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode >= 1)
{
if(ed.xmod)
{
for(int j = -2; j < 3; j++)
{
for(int i = -2; i < 3; i++)
{
ed.placetilelocal(ed.tilex + i, ed.tiley + j, ed.dmtile);
}
}
}
else if(ed.zmod)
{
for(int j = -1; j < 2; j++)
{
for(int i = -1; i < 2; i++)
{
ed.placetilelocal(ed.tilex + i, ed.tiley + j, ed.dmtile);
}
}
}
else
{
ed.placetilelocal(ed.tilex, ed.tiley, ed.dmtile);
}
}
else
{
if(ed.xmod)
{
for(int j = -2; j < 3; j++)
{
for(int i = -2; i < 3; i++)
{
ed.placetilelocal(ed.tilex + i, ed.tiley + j, 80);
}
}
}
else if(ed.zmod)
{
for(int j = -1; j < 2; j++)
{
for(int i = -1; i < 2; i++)
{
ed.placetilelocal(ed.tilex + i, ed.tiley + j, 80);
}
}
}
else
{
ed.placetilelocal(ed.tilex, ed.tiley, 80);
}
}
}
else if(ed.drawmode == 1)
{
//place background tiles
if(ed.xmod)
{
for(int j = -2; j < 3; j++)
{
for(int i = -2; i < 3; i++)
{
ed.placetilelocal(ed.tilex + i, ed.tiley + j, 2);
}
}
}
else if(ed.zmod)
{
for(int j = -1; j < 2; j++)
{
for(int i = -1; i < 2; i++)
{
ed.placetilelocal(ed.tilex + i, ed.tiley + j, 2);
}
}
}
else
{
ed.placetilelocal(ed.tilex, ed.tiley, 2);
}
}
else if(ed.drawmode == 2)
{
//place spikes
ed.placetilelocal(ed.tilex, ed.tiley, 8);
}
int tmp = edentat(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30));
if(tmp == -1)
{
//Room text and script triggers can be placed in walls
if(ed.drawmode == 10)
{
ed.roomtextmod = true;
ed.roomtextent = EditorData::GetInstance().numedentities;
ed.textentry = true;
key.enabletextentry();
key.keybuffer = "";
dwgfx.backgrounddrawn = false;
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 17);
ed.lclickdelay = 1;
}
else if(ed.drawmode == 12) //Script Trigger
{
ed.boundarytype = 0;
ed.boundx1 = ed.tilex * 8;
ed.boundy1 = ed.tiley * 8;
ed.boundarymod = 2;
ed.lclickdelay = 1;
}
}
if(tmp == -1 && ed.free(ed.tilex, ed.tiley) == 0)
{
if(ed.drawmode == 3)
{
if(ed.numtrinkets < 20)
{
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 9);
ed.lclickdelay = 1;
ed.numtrinkets++;
}
else
{
ed.note = "ERROR: Max number of trinkets is 20";
ed.notedelay = 45;
}
}
else if(ed.drawmode == 4)
{
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 10, 1);
ed.lclickdelay = 1;
}
else if(ed.drawmode == 5)
{
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 3);
ed.lclickdelay = 1;
}
else if(ed.drawmode == 6)
{
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 2, 5);
ed.lclickdelay = 1;
}
else if(ed.drawmode == 7)
{
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 2, 0);
ed.lclickdelay = 1;
}
else if(ed.drawmode == 8)
{
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 1, 0);
ed.lclickdelay = 1;
}
else if(ed.drawmode == 9)
{
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 11, 0);
ed.lclickdelay = 1;
}
else if(ed.drawmode == 11)
{
ed.scripttextmod = true;
ed.scripttextent = EditorData::GetInstance().numedentities;
ed.textentry = true;
key.enabletextentry();
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 18, 0);
ed.lclickdelay = 1;
}
else if(ed.drawmode == 13)
{
ed.warpmod = true;
ed.warpent = EditorData::GetInstance().numedentities;
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 13);
ed.lclickdelay = 1;
}
else if(ed.drawmode == 14)
{
//Warp lines
if(ed.level[ed.levx + (ed.maxwidth * ed.levy)].warpdir == 0)
{
if(ed.tilex == 0)
{
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 50, 0);
}
else if(ed.tilex == 39)
{
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 50, 1);
}
else if(ed.tiley == 0)
{
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 50, 2);
}
else if(ed.tiley == 29)
{
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 50, 3);
}
else
{
ed.note = "ERROR: Warp lines must be on edges";
ed.notedelay = 45;
}
}
else
{
ed.note = "ERROR: Cannot have both warp types";
ed.notedelay = 45;
}
ed.lclickdelay = 1;
}
else if(ed.drawmode == 15) //Crewmate
{
if(ed.numcrewmates < 20)
{
addedentity(ed.tilex + (ed.levx * 40),
ed.tiley + (ed.levy * 30),
15,
1 + int(fRandom() * 5));
ed.lclickdelay = 1;
ed.numcrewmates++;
}
else
{
ed.note = "ERROR: Max number of crewmates is 20";
ed.notedelay = 45;
}
}
else if(ed.drawmode == 16) //Start Point
{
//If there is another start point, destroy it
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
if(edentity[i].t == 16)
{
removeedentity(i);
i--;
}
}
addedentity(ed.tilex + (ed.levx * 40), ed.tiley + (ed.levy * 30), 16, 0);
ed.lclickdelay = 1;
}
}
else if(edentity[tmp].t == 1)
{
edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 4;
ed.lclickdelay = 1;
}
else if(edentity[tmp].t == 2)
{
if(edentity[tmp].p1 >= 5)
{
edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 9;
if(edentity[tmp].p1 < 5)
edentity[tmp].p1 = 5;
}
else
{
edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 4;
}
ed.lclickdelay = 1;
}
else if(edentity[tmp].t == 10)
{
edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 2;
ed.lclickdelay = 1;
}
else if(edentity[tmp].t == 11)
{
edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 2;
ed.lclickdelay = 1;
}
else if(edentity[tmp].t == 15)
{
edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 6;
ed.lclickdelay = 1;
}
else if(edentity[tmp].t == 16)
{
edentity[tmp].p1 = (edentity[tmp].p1 + 1) % 2;
ed.lclickdelay = 1;
}
else if(edentity[tmp].t == 17)
{
ed.roomtextmod = true;
ed.roomtextent = tmp;
ed.textentry = true;
key.enabletextentry();
key.keybuffer = edentity[tmp].scriptname;
ed.lclickdelay = 1;
}
else if(edentity[tmp].t == 18)
{
ed.scripttextmod = true;
ed.scripttextent = tmp;
ed.textentry = true;
key.enabletextentry();
key.keybuffer = edentity[tmp].scriptname;
ed.lclickdelay = 1;
}
}
}
else
{
ed.lclickdelay = 0;
}
if(key.rightbutton)
{
//place tiles
if(ed.xmod)
{
for(int j = -2; j < 3; j++)
{
for(int i = -2; i < 3; i++)
{
ed.placetilelocal(ed.tilex + i, ed.tiley + j, 0);
}
}
}
else if(ed.zmod)
{
for(int j = -1; j < 2; j++)
{
for(int i = -1; i < 2; i++)
{
ed.placetilelocal(ed.tilex + i, ed.tiley + j, 0);
}
}
}
else
{
ed.placetilelocal(ed.tilex, ed.tiley, 0);
}
for(int i = 0; i < EditorData::GetInstance().numedentities; i++)
{
if(edentity[i].x == ed.tilex + (ed.levx * 40) && edentity[i].y == ed.tiley + (ed.levy * 30))
{
if(edentity[i].t == 9)
ed.numtrinkets--;
if(edentity[i].t == 15)
ed.numcrewmates--;
removeedentity(i);
}
}
}
if(key.middlebutton)
{
ed.dmtile = ed.contents[ed.tilex + (ed.levx * 40) + ed.vmult[ed.tiley + (ed.levy * 30)]];
}
}
}
}
if(ed.updatetiles && ed.level[ed.levx + (ed.levy * ed.maxwidth)].directmode == 0)
{
ed.updatetiles = false;
//Correctly set the tiles in the current room
switch(ed.level[ed.levx + (ed.levy * ed.maxwidth)].tileset)
{
case 0: //The Space Station
for(int j = 0; j < 30; j++)
{
for(int i = 0; i < 40; i++)
{
temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)];
if(ed.contents[temp] >= 3 && ed.contents[temp] < 80)
{
//Fix spikes
ed.contents[temp] = ed.spikedir(i, j);
}
else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680)
{
//Fix background
ed.contents[temp] = ed.backedgetile(i, j) + ed.backbase(ed.levx, ed.levy);
}
else if(ed.contents[temp] > 0)
{
//Fix tiles
ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy);
}
}
}
break;
case 1: //Outside
for(int j = 0; j < 30; j++)
{
for(int i = 0; i < 40; i++)
{
temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)];
if(ed.contents[temp] >= 3 && ed.contents[temp] < 80)
{
//Fix spikes
ed.contents[temp] = ed.spikedir(i, j);
}
else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680)
{
//Fix background
ed.contents[temp] = ed.outsideedgetile(i, j) + ed.backbase(ed.levx, ed.levy);
}
else if(ed.contents[temp] > 0)
{
//Fix tiles
ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy);
}
}
}
break;
case 2: //Lab
for(int j = 0; j < 30; j++)
{
for(int i = 0; i < 40; i++)
{
temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)];
if(ed.contents[temp] >= 3 && ed.contents[temp] < 80)
{
//Fix spikes
ed.contents[temp]
= ed.labspikedir(i, j, ed.level[ed.levx + (ed.maxwidth * ed.levy)].tilecol);
}
else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680)
{
//Fix background
ed.contents[temp] = 713;
}
else if(ed.contents[temp] > 0)
{
//Fix tiles
ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy);
}
}
}
break;
case 3: //Warp Zone/Intermission
for(int j = 0; j < 30; j++)
{
for(int i = 0; i < 40; i++)
{
temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)];
if(ed.contents[temp] >= 3 && ed.contents[temp] < 80)
{
//Fix spikes
ed.contents[temp] = ed.spikedir(i, j);
}
else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680)
{
//Fix background
ed.contents[temp] = 713; //ed.backbase(ed.levx,ed.levy);
}
else if(ed.contents[temp] > 0)
{
//Fix tiles
//ed.contents[temp]=ed.warpzoneedgetile(i,j)+ed.base(ed.levx,ed.levy);
ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy);
}
}
}
break;
case 4: //The ship
for(int j = 0; j < 30; j++)
{
for(int i = 0; i < 40; i++)
{
temp = i + (ed.levx * 40) + ed.vmult[j + (ed.levy * 30)];
if(ed.contents[temp] >= 3 && ed.contents[temp] < 80)
{
//Fix spikes
ed.contents[temp] = ed.spikedir(i, j);
}
else if(ed.contents[temp] == 2 || ed.contents[temp] >= 680)
{
//Fix background
ed.contents[temp] = ed.backedgetile(i, j) + ed.backbase(ed.levx, ed.levy);
}
else if(ed.contents[temp] > 0)
{
//Fix tiles
ed.contents[temp] = ed.edgetile(i, j) + ed.base(ed.levx, ed.levy);
}
}
}
break;
case 5: //The Tower
break;
case 6: //Custom Set 1
break;
case 7: //Custom Set 2
break;
case 8: //Custom Set 3
break;
case 9: //Custom Set 4
break;
}
}
}
| 23.717841 | 171 | 0.540716 |
TijmenUU
|
652ea7d3b537e73f69adb502881ab69f22a61727
| 490 |
cpp
|
C++
|
EU4toV2/Source/Mappers/FactoryTypes/FactoryTypeInputs.cpp
|
GregB76/EU4toVic2
|
0a8822101a36a16036fdc315e706d113d9231101
|
[
"MIT"
] | 1 |
2020-10-03T16:01:28.000Z
|
2020-10-03T16:01:28.000Z
|
EU4toV2/Source/Mappers/FactoryTypes/FactoryTypeInputs.cpp
|
P4blo7/EU4toVic2
|
3f6d354a1f5e529f3d96b3616fe5109bc23f2972
|
[
"MIT"
] | null | null | null |
EU4toV2/Source/Mappers/FactoryTypes/FactoryTypeInputs.cpp
|
P4blo7/EU4toVic2
|
3f6d354a1f5e529f3d96b3616fe5109bc23f2972
|
[
"MIT"
] | null | null | null |
#include "FactoryTypeInputs.h"
#include "ParserHelpers.h"
mappers::FactoryTypeInputs::FactoryTypeInputs(std::istream& theStream)
{
registerRegex("[a-z_]+", [this](const std::string& inputGood, std::istream& theStream)
{
const commonItems::singleDouble inputValue(theStream);
productionInputValues.insert(std::make_pair(inputGood, inputValue.getDouble()));
});
registerRegex("[a-zA-Z0-9\\_.:]+", commonItems::ignoreItem);
parseStream(theStream);
clearRegisteredKeywords();
}
| 30.625 | 87 | 0.746939 |
GregB76
|
6531c48161494a299204e96901484ac2c847b15e
| 192 |
cpp
|
C++
|
Statistics.cpp
|
1-gcc/Loup
|
ff0d54b4b068e68d39dcd9a4d92ed9fcdb9c6f09
|
[
"MIT"
] | null | null | null |
Statistics.cpp
|
1-gcc/Loup
|
ff0d54b4b068e68d39dcd9a4d92ed9fcdb9c6f09
|
[
"MIT"
] | null | null | null |
Statistics.cpp
|
1-gcc/Loup
|
ff0d54b4b068e68d39dcd9a4d92ed9fcdb9c6f09
|
[
"MIT"
] | null | null | null |
// Statistics.cpp
// (C) Copyright 2017 by Martin Brunn see License.txt for details
//
#include "Statistics.h"
Statistics::Statistics()
{
}
Statistics::~Statistics()
{
}
| 12 | 67 | 0.630208 |
1-gcc
|
6531cee17f6edf825b268b8cdb3818864fc97781
| 321 |
cpp
|
C++
|
delete_free/main.cpp
|
VgTajdd/cpp_playground
|
d13c198952782a96cccdd35504abd8c915128e19
|
[
"MIT"
] | 2 |
2019-12-18T12:20:12.000Z
|
2021-08-02T00:16:17.000Z
|
delete_free/main.cpp
|
VgTajdd/cpp_playground
|
d13c198952782a96cccdd35504abd8c915128e19
|
[
"MIT"
] | null | null | null |
delete_free/main.cpp
|
VgTajdd/cpp_playground
|
d13c198952782a96cccdd35504abd8c915128e19
|
[
"MIT"
] | null | null | null |
// free(): is C method (Is it necessary to use C in your C++ app?)
// delete: is C++ operator
int main()
{
int* a = new int[5];
a[4] = 4;
int* b = a;
//free( a ); // It works but is necessary to include stdlib.h
//free( b );
//delete a[]; // It works.
delete[] b; // It works.
__debugbreak();
return 0;
}
| 16.894737 | 67 | 0.557632 |
VgTajdd
|
6531eff7da7e2206e904fd0577e38bbb47b142e1
| 836 |
hpp
|
C++
|
include/architect/clang.hpp
|
KoltesDigital/architect.cpp
|
97d1225a89887624ad467f602d6f6468410c49ab
|
[
"MIT"
] | 2 |
2018-07-02T01:47:31.000Z
|
2019-12-14T23:53:02.000Z
|
include/architect/clang.hpp
|
Bloutiouf/architect.cpp
|
97d1225a89887624ad467f602d6f6468410c49ab
|
[
"MIT"
] | null | null | null |
include/architect/clang.hpp
|
Bloutiouf/architect.cpp
|
97d1225a89887624ad467f602d6f6468410c49ab
|
[
"MIT"
] | null | null | null |
#pragma once
#ifdef ARCHITECT_CLANG_SUPPORT
#include <functional>
#include <string>
typedef struct CXTranslationUnitImpl *CXTranslationUnit;
namespace architect
{
class Registry;
namespace clang
{
typedef std::function<bool(const std::string &)> Filter;
struct Parameters
{
Filter filter; // returns whether to visit symbols in the file
Parameters();
};
class DirectoryFilter
{
public:
DirectoryFilter(); // working directory
DirectoryFilter(const std::string &path);
bool operator()(const std::string &filename) const;
private:
std::string _path;
};
void parse(Registry ®istry, const CXTranslationUnit translationUnit, Parameters ¶meters = Parameters());
bool parse(Registry ®istry, int argc, const char *const *argv, Parameters ¶meters = Parameters());
}
}
#endif
| 19.44186 | 113 | 0.727273 |
KoltesDigital
|
6532f9844d9f1887eeda5e8bdb0ee88a38a732fb
| 2,609 |
cpp
|
C++
|
src/Popup.cpp
|
LeandreBl/sfml-scene
|
3fb0d1167f1585c0c82775a23b44df46ec7378d5
|
[
"Apache-2.0"
] | 2 |
2020-12-10T20:22:17.000Z
|
2020-12-10T20:23:35.000Z
|
src/Popup.cpp
|
LeandreBl/sfml-scene
|
3fb0d1167f1585c0c82775a23b44df46ec7378d5
|
[
"Apache-2.0"
] | null | null | null |
src/Popup.cpp
|
LeandreBl/sfml-scene
|
3fb0d1167f1585c0c82775a23b44df46ec7378d5
|
[
"Apache-2.0"
] | null | null | null |
#include "Popup.hpp"
#include "Colors.hpp"
namespace sfs {
Popup::Popup(Scene &scene, const sf::Font &font, const sf::Vector2f &position) noexcept
: UI(scene, "Popup", position)
, _box(addComponent<Rectangle>())
, _text(addComponent<Text>(font, "", sf::Color::Black))
, _queue()
, _elapsed(0.f)
{
}
void Popup::updateString() noexcept
{
_text.setString(_queue.front().first);
auto rect = _text.getLocalBounds();
float gapx = rect.width * 1.5;
float gapy = rect.height * 2;
_box.setSize(sf::Vector2f(gapx, gapy));
_box.setOffset(sf::Vector2f(-rect.width, 0));
auto boxrect = _box.getLocalBounds();
_text.setOffset(sf::Vector2f((boxrect.width - rect.width) / 2 - rect.left,
(boxrect.height - rect.height) / 2 - rect.top)
+ _box.getOffset());
}
sf::Uint8 Popup::getAlpha() const noexcept
{
if (_elapsed <= _queue.front().second / 3) {
return _elapsed * 255 / (_queue.front().second / 3);
}
else if (_elapsed <= _queue.front().second * 2 / 3) {
return 255;
}
return 255 - (_elapsed * 255 / (_queue.front().second / 3));
}
sf::FloatRect Popup::getGlobalBounds() noexcept
{
return _text.getGlobalBounds();
}
void Popup::clean() noexcept
{
auto color = _box.getFillColor();
color.a = 0;
_box.setFillColor(color);
_text.setString("");
_elapsed = 0;
}
void Popup::start() noexcept
{
}
void Popup::update() noexcept
{
if (_queue.size() > 0) {
_elapsed += scene().deltaTime();
if (_elapsed >= _queue.front().second) {
_queue.pop();
_elapsed = 0.f;
if (_queue.size() > 0) {
updateString();
}
else {
Popup::clean();
return;
}
}
auto color = _box.getFillColor();
auto alpha = getAlpha();
color.a = alpha;
_box.setFillColor(color);
color = _text.getFillColor();
color.a = alpha;
_text.setFillColor(color);
}
}
void Popup::onEvent(const sf::Event &) noexcept
{
}
void Popup::onDestroy() noexcept
{
}
void Popup::setTexture(const sf::Texture &texture) noexcept
{
_box.setTexture(&texture);
}
void Popup::setCharacterSize(uint32_t size) noexcept
{
_text.setCharacterSize(size);
}
void Popup::setBoxColor(const sf::Color &color) noexcept
{
_box.setFillColor(color);
}
void Popup::setTextColor(const sf::Color &color) noexcept
{
_text.setFillColor(color);
}
void Popup::push(const sf::String &string, float duration) noexcept
{
_queue.emplace(string, duration);
if (_queue.size() == 1)
updateString();
}
void Popup::clear() noexcept
{
pop(_queue.size());
}
void Popup::pop(size_t n) noexcept
{
while (_queue.size() > 0 && n > 0)
_queue.pop();
if (_queue.size() == 0)
Popup::clean();
}
} // namespace sfs
| 19.765152 | 87 | 0.661173 |
LeandreBl
|
6533f5f298c27ffe512cd2e2f97d372d32e08f23
| 1,240 |
cpp
|
C++
|
src/Preprocessor.cpp
|
m87/backpack-tracker
|
090978d24a60d9490c09f1a8d892a21d7f4f3126
|
[
"Apache-2.0"
] | null | null | null |
src/Preprocessor.cpp
|
m87/backpack-tracker
|
090978d24a60d9490c09f1a8d892a21d7f4f3126
|
[
"Apache-2.0"
] | null | null | null |
src/Preprocessor.cpp
|
m87/backpack-tracker
|
090978d24a60d9490c09f1a8d892a21d7f4f3126
|
[
"Apache-2.0"
] | null | null | null |
#include "Preprocessor.h"
Preprocessor::Preprocessor(std::string file) : _cap(new cv::VideoCapture(file)) {
MEMORY("Preprocessor created");
if(!_cap->isOpened())
throw GenericException(GenericException::CAP_NOT_OPENED);
}
Preprocessor::~Preprocessor() {
MEMORY("Preprocessor deleted");
}
bool Preprocessor::getFrame(cv::Mat &out,cv::Mat &out_real,float w , float h, bool gray) {
cv::Mat tmp;
*_cap >> tmp;
if(tmp.rows ==0) return false;
tmp.copyTo(out_real);
if(h>0) {
resize(tmp,out,cv::Size(w,h));
} else {
resize(tmp,out,cv::Size(w,w/(float)tmp.cols*tmp.rows));
}
if(gray) {
cvtColor(out,out,CV_RGB2GRAY);
}
display(ConfigManager::VIEW_FRAME_REAL, out_real);
display(ConfigManager::VIEW_FRAME_RESIZED, out);
VERBOSE_O("Preprocesso:: resized frame reuqest");
return true;
}
bool Preprocessor::getFrame(cv::Mat &out,float w , float h, bool gray) {
cv::Mat tmp;
*_cap >> tmp;
if(tmp.rows ==0) return false;
if(h>0) {
resize(tmp,out,cv::Size(w,h));
} else {
resize(tmp,out,cv::Size(w,w/(float)tmp.cols*tmp.rows));
}
if(gray) {
cvtColor(out,out,CV_RGB2GRAY);
}
return true;
}
| 23.846154 | 90 | 0.617742 |
m87
|
6538aefc1735917cb09946b87626359048bf4a17
| 571 |
cpp
|
C++
|
memory/builtins/functions/internalFunctions/Print.cpp
|
Savioor/NotPython
|
512d5feba6d6efb960d38adc98d2bd5ec7d3db3b
|
[
"Apache-2.0"
] | 2 |
2019-11-17T22:38:23.000Z
|
2020-05-28T09:28:26.000Z
|
memory/builtins/functions/internalFunctions/Print.cpp
|
Savioor/NotPython
|
512d5feba6d6efb960d38adc98d2bd5ec7d3db3b
|
[
"Apache-2.0"
] | null | null | null |
memory/builtins/functions/internalFunctions/Print.cpp
|
Savioor/NotPython
|
512d5feba6d6efb960d38adc98d2bd5ec7d3db3b
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by USER on 6/1/2020.
//
#include <iostream>
#include "Print.h"
#include "../../PyVariable.h"
#include "../../primitive/PyString.h"
#include "../../../MemoryManager.h"
PyClass *Print::process(std::map<std::string, PyClass *> &map) {
const PyString* asStr = map["data"]->asString();
if (asStr == nullptr) {
std::cout << map["data"] << std::endl;
} else {
std::cout << asStr->getValue() << std::endl;
}
return MemoryManager::getManager().getNone();
}
Print::Print() : PyInternalFunction(new PyVariable("data", false)) {}
| 25.954545 | 69 | 0.598949 |
Savioor
|
6539554ea836c0fd3caecb6811692e2324946b42
| 10,355 |
cpp
|
C++
|
src/MinConsoleNative/CellRenderer.cpp
|
OpenGreatDream/Console
|
205a6802c6d12d322fa66c91fa7baa3e38e8d6c1
|
[
"MIT"
] | 5 |
2021-04-11T17:32:45.000Z
|
2021-09-16T18:27:58.000Z
|
src/MinConsoleNative/CellRenderer.cpp
|
OpenGreatDream/MinConsole
|
4adc9e5574c77985488d22528ee318a1f62649b0
|
[
"MIT"
] | 4 |
2021-05-01T10:22:14.000Z
|
2021-05-05T11:20:34.000Z
|
src/MinConsoleNative/CellRenderer.cpp
|
OpenGreatDream/Console
|
205a6802c6d12d322fa66c91fa7baa3e38e8d6c1
|
[
"MIT"
] | null | null | null |
#include "CellRenderer.hpp"
#include "String.hpp"
#include "TextLayout.hpp"
#include "VTConverter.hpp"
#include <string>
using namespace std;
namespace MinConsoleNative
{
CellRenderer::CellRenderer(int consoleWidth, int consoleHeight, CellRendererMode mode)
{
this->consoleWidth = consoleWidth;
this->consoleHeight = consoleHeight;
this->mode = mode;
this->cellArray = new Cell[consoleWidth * consoleHeight];
this->cellArrayBuffer = new Cell[consoleWidth * consoleHeight];
if (mode == CellRendererMode::Fast)
{
this->charInfos = new CHAR_INFO[consoleWidth * consoleHeight];
}
else
{
this->charInfos = nullptr;
}
}
CellRenderer::~CellRenderer()
{
delete[] this->cellArray;
delete[] this->cellArrayBuffer;
if (mode == CellRendererMode::Fast)
{
delete[] this->charInfos;
}
}
void CellRenderer::Clear(const Cell& cell)
{
for (int i = 0; i < consoleWidth * consoleHeight; i++)
{
this->cellArrayBuffer[i] = this->cellArray[i]; //copy
this->cellArray[i] = cell; //set default
}
}
void CellRenderer::Render()
{
if (mode == CellRendererMode::Fast) RenderFast();
else if (mode == CellRendererMode::TrueColor) RenderTrueColor();
else if (mode == CellRendererMode::Mixed) RenderMixed();
else if (mode == CellRendererMode::FastTrueColor) RenderFastTrueColor();
}
void CellRenderer::Draw(const Vector2& pos, const Cell& cell)
{
if (pos.x < 0 || pos.x > consoleWidth - 1 ||
pos.y < 0 || pos.y > consoleHeight - 1) return;
int index = consoleWidth * pos.y + pos.x;
this->cellArray[index] = cell;
}
void CellRenderer::DrawString(const Vector2& pos, const std::wstring& wstr, Color24 foreColor, Color24 backColor, bool underScore)
{
for (int i = 0; i < wstr.size(); i++)
{
CellRenderer::Draw(Vector2(pos.x + i, pos.y), Cell(wstr[i], foreColor, backColor, underScore));
}
}
int CellRenderer::DrawString2(const Vector2& pos, const std::wstring& wstr, Color24 foreColor, Color24 backColor, bool underScore)
{
vector<wstring> grids = textLayout.WstringToGrids(wstr);
for (int i = 0; i < grids.size(); i++)
{
const wstring& gridStr = grids[i];
if (gridStr.size() == 1)
{
CellRenderer::Draw(Vector2(pos.x + i * 2, pos.y), Cell(gridStr[0], foreColor, backColor, underScore, true));
CellRenderer::Draw(Vector2(pos.x + i * 2 + 1, pos.y), Cell(L' ', foreColor, backColor, underScore, false));
}
else if (gridStr.size() == 2)
{
CellRenderer::Draw(Vector2(pos.x + i * 2, pos.y), Cell(gridStr[0], foreColor, backColor, underScore));
CellRenderer::Draw(Vector2(pos.x + i * 2 + 1, pos.y), Cell(gridStr[1], foreColor, backColor, underScore));
}
}
return grids.size();
}
void CellRenderer::DrawStringWrap(const Vector2& pos, const std::wstring& wstr, Color24 foreColor, Color24 backColor, bool underScore)
{
for (int i = 0; i < wstr.size(); i++)
{
int positionX = pos.x + i;
int positionY = pos.y;
while (positionX > consoleWidth - 1)
{
positionX -= consoleWidth;
positionY++;
}
CellRenderer::Draw(Vector2(positionX, positionY), Cell(wstr[i], foreColor, backColor, underScore));
}
}
int CellRenderer::DrawString2Wrap(const Vector2& pos, const std::wstring& wstr, Color24 foreColor, Color24 backColor, bool underScore)
{
vector<wstring> grids = textLayout.WstringToGrids(wstr);
for (int i = 0; i < grids.size(); i++)
{
int positionX = pos.x + i * 2;
int positionY = pos.y;
while (positionX > consoleWidth - 1)
{
positionX -= consoleWidth;
positionY++;
}
const wstring& gridStr = grids[i];
if (gridStr.size() == 1)
{
CellRenderer::Draw(Vector2(positionX, positionY), Cell(gridStr[0], foreColor, backColor, underScore, true));
CellRenderer::Draw(Vector2(positionX + 1, positionY), Cell(L' ', foreColor, backColor, underScore, false));
}
else if (gridStr.size() == 2)
{
CellRenderer::Draw(Vector2(positionX, positionY), Cell(gridStr[0], foreColor, backColor, underScore));
CellRenderer::Draw(Vector2(positionX + 1, positionY), Cell(gridStr[1], foreColor, backColor, underScore));
}
}
return grids.size();
}
void CellRenderer::DrawBorderBox(const Vector2& pos, const Vector2& size, const Vector2& borderSize, const Cell& cell, const Cell& borderCell)
{
for (int i = 0; i < size.y; i++)
{
for (int j = 0; j < size.x; j++)
{
if (i >= 0 && i < borderSize.y || j >= 0 && j < borderSize.x ||
i <= size.y - 1 && i > size.y - 1 - borderSize.y ||
j <= size.x - 1 && j > size.x - 1 - borderSize.x)
{
CellRenderer::Draw(Vector2(pos.x + j, pos.y + i), borderCell);
}
else
{
CellRenderer::Draw(Vector2(pos.x + j, pos.y + i), cell);
}
}
}
}
void CellRenderer::DrawBorderBox2(const Vector2& pos, const Vector2& size, const Vector2& borderSize, const std::wstring& cellWstr, Color24 cellForeColor, Color24 cellBackColor, bool cellUnderScore, const std::wstring& borderWstr, Color24 borderForeColor, Color24 borderBackColor, bool borderUnderScore)
{
for (int i = 0; i < size.y; i++)
{
for (int j = 0; j < size.x; j++)
{
if (i >= 0 && i < borderSize.y || j >= 0 && j < borderSize.x ||
i <= size.y - 1 && i > size.y - 1 - borderSize.y ||
j <= size.x - 1 && j > size.x - 1 - borderSize.x)
{
CellRenderer::DrawString2(Vector2(pos.x + j * 2, pos.y + i), borderWstr, borderForeColor, borderBackColor, borderUnderScore);
}
else
{
CellRenderer::DrawString2(Vector2(pos.x + j * 2, pos.y + i), cellWstr, cellForeColor, cellBackColor, cellUnderScore);
}
}
}
}
void CellRenderer::RenderFast()
{
bool findLeadingByte = false;
for (int i = 0; i < consoleWidth * consoleHeight; i++)
{
const Cell& cell = this->cellArray[i];
ushort att = 0;
att |= MinConsoleColorToUshort(cell.foreColor.ToConsoleColor(), cell.backColor.ToConsoleColor());
if (cell.underScore) att |= COMMON_LVB_UNDERSCORE;
if (cell.isLeadingByte)
{
att |= COMMON_LVB_LEADING_BYTE;
findLeadingByte = true;
}
else if (findLeadingByte)
{
att |= COMMON_LVB_TRAILING_BYTE;
findLeadingByte = false;
}
charInfos[i].Attributes = att;
charInfos[i].Char.UnicodeChar = cell.c;
}
console.WriteConsoleOutputW(charInfos, 0, 0, consoleWidth, consoleHeight);
}
void CellRenderer::RenderMixed()
{
//draw true color:
for (int i = 0; i < consoleWidth * consoleHeight; i++)
{
const Cell& cell = this->cellArray[i];
const Cell& cellBuffer = this->cellArrayBuffer[i];
if (cell != cellBuffer)
{
COORD position = { i % consoleWidth, i / consoleWidth };
COORD beforePosition = console.GetConsoleCursorPos();
console.SetConsoleCursorPos(position);
console.Write(String::WcharToWstring(L' '), cell.foreColor, cell.backColor, cell.underScore);
console.SetConsoleCursorPos(beforePosition);
}
}
//draw string:
wstring* lines = new wstring[consoleHeight];
for (int i = 0; i < consoleWidth * consoleHeight; i++)
{
lines[i / consoleWidth] += this->cellArray[i].c;
const Cell& cell = this->cellArray[i];
if (cell.isLeadingByte)
{
i++;
}
}
for (int i = 0; i < consoleHeight; i++)
{
console.WriteConsoleOutputCharacterW(lines[i], { 0, (short)i });
}
delete[] lines;
}
void CellRenderer::RenderTrueColor()
{
for (int i = 0; i < consoleWidth * consoleHeight; i++)
{
const Cell& cell = this->cellArray[i];
const Cell& cellBuffer = this->cellArrayBuffer[i];
if (cell != cellBuffer)
{
COORD position = { i % consoleWidth, i / consoleWidth };
COORD beforePosition = console.GetConsoleCursorPos();
console.SetConsoleCursorPos(position);
console.Write(String::WcharToWstring(cell.c), cell.foreColor, cell.backColor, cell.underScore);
console.SetConsoleCursorPos(beforePosition);
}
}
}
void CellRenderer::RenderFastTrueColor()
{
wstring wstr;
for (int i = 0; i < consoleWidth * consoleHeight; i++)
{
const Cell& cell = this->cellArray[i];
wstr += cell.c;
//wstring foreColor = L"\033[38;2;255;0;255m";
//wstr += foreColor + cell.c;
//wstring fore_str = VTConverter::VTForeColor(cell.foreColor);
//wstring back_str = VTConverter::VTBackColor(cell.backColor);
//wstring us_str = VTConverter::VTUnderline(cell.underScore);
//wstring reset_str = VTConverter::VTResetStyle();
//wstr += (fore_str + back_str + us_str + cell.c + reset_str);
}
//console.Write(wstr, { 233,21,22 });
console.Write(wstr);
}
}
| 38.210332 | 307 | 0.538098 |
OpenGreatDream
|
653b53055a56822d2126e130ad93f87441fe3d70
| 817 |
cpp
|
C++
|
I8086CL/I8086CL.cpp
|
koutheir/i8086sim
|
c47fe1ad1cfe8121a7cd6c66f673097c283d2af6
|
[
"BSD-3-Clause"
] | 3 |
2018-08-25T00:03:42.000Z
|
2020-01-06T12:37:04.000Z
|
I8086CL/I8086CL.cpp
|
koutheir/i8086sim
|
c47fe1ad1cfe8121a7cd6c66f673097c283d2af6
|
[
"BSD-3-Clause"
] | null | null | null |
I8086CL/I8086CL.cpp
|
koutheir/i8086sim
|
c47fe1ad1cfe8121a7cd6c66f673097c283d2af6
|
[
"BSD-3-Clause"
] | null | null | null |
#include <windows.h>
BOOL APIENTRY wWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
int argc;
wchar_t **argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argc < 4) return ERROR_INVALID_PARAMETER;
DWORD nErr=ERROR_SUCCESS, nParentID = (DWORD)_wtol(argv[1]);
HANDLE hList[2] = {
OpenProcess(SYNCHRONIZE, FALSE, nParentID),
(HANDLE)_wtol(argv[3])
};
if (!hList[0]) return GetLastError();
if (!AttachConsole(nParentID)) { //Attach to the parent console
nErr = GetLastError();
goto Done;
}
if (!SetEvent((HANDLE)_wtol(argv[2]))) { //Allow the parent to continue execution
nErr = GetLastError();
goto Done;
}
if (WaitForMultipleObjects(2, hList, FALSE, INFINITE) == WAIT_FAILED)
nErr = GetLastError();
Done:
CloseHandle(hList[0]);
return nErr;
}
| 22.694444 | 84 | 0.667075 |
koutheir
|
653ba5cc16c9453cb55af179bff0c153d989a2c8
| 24,644 |
cxx
|
C++
|
src/runtime_src/tools/xclbinutil/SectionAIEPartition.cxx
|
bryanloz-xilinx/XRT
|
8de6bc04f7060c8272cbb7857531335f1aa31099
|
[
"Apache-2.0"
] | null | null | null |
src/runtime_src/tools/xclbinutil/SectionAIEPartition.cxx
|
bryanloz-xilinx/XRT
|
8de6bc04f7060c8272cbb7857531335f1aa31099
|
[
"Apache-2.0"
] | null | null | null |
src/runtime_src/tools/xclbinutil/SectionAIEPartition.cxx
|
bryanloz-xilinx/XRT
|
8de6bc04f7060c8272cbb7857531335f1aa31099
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright (C) 2022 Advanced Micro Devices, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located 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 "SectionAIEPartition.h"
#include "XclBinUtilities.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/functional/factory.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
namespace XUtil = XclBinUtilities;
// -------------------------------------------------------------------------
// Static Variables / Classes
SectionAIEPartition::init SectionAIEPartition::initializer;
SectionAIEPartition::init::init()
{
auto sectionInfo = std::make_unique<SectionInfo>(AIE_PARTITION, "AIE_PARTITION", boost::factory<SectionAIEPartition*>());
sectionInfo->nodeName = "aie_partition";
sectionInfo->supportsSubSections = true;
sectionInfo->supportsIndexing = true;
// There is only one-subsection that is supported. By default it is not named.
sectionInfo->subSections.push_back("");
sectionInfo->supportedAddFormats.push_back(FormatType::json);
sectionInfo->supportedDumpFormats.push_back(FormatType::json);
addSectionType(std::move(sectionInfo));
}
// -------------------------------------------------------------------------
class SectionHeap {
public:
SectionHeap() = delete;
SectionHeap(uint64_t heapSectionOffset)
{
if (XUtil::bytesToAlign(heapSectionOffset) != 0)
throw std::runtime_error("Error: HeapSectionOffset is not aligned to 8 bytes");
m_heapSectionOffset = heapSectionOffset;
}
void write(const char* pBuffer, size_t size, bool align = true)
{
if ((pBuffer != nullptr) && size)
m_heapBuffer.write(pBuffer, size);
if (align)
XUtil::alignBytes(m_heapBuffer, 8);
}
uint64_t getNextBufferOffset()
{
// Get the current size
m_heapBuffer.seekp(0, std::ios_base::end);
uint64_t bufSize = (uint64_t)m_heapBuffer.tellp();
// And add it to the buffer offset.
return bufSize + m_heapSectionOffset;
}
void writeHeapToStream(std::ostringstream& osStream)
{
const auto& sHeap = m_heapBuffer.str();
osStream.write(sHeap.c_str(), sHeap.size());
}
protected:
uint64_t m_heapSectionOffset;
std::ostringstream m_heapBuffer;
};
// ----------------------------------------------------------------------------
bool
SectionAIEPartition::subSectionExists(const std::string& /*sSubSectionName*/) const
{
// No buffer no subsections
return (m_pBuffer != nullptr);
}
// -------------------------------------------------------------------------
static const std::vector<std::pair<std::string, CDO_Type>> CTTypes = {
{ "UNKNOWN", CT_UNKNOWN },
{ "PRIMARY", CT_PRIMARY },
{ "LITE", CT_LITE }
};
static const std::string&
getCDOTypeStr(CDO_Type eCDOType)
{
auto iter = std::find_if(CTTypes.begin(), CTTypes.end(), [&](const auto& entry) {return entry.second == eCDOType;});
if (iter == CTTypes.end())
return getCDOTypeStr(CT_UNKNOWN);
return iter->first;
}
static CDO_Type
getCDOTypesEnum(const std::string& sTypeName)
{
auto iter = std::find_if(CTTypes.begin(), CTTypes.end(), [&](const auto& entry) {return boost::iequals(entry.first, sTypeName);});
if (iter == CTTypes.end())
return CT_UNKNOWN;
return iter->second;
}
// -------------------------------------------------------------------------
static void
process_PDI_uuid(const boost::property_tree::ptree& ptPDI,
aie_pdi& aieParitionPDI)
{
XUtil::TRACE("Processing PDI UUID");
auto uuid = ptPDI.get<std::string>("uuid", "");
if (uuid.empty())
throw std::runtime_error("Error: The PDI element is missing the 'uuid' node.");
// Clean up the UUID
boost::replace_all(uuid, "0x", ""); // Remove all "0x"
boost::replace_all(uuid, "-", ""); // Remove all minus signs
if (uuid.size() < (2 * sizeof(aie_pdi::uuid))) // Add leading zeros
uuid.insert(0, (2 * sizeof(aie_pdi::uuid) - uuid.size()), '0');
if (uuid.size() > (2 * sizeof(aie_pdi::uuid)))
throw std::runtime_error("Error: The UUID node value is larger then the storage size for this value.");
// Write out the value
XUtil::hexStringToBinaryBuffer(uuid, reinterpret_cast<unsigned char*>(aieParitionPDI.uuid), sizeof(aie_pdi::uuid));
}
// -------------------------------------------------------------------------
static void
read_file_into_buffer(const std::string& fileName,
const boost::filesystem::path& fromRelativeDir,
std::vector<char>& buffer)
{
// Build the path to our file of interest
boost::filesystem::path filePath = fileName;
if (filePath.is_relative()) {
filePath = fromRelativeDir;
filePath /= fileName;
}
XUtil::TRACE(boost::format("Reading in the file: '%s'") % filePath.string());
// Open the file
std::ifstream file(filePath.string(), std::ifstream::in | std::ifstream::binary);
if (!file.is_open())
throw std::runtime_error("ERROR: Unable to open the file for reading: " + fileName);
// Get the file size
file.seekg(0, file.end);
std::streamsize fileSize = file.tellg();
file.seekg(0, file.beg);
// Resize the buffer and read in the array
buffer.resize(fileSize);
file.read(buffer.data(), fileSize);
// Make sure that the entire buffer was read
if (file.gcount() != fileSize)
throw std::runtime_error("ERROR: Input stream for the binary buffer is smaller then the expected size.");
}
// -------------------------------------------------------------------------
static void
process_PDI_file(const boost::property_tree::ptree& ptAIEPartitionPDI,
const boost::filesystem::path& relativeFromDir,
aie_pdi& aiePartitionPDI,
SectionHeap& heap)
{
XUtil::TRACE("Processing PDI Files");
const auto& fileName = ptAIEPartitionPDI.get<std::string>("file_name", "");
if (fileName.empty())
throw std::runtime_error("Error: Missing PDI file name node.");
// Read file image from disk
std::vector<char> buffer;
read_file_into_buffer(fileName, relativeFromDir, buffer);
// Store file image in the heap
aiePartitionPDI.pdi_image.size = static_cast<decltype(aiePartitionPDI.pdi_image.size)>(buffer.size());
aiePartitionPDI.pdi_image.offset = static_cast<decltype(aiePartitionPDI.pdi_image.offset)>(heap.getNextBufferOffset());
heap.write(reinterpret_cast<const char*>(buffer.data()), buffer.size());
}
// -------------------------------------------------------------------------
static void
process_pre_cdo_groups(const boost::property_tree::ptree& ptAIECDOGroup,
cdo_group& aieCDOGroup,
SectionHeap& heap)
{
XUtil::TRACE("Processing Pre CDO Groups");
std::vector<std::string> preCDOGroups = XUtil::as_vector_simple<std::string>(ptAIECDOGroup, "pre_cdo_groups");
aieCDOGroup.pre_cdo_groups.size = static_cast<decltype(aieCDOGroup.pre_cdo_groups.size)>(preCDOGroups.size());
// It is O.K. not to have any CDO groups
if (aieCDOGroup.pre_cdo_groups.size == 0)
return;
// Record where the CDO group array starts.
aieCDOGroup.pre_cdo_groups.offset = static_cast<decltype(aieCDOGroup.pre_cdo_groups.offset)>(heap.getNextBufferOffset());
// Write out the CDO value to the heap.
for (const auto& element : preCDOGroups) {
uint64_t preGroupID = std::strtoul(element.c_str(), NULL, 0);
heap.write(reinterpret_cast<const char*>(&preGroupID), sizeof(decltype(preGroupID)), false /*align*/);
}
// Align the heap to the next 64-bit word.
heap.write(nullptr, 0);
}
// -------------------------------------------------------------------------
static void
process_PDI_cdo_groups(const boost::property_tree::ptree& ptAIEPartitionPDI,
aie_pdi& aiePDI,
SectionHeap& heap)
{
XUtil::TRACE("Processing CDO Groups");
std::vector<boost::property_tree::ptree> ptCDOs = XUtil::as_vector<boost::property_tree::ptree>(ptAIEPartitionPDI, "cdo_groups");
aiePDI.cdo_groups.size = static_cast<decltype(aiePDI.cdo_groups.size)>(ptCDOs.size());
if (aiePDI.cdo_groups.size == 0)
throw std::runtime_error("Error: There are no cdo groups in the PDI node AIE Partition section.");
// Examine each of the CDO groups
std::vector<cdo_group> vCDOs;
for (const auto& element : ptCDOs) {
cdo_group aieCDOGroup = { };
// Name
auto name = element.get<std::string>("name", "");
aieCDOGroup.mpo_name = static_cast<decltype(aieCDOGroup.mpo_name)>(heap.getNextBufferOffset());
heap.write(reinterpret_cast<const char*>(name.c_str()), name.size() + 1 /*Null CharL*/);
// Type
aieCDOGroup.cdo_type = static_cast<decltype(aieCDOGroup.cdo_type)>(getCDOTypesEnum(element.get<std::string>("type", "")));
// PDI ID
auto sPDIValue = element.get<std::string>("pdi_id", "");
if (sPDIValue.empty())
throw std::runtime_error("Error: PDI ID node value not found");
aieCDOGroup.pdi_id = std::strtoul(sPDIValue.c_str(), NULL, 0);
// DPU Function ID (optional)
auto sDPUValue = element.get<std::string>("dpu_kernel_id", "");
if (!sDPUValue.empty())
aieCDOGroup.dpu_kernel_id = std::strtoul(sDPUValue.c_str(), NULL, 0);
// PRE CDO Groups (optional)
process_pre_cdo_groups(element, aieCDOGroup, heap);
// Finished processing the element. Save it away.
vCDOs.push_back(aieCDOGroup);
}
// Write out the CDO group array. Note: The CDO group element is 64-bit aligned.
aiePDI.cdo_groups.offset = static_cast<decltype(aiePDI.cdo_groups.offset)>(heap.getNextBufferOffset());
for (const auto& element : vCDOs)
heap.write(reinterpret_cast<const char*>(&element), sizeof(cdo_group));
}
// -------------------------------------------------------------------------
static void
process_PDIs(const boost::property_tree::ptree& ptAIEPartition,
const boost::filesystem::path& relativeFromDir,
aie_partition& aiePartitionHdr,
SectionHeap& heap)
{
XUtil::TRACE("Processing PDIs");
std::vector<boost::property_tree::ptree> ptPDIs = XUtil::as_vector<boost::property_tree::ptree>(ptAIEPartition, "PDIs");
aiePartitionHdr.aie_pdi.size = static_cast<decltype(aiePartitionHdr.aie_pdi.size)>(ptPDIs.size());
if (aiePartitionHdr.aie_pdi.size == 0)
throw std::runtime_error("Error: There are no PDI nodes in the AIE Partition section.");
// Examine each of the PDI entries
std::vector<aie_pdi> vPDIs;
for (const auto& element : ptPDIs) {
aie_pdi aiePartitionPDI = { };
process_PDI_uuid(element, aiePartitionPDI);
process_PDI_file(element, relativeFromDir, aiePartitionPDI, heap);
process_PDI_cdo_groups(element, aiePartitionPDI, heap);
// Finished processing the element. Save it away.
vPDIs.push_back(aiePartitionPDI);
}
// Write out the PDI array. Note: The PDI elements are 64-bit aligned.
aiePartitionHdr.aie_pdi.offset = static_cast<decltype(aiePartitionHdr.aie_pdi.offset)>(heap.getNextBufferOffset());
for (const auto& element : vPDIs)
heap.write(reinterpret_cast<const char*>(&element), sizeof(aie_pdi));
}
// -------------------------------------------------------------------------
static void
process_partition_info(const boost::property_tree::ptree& ptAIEPartition,
aie_partition_info& partitionInfo,
SectionHeap& heap)
{
XUtil::TRACE("Processing partition info");
static const boost::property_tree::ptree ptEmpty;
// Get the information regarding the relocatable partitions
const auto& ptPartition = ptAIEPartition.get_child("partition", ptEmpty);
if (ptPartition.empty())
throw std::runtime_error("Error: The AIE partition is missing the 'partition' node.");
partitionInfo = { };
// Parse the column's width
partitionInfo.column_width = ptPartition.get<uint16_t>("column_width", 0);
if (partitionInfo.column_width == 0)
throw std::runtime_error("Error: Missing AIE partition column width");
// Parse the start columns
std::vector<uint16_t> startColumns = XUtil::as_vector_simple<uint16_t>(ptPartition, "start_columns");
partitionInfo.start_columns.size = static_cast<decltype(partitionInfo.start_columns.size)>(startColumns.size());
if (partitionInfo.start_columns.size == 0)
throw std::runtime_error("Error: Missing start columns for the AIE partition.");
// Write out the 16-bit array.
partitionInfo.start_columns.offset = static_cast<decltype(partitionInfo.start_columns.offset)>(heap.getNextBufferOffset());
for (const auto element : startColumns)
heap.write(reinterpret_cast<const char*>(&element), sizeof(uint16_t), false /*align*/);
// Align the heap to the next 64 bit word
heap.write(nullptr, 0, true /*align*/);
}
// -------------------------------------------------------------------------
static void
createAIEPartitionImage(const std::string& sectionIndexName,
const boost::filesystem::path& relativeFromDir,
std::istream& iStream,
std::ostringstream& osBuffer)
{
errno = 0; // Reset any strtoul errors that might have occurred elsewhere
// Get the boost property tree
iStream.clear();
iStream.seekg(0);
boost::property_tree::ptree pt;
boost::property_tree::read_json(iStream, pt);
XUtil::TRACE_PrintTree("AIE_PARTITION", pt);
const boost::property_tree::ptree& ptAIEPartition = pt.get_child("aie_partition");
aie_partition aie_partitionHdr = { };
// Initialized the start of the section heap
SectionHeap heap(sizeof(aie_partition));
aie_partitionHdr.mpo_name = static_cast<decltype(aie_partitionHdr.mpo_name)>(heap.getNextBufferOffset());
heap.write(sectionIndexName.c_str(), sectionIndexName.size() + 1 /*Null char*/);
// Process the nodes
process_partition_info(ptAIEPartition, aie_partitionHdr.info, heap);
process_PDIs(ptAIEPartition, relativeFromDir, aie_partitionHdr, heap);
// Write out the contents of the section
osBuffer.write(reinterpret_cast<const char*>(&aie_partitionHdr), sizeof(aie_partitionHdr));
heap.writeHeapToStream(osBuffer);
}
// -------------------------------------------------------------------------
void
SectionAIEPartition::readSubPayload(const char* pOrigDataSection,
unsigned int /*origSectionSize*/,
std::istream& iStream,
const std::string& sSubSectionName,
Section::FormatType eFormatType,
std::ostringstream& buffer) const
{
// Only default (e.g. empty) sub sections are supported
if (!sSubSectionName.empty()) {
auto errMsg = boost::format("ERROR: Subsection '%s' not support by section '%s")
% sSubSectionName % getSectionKindAsString();
throw std::runtime_error(boost::str(errMsg));
}
// Some basic DRC checks
if (pOrigDataSection != nullptr) {
std::string errMsg = "ERROR: AIE Partition section already exists.";
throw std::runtime_error(errMsg);
}
if (eFormatType != Section::FormatType::json) {
std::string errMsg = "ERROR: AIE Parition only supports the JSON format.";
throw std::runtime_error(errMsg);
}
// Get the JSON's file parent directory. This is used later to any
// relative PDI images that might need need to be read in.
boost::filesystem::path p(getPathAndName());
const auto relativeFromDir = p.parent_path();
createAIEPartitionImage(getSectionIndexName(), relativeFromDir, iStream, buffer);
}
// -------------------------------------------------------------------------
static void
populate_partition_info(const char* pBase,
const aie_partition_info& aiePartitionInfo,
boost::property_tree::ptree& ptAiePartition)
{
XUtil::TRACE("Populating Partition Info");
boost::property_tree::ptree ptPartitionInfo;
// Column Width
ptPartitionInfo.put("column_width", (boost::format("%d") % aiePartitionInfo.column_width).str());
// Start Columns
boost::property_tree::ptree ptStartColumnArray;
const uint16_t* columnArray = reinterpret_cast<const uint16_t*>(pBase + aiePartitionInfo.start_columns.offset);
for (uint32_t index = 0; index < aiePartitionInfo.start_columns.size; index++) {
boost::property_tree::ptree ptElement;
ptElement.put("", (boost::format("%d") % columnArray[index]).str());
ptStartColumnArray.push_back({ "", ptElement });
}
ptPartitionInfo.add_child("start_columns", ptStartColumnArray);
ptAiePartition.add_child("partition", ptPartitionInfo);
}
// -------------------------------------------------------------------------
static void
populate_pre_cdo_groups(const char* pBase,
const cdo_group& aieCDOGroup,
boost::property_tree::ptree& ptCDOGroup)
{
XUtil::TRACE("Populating PRE CDO groups");
// If there is nothing to process, don't create the entry
if (aieCDOGroup.pre_cdo_groups.size == 0)
return;
boost::property_tree::ptree ptPreCDOGroupArray;
const uint64_t* aiePreCDOGroupArray = reinterpret_cast<const uint64_t*>(pBase + aieCDOGroup.pre_cdo_groups.offset);
for (uint32_t index = 0; index < aieCDOGroup.pre_cdo_groups.size; index++) {
const uint64_t& element = aiePreCDOGroupArray[index];
boost::property_tree::ptree ptElement;
ptElement.put("", (boost::format("0x%x") % element));
ptPreCDOGroupArray.push_back({ "", ptElement });
}
ptCDOGroup.add_child("pre_cdo_groups", ptPreCDOGroupArray);
}
// -------------------------------------------------------------------------
static void
populate_cdo_groups(const char* pBase,
const aie_pdi& aiePDI,
boost::property_tree::ptree& ptAiePDI)
{
XUtil::TRACE("Populating CDO groups");
boost::property_tree::ptree ptCDOGroupArray;
const cdo_group* aieCDOGroupArray = reinterpret_cast<const cdo_group*>(pBase + aiePDI.cdo_groups.offset);
for (uint32_t index = 0; index < aiePDI.cdo_groups.size; index++) {
const cdo_group& element = aieCDOGroupArray[index];
boost::property_tree::ptree ptElement;
// Name
ptElement.put("name", reinterpret_cast<const char*>(pBase + element.mpo_name));
// Type
if ((CDO_Type)element.cdo_type != CT_UNKNOWN)
ptElement.put("type", getCDOTypeStr((CDO_Type)element.cdo_type));
// PDI ID
ptElement.put("pdi_id", (boost::format("0x%x") % element.pdi_id).str());
// Function ID
if (element.dpu_kernel_id)
ptElement.put("dpu_kernel_id", (boost::format("0x%x") % element.dpu_kernel_id).str());
// Pre cdo groups
populate_pre_cdo_groups(pBase, element, ptElement);
// Add the cdo group element to the array
ptCDOGroupArray.push_back({ "", ptElement });
}
ptAiePDI.add_child("cdo_groups", ptCDOGroupArray);
}
// -------------------------------------------------------------------------
static void
write_pdi_image(const char* pBase,
const aie_pdi& aiePDI,
const std::string& fileName,
const boost::filesystem::path& relativeToDir)
{
boost::filesystem::path filePath = relativeToDir;
filePath /= fileName;
XUtil::TRACE(boost::format("Creating PDI Image: %s") % filePath.string());
std::fstream oPDIFile;
oPDIFile.open(filePath.string(), std::ifstream::out | std::ifstream::binary);
if (!oPDIFile.is_open()) {
const auto errMsg = boost::format("ERROR: Unable to open the file for writing: %s") % filePath.string();
throw std::runtime_error(errMsg.str());
}
oPDIFile.write(reinterpret_cast<const char*>(pBase + aiePDI.pdi_image.offset), aiePDI.pdi_image.size);
}
// -------------------------------------------------------------------------
static void
populate_PDIs(const char* pBase,
const boost::filesystem::path& relativeToDir,
const aie_partition& aiePartition,
boost::property_tree::ptree& ptAiePartition)
{
XUtil::TRACE("Populating DPI Array");
boost::property_tree::ptree ptPDIArray;
const aie_pdi* aiePdiArray = reinterpret_cast<const aie_pdi*>(pBase + aiePartition.aie_pdi.offset);
for (uint32_t index = 0; index < aiePartition.aie_pdi.size; index++) {
const aie_pdi& element = aiePdiArray[index];
boost::property_tree::ptree ptElement;
// UUID
ptElement.put("uuid", XUtil::getUUIDAsString(element.uuid));
// Partition Image
std::string fileName = XUtil::getUUIDAsString(element.uuid) + ".pdi";
write_pdi_image(pBase, element, fileName, relativeToDir);
ptElement.put("file_name", fileName);
// CDO Groups
populate_cdo_groups(pBase, element, ptElement);
// Add the PDI element to the array
ptPDIArray.push_back({ "", ptElement });
}
ptAiePartition.add_child("PDIs", ptPDIArray);
}
// -------------------------------------------------------------------------
static void
writeAIEPartitionImage(const char* pBuffer,
unsigned int bufferSize,
const boost::filesystem::path& relativeToDir,
std::ostream& oStream)
{
XUtil::TRACE("AIE_PARTITION : Creating JSON IMAGE");
// Do we have enough room to overlay the header structure
if (bufferSize < sizeof(aie_partition)) {
auto errMsg = boost::format("ERROR: Segment size (%d) is smaller than the size of the aie_partition structure (%d)") % bufferSize % sizeof(aie_partition);
throw std::runtime_error(boost::str(errMsg));
}
auto pHdr = reinterpret_cast<const aie_partition*>(pBuffer);
// Name
boost::property_tree::ptree ptAiePartition;
ptAiePartition.put("name", pBuffer + pHdr->mpo_name);
// Partition info
populate_partition_info(pBuffer, pHdr->info, ptAiePartition);
// PDIs
populate_PDIs(pBuffer, relativeToDir, *pHdr, ptAiePartition);
// Write out the built property tree
boost::property_tree::ptree ptRoot;
ptRoot.put_child("aie_partition", ptAiePartition);
XUtil::TRACE_PrintTree("root", ptRoot);
boost::property_tree::write_json(oStream, ptRoot);
}
// -------------------------------------------------------------------------
void
SectionAIEPartition::writeSubPayload(const std::string& sSubSectionName,
FormatType eFormatType,
std::fstream& oStream) const
{
// Some basic DRC checks
if (m_pBuffer == nullptr) {
std::string errMsg = "ERROR: Vendor Metadata section does not exist.";
throw std::runtime_error(errMsg);
}
if (!sSubSectionName.empty()) {
auto errMsg = boost::format("ERROR: Subsection '%s' not support by section '%s")
% sSubSectionName % getSectionKindAsString();
throw std::runtime_error(boost::str(errMsg));
}
// Some basic DRC checks
if (eFormatType != Section::FormatType::json) {
std::string errMsg = "ERROR: AIE Partition section only supports the JSON format.";
throw std::runtime_error(errMsg);
}
boost::filesystem::path p(getPathAndName());
const auto relativeToDir = p.parent_path();
writeAIEPartitionImage(m_pBuffer, m_bufferSize, relativeToDir, oStream);
}
// -------------------------------------------------------------------------
void
SectionAIEPartition::readXclBinBinary(std::istream& iStream,
const axlf_section_header& sectionHeader)
{
Section::readXclBinBinary(iStream, sectionHeader);
XUtil::TRACE("Determining AIE_PARTITION Section Name");
// Do we have enough room to overlay the header structure
if (m_bufferSize < sizeof(aie_partition)) {
auto errMsg = boost::format("ERROR: Segment size (%d) is smaller than the size of the aie_partition structure (%d)")
% m_bufferSize % sizeof(aie_partition);
throw std::runtime_error(boost::str(errMsg));
}
auto pHdr = reinterpret_cast<const aie_partition*>(m_pBuffer);
// Name
std::string name = m_pBuffer + pHdr->mpo_name;
XUtil::TRACE(std::string("Successfully read in the AIE_PARTITION section: '") + name + "' ");
Section::m_sIndexName = name;
}
// -------------------------------------------------------------------------
| 36.02924 | 158 | 0.646689 |
bryanloz-xilinx
|
653fa5e0e418f3ee481bfbcf8b1ccdb258d914ec
| 2,144 |
cpp
|
C++
|
tests/cthread/test_reset_noninit_read.cpp
|
hachetman/systemc-compiler
|
0cc81ace03336d752c0146340ff5763a20e3cefd
|
[
"Apache-2.0"
] | 86 |
2020-10-23T15:59:47.000Z
|
2022-03-28T18:51:19.000Z
|
tests/cthread/test_reset_noninit_read.cpp
|
hachetman/systemc-compiler
|
0cc81ace03336d752c0146340ff5763a20e3cefd
|
[
"Apache-2.0"
] | 18 |
2020-12-14T13:11:26.000Z
|
2022-03-14T05:34:20.000Z
|
tests/cthread/test_reset_noninit_read.cpp
|
hachetman/systemc-compiler
|
0cc81ace03336d752c0146340ff5763a20e3cefd
|
[
"Apache-2.0"
] | 17 |
2020-10-29T16:19:43.000Z
|
2022-03-11T09:51:05.000Z
|
/******************************************************************************
* Copyright (c) 2020, Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception.
*
*****************************************************************************/
#include "systemc.h"
#include <sct_assert.h>
using namespace sc_core;
// Read not initialized variables/arrays in reset -- error/warning reported
class A : public sc_module
{
public:
sc_in<bool> clk{"clk"};
sc_signal<bool> nrst{"nrst"};
int* p;
int m;
int* q = &m;
int n;
int& r = n;
int mm;
SC_CTOR(A)
{
p = sc_new<int>();
SC_CTHREAD(readProc1, clk.pos());
async_reset_signal_is(nrst, false);
SC_CTHREAD(readProc2, clk.pos());
async_reset_signal_is(nrst, false);
}
sc_signal<int> s{"s"};
void f1(int par_a[3]) {
auto ii = par_a[1];
}
void f2(int (&par_a)[3], int i) {
auto ii = par_a[i];
}
void f3(int par_a[3][3], int i) {
auto ii = par_a[i+1][i+2];
}
sc_signal<int> s0;
void readProc1()
{
int aa[3];
int bb[3] = {0,1,2};
int cc[3][3];
int dd[3];
f1(aa); // Warning
f2(bb, 1);
f3(cc, 0); // Warning
int i = dd[1]; // Warning
int j;
int& r = j;
i = r; // Warning
int l;
i = l + 1; // Warning
s0 = i;
wait();
while(1) {
wait();
}
}
sc_signal<int> s1;
void readProc2()
{
int i;
i = *p; // Error
i = mm; // Error
int j = *q; // Error
j = r; // Error
s1 = i + j;
wait();
while(1) {
wait();
}
}
};
int sc_main(int argc, char* argv[])
{
sc_clock clk("clk", 1, SC_NS);
A a_mod{"a_mod"};
a_mod.clk(clk);
sc_start();
return 0;
}
| 20.815534 | 79 | 0.392257 |
hachetman
|
6546b8d70b2c6680eac41aa85509505cf440f21b
| 1,104 |
cpp
|
C++
|
acmicpc/14449.cpp
|
juseongkr/BOJ
|
8f10a2bf9a7d695455493fbe7423347a8b648416
|
[
"Apache-2.0"
] | 7 |
2020-02-03T10:00:19.000Z
|
2021-11-16T11:03:57.000Z
|
acmicpc/14449.cpp
|
juseongkr/Algorithm-training
|
8f10a2bf9a7d695455493fbe7423347a8b648416
|
[
"Apache-2.0"
] | 1 |
2021-01-03T06:58:24.000Z
|
2021-01-03T06:58:24.000Z
|
acmicpc/14449.cpp
|
juseongkr/Algorithm-training
|
8f10a2bf9a7d695455493fbe7423347a8b648416
|
[
"Apache-2.0"
] | 1 |
2020-01-22T14:34:03.000Z
|
2020-01-22T14:34:03.000Z
|
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Segment {
public:
int len;
vector<long long> tree;
Segment(int n) : len(n) { tree.resize(2*n); }
void make()
{
for (int i=len-1; i>0; i--)
tree[i] = (tree[i*2] + tree[i*2+1]);
}
void update(int i, int val)
{
i += len;
tree[i] = val;
for (i/=2; i>0; i/=2)
tree[i] = (tree[2*i] + tree[2*i+1]);
}
long long query(int l, int r)
{
l += len;
r += len;
long long ret = 0;
while (l <= r) {
if (l % 2 == 1)
ret += tree[l++];
if (r % 2 == 0)
ret += tree[r--];
l /= 2;
r /= 2;
}
return ret;
}
};
int main()
{
ios_base::sync_with_stdio(0);
cout.tie(0);
cin.tie(0);
vector<pair<int, int>> vec;
int n, t;
cin >> n;
for (int i=0; i<n; ++i) {
cin >> t;
vec.push_back({t, i});
}
sort(vec.rbegin(), vec.rend());
int ans = 0;
Segment seg = Segment(n);
for (int i=0; i<n; ++i) {
int x = vec[i].second;
int l = seg.query(0, x);
int r = seg.query(x, n);
if (l*2 < r || r*2 < l)
ans++;
seg.update(x, 1);
}
cout << ans << '\n';
return 0;
}
| 14.526316 | 46 | 0.501812 |
juseongkr
|
6548f6c55271d48e71e07382db71dd153efca912
| 559 |
cc
|
C++
|
src/auth.cc
|
watersalesman/BeastQuest
|
7622ce59a87c79cabbc7efee77d17866ab626b40
|
[
"MIT"
] | 1 |
2019-10-31T12:41:42.000Z
|
2019-10-31T12:41:42.000Z
|
src/auth.cc
|
watersalesman/BeastQuest
|
7622ce59a87c79cabbc7efee77d17866ab626b40
|
[
"MIT"
] | null | null | null |
src/auth.cc
|
watersalesman/BeastQuest
|
7622ce59a87c79cabbc7efee77d17866ab626b40
|
[
"MIT"
] | null | null | null |
#include "beastquest/auth.hh"
#include <boost/beast.hpp>
#include <string>
namespace detail = boost::beast::detail;
namespace quest {
BasicAuth::BasicAuth(std::string username, std::string password)
: username_{std::move(username)},
password_{std::move(password)},
auth_string_("Basic " +
detail::base64_encode(username_ + ":" + password_)) {}
std::string BasicAuth::GetAuthString() const noexcept { return auth_string_; }
bool BasicAuth::IsEmpty() const noexcept { return auth_string_.empty(); }
} // namespace quest
| 29.421053 | 78 | 0.692308 |
watersalesman
|
65490c281c0ad50b3926840de0dd526a144466c3
| 27,492 |
hpp
|
C++
|
dmp/openCV_dmp.hpp
|
klaricmn/snippets
|
a1ae04c13a2209dee013284358d2d987bb0fb4fc
|
[
"MIT"
] | null | null | null |
dmp/openCV_dmp.hpp
|
klaricmn/snippets
|
a1ae04c13a2209dee013284358d2d987bb0fb4fc
|
[
"MIT"
] | null | null | null |
dmp/openCV_dmp.hpp
|
klaricmn/snippets
|
a1ae04c13a2209dee013284358d2d987bb0fb4fc
|
[
"MIT"
] | null | null | null |
#ifndef _OPENCV_DMP_HPP_
#define _OPENCV_DMP_HPP_
#include <vector>
#include <opencv2/core/core.hpp>
#include <boost/filesystem.hpp>
#include <limits>
#include <map>
#include <set>
#include <list>
#include <vector>
#include <stdexcept>
#include <opencv2/imgproc/imgproc.hpp>
//for DEBUG
//#include <opencv2/highgui/highgui.hpp>
///
/// Generate a opening DMP profile
/// \param inputImage The image that will be filtered for light objects
/// \param ses The set of strictly increasing geodesic structuring elements
///
template <typename OperatingPixelType>
std::vector<cv::Mat> opencvOpenDmp(const cv::Mat& inputImage, const std::vector<int>& ses);
///
/// Dilation by Reconstruction using the Downhill Filter algorithm (Robinson,Whelan)
///
/// \param mask The image/surface that bounds the reconstruction of the marker
/// \param mark The image/surface that initializes the reconstruction
/// \returns The dilation reconstruction
template <typename OperatingPixelType>
cv::Mat dilationByReconstructionDownhill(const cv::Mat& mask, const cv::Mat& mark);
///
/// Generate a closing DMP profile
/// \param inputImage The image that will be filtered for dark objects
/// \param ses The set of strictly increasing geodesic structuring elements
///
template <typename OperatingPixelType>
std::vector<cv::Mat> opencvCloseDmp(const cv::Mat& inputImage, const std::vector<int>& ses);
///
/// Erosion by Reconstruction using an Uphill Filter algorithm (insp. by Robinson,Whelan)
///
/// \param mask The image/surface that bounds the reconstruction of the marker
/// \param mark The image/surface that initializes the reconstruction
/// \returns The erosion reconstruction
template <typename OperatingPixelType>
cv::Mat erosionByReconstructionUphill(const cv::Mat& mask, const cv::Mat& mark);
/// Dump the pyramid levels
/// \param dmp the pyramid cells to dump
/// \param sideTag the Open or Close identifier for the levels
/// \param outputPath the output directory
/// \param filePath the filename being processed
void dumpDmpLevels(const std::vector<cv::Mat>& dmp, const std::vector<int>& ses, const std::string& sideTag,
const boost::filesystem::path& outputPath,
const boost::filesystem::path& filePath);
// ============================
// ============================
// == BEGIN Template Functions
// ============================
// ============================
template <typename OperatingPixelType>
std::vector<cv::Mat> opencvOpenDmp(const cv::Mat& inputImage, const std::vector<int>& ses)
{
//cgi::log::MetaLogStream& log(cgi::log::MetaLogStream::instance());
// ++ Open, then dilate by reconstruction
//if (false == std::numeric_limits<T>::is_integer)
// CGI_THROW(std::logic_error,"Invalid template type");
// Build Structuring Elements
std::vector<cv::Mat> structuringElements;
for (std::vector<int>::const_iterator level = ses.begin();level!=ses.end();++level)
{
const int lev = *level;
// Circular structuring element
const int edgeSize = lev+1+lev; // turn radius into edge size
structuringElements.push_back(
cv::getStructuringElement(cv::MORPH_ELLIPSE,cv::Size(edgeSize,edgeSize))
);
}
// Build Morphological Operation Stack (open)
std::vector<cv::Mat> mos;
for (unsigned int level = 0;level<structuringElements.size();++level)
{
cv::Mat filteredImage(inputImage.size().height, inputImage.size().width, cv::DataType<OperatingPixelType>::type);
cv::morphologyEx(inputImage, filteredImage, cv::MORPH_OPEN, structuringElements.at(level));
mos.push_back(filteredImage);
}
const int n_lvls = mos.size();
// log << cgi::log::Priority::INFO << "opencvOpenDmp" << "MOS Produced, size:" << n_lvls << cgi::log::flush;
// Set the Tile band count to the SEs array size
std::vector<cv::Mat> profile;
profile.reserve(n_lvls);
// ////////////////////////////////////////////////////////////////////////
// USE: dilationByReconstructionDownhill(const cv::Mat& mask,const cv::Mat& mark)
cv::Mat tempRec; // Temporary Open Record
cv::Mat lastRec; // previous level Open Record
// Open = (erode,dilate)
//typename MorphologyOperator<DataType>::type morphology(_ses[0]);
//typename ReconstructionOperator<DataType>::type reconstructor;
//dilationByReconstructionDownhill( inputImage, mos.at(0) ).copyTo(tempRec);
tempRec = dilationByReconstructionDownhill<OperatingPixelType>( inputImage, mos.at(0) ).clone();
// get the absolute difference of the two images
cv::Mat diffImage(inputImage.size().height, inputImage.size().width, cv::DataType<OperatingPixelType>::type);
absdiff(inputImage, tempRec, diffImage);
profile.push_back(diffImage.clone());
tempRec.copyTo(lastRec);
// Subsequent Levels
for (int i = 1;i < n_lvls;++i)
{
// reconstruction(mask , mark)
//dilationByReconstructionDownhill( inputImage, mos.at(i) ).copyTo(tempRec);
tempRec = dilationByReconstructionDownhill<OperatingPixelType>( inputImage, mos.at(i) ).clone();
// BEGIN DEBUG
/*
std::stringstream ss;
ss << "reconstruction_from_opening_" << i << ".png";
if(!cv::imwrite(ss.str(), tempRec))
{
throw std::runtime_error("Failed to write");
}
*/
// END DEBUG
// get the absolute difference of the two images
absdiff(lastRec, tempRec, diffImage);
profile.push_back(diffImage.clone());
tempRec.copyTo(lastRec);
}
return profile;
}
template <typename OperatingPixelType>
cv::Mat dilationByReconstructionDownhill(const cv::Mat& mask, const cv::Mat& mark)
{
//typedef unsigned short OperatingPixelType;
//cgi::log::MetaLogStream& log(cgi::log::MetaLogStream::instance());
if (false == std::numeric_limits<OperatingPixelType>::is_integer)
//CGI_THROW(std::logic_error,"Invalid template / operating-pixel type");
throw new std::logic_error("Invalid template / operating-pixel type");
const cv::Size size = mask.size();
//if (size.width != mark.size().width || size.height != mark.size().height)
if (size != mark.size())
{
//log << cgi::log::Priority::ERROR << "dilationByReconstructionUphill"
//<< "Size mismatch: ("
//<< size.width << "," << size.height << ") != ("
//<< mark.size().width << "," << mark.size().height << ")" << cgi::log::flush;
}
// --------------------------------
// Place each p : I(p) > 0 into List[I(p)]
// --------------------------------
// Copy the marker into the reconstruction
// we can then grow it in place
// value i has a list of pixels at position (y,x)
cv::Mat reconstruction(mark.size().height, mark.size().width, cv::DataType<OperatingPixelType>::type);
mark.copyTo(reconstruction);
// for template, use typename
// typedef typename std::list<std::pair<int,int> > LocationListType;
// typedef typename std::map< OperatingPixelType, LocationListType > MapOfLocationListType;
typedef typename std::list<std::pair<int,int> > LocationListType;
typedef typename std::map< OperatingPixelType, LocationListType > MapOfLocationListType;
// This is essentially an indexed image version of the input `mark' raster
MapOfLocationListType valueLocationListMap;
// Build an in-memory indexed image
// but while we are at it, verify that it is properly bounded by `mask' raster
for (int i = 0; i < size.height; ++i)
for (int j = 0; j < size.width; ++j)
{
const OperatingPixelType pixelValue = reconstruction.at<OperatingPixelType>(i, j);
if (pixelValue > mask.at<OperatingPixelType>(i, j))
{
//std::cout << "Storing ("<< i << "," << j <<") into valueLocationListMap["<< static_cast<int>(pixelValue) << "]" << std::endl;
std::stringstream msg;
msg << "(pixelValue > mask[0](i, j)), for raster location = ("<<i<<","<<j<<")";
//CGI_THROW (std::logic_error, msg.str()); // the marker must always be LTE the mask, by definition
throw new std::logic_error( msg.str());
}
valueLocationListMap[pixelValue].push_back( std::make_pair<int,int>(i,j) );
}
// No valid pixels or values above floor? Return the input as output
if (valueLocationListMap.size() == 0)
return reconstruction;
// --------------------------------
// The farthest downhill we will go
// is to the current min(mark[0])
// therefore, we do not need to
// process the current min, we
// already copied them to output
const OperatingPixelType minValue = valueLocationListMap.begin()->first;
valueLocationListMap[minValue].clear();
std::set<std::pair<int,int> > finalizedPixels;
// --------------------------------
// Do a backward iteration (downhill)
// through the
// valueLocationListMap[values]
// --------------------------------
// use typename for template version
//for (typename MapOfLocationListType::reverse_iterator valueList = valueLocationListMap.rbegin();
// valueList != valueLocationListMap.rend(); ++valueList)
for (typename MapOfLocationListType::reverse_iterator valueList = valueLocationListMap.rbegin();
valueList != valueLocationListMap.rend(); ++valueList)
{
// The gray value
const OperatingPixelType currentValue = valueList->first;
// The list of (y,x) tuples
LocationListType locations = valueList->second;
// for each location indexed in the value list
while (!locations.empty())
{
// Debug thing
// if (locations.size() > (size.width * size.height))
// {
// CGI_THROW(std::logic_error, "GrayscaleDilationByReconstructionDownhill has gone out of control, this should never happen!");
// }
// pull/pop the first position from the list, mark it as finalized
std::pair<int,int> frontPosition = locations.front();
finalizedPixels.insert(frontPosition);
locations.pop_front();
const int y = frontPosition.first;
const int x = frontPosition.second;
const int pre_x = x - 1;
const int post_x = x + 1;
const int pre_y = y - 1;
const int post_y = y + 1;
// For each neighbor
// - a -
// b p d
// - c -
// a = (pre_y,x), b = (y,pre_x), c = (post_y,x), d = (y,post_x)
// Neighbor Pixel 'a'
const std::pair<int,int> a = std::make_pair<int,int>(pre_y,x);
const OperatingPixelType mask_a = mask.at<OperatingPixelType>(pre_y,x);
// if neighbor index is within bounds and not finalized
if ((finalizedPixels.find(a) == finalizedPixels.end()) && (pre_y >= 0) && (mask_a > 0))
{
OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(pre_y,x);
OperatingPixelType constraintValue = std::min<OperatingPixelType>(currentValue,mask_a);
// std::cout << "Neighbor(a) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl;
if (neighborValue < constraintValue)
{
reconstruction.at<OperatingPixelType>(pre_y,x) = constraintValue;
if ( constraintValue == currentValue )
{
// std::cout << "Adding ("<< pre_y << "," << x <<") to current list" << std::endl;
locations.push_back( a );
}
else
{
// std::cout << "Moving ("<< pre_y << "," << x <<") from "
// << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl;
valueLocationListMap[neighborValue].remove( a );
valueLocationListMap[constraintValue].push_back( a );
}
}
}
// Neighbor Pixel 'b'
const std::pair<int,int> b = std::make_pair<int,int>(y,pre_x);
const OperatingPixelType mask_b = mask.at<OperatingPixelType>(y,pre_x);
if ((finalizedPixels.find(b) == finalizedPixels.end()) && (pre_x >= 0) && (mask_b > 0))
{
OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(y,pre_x);
OperatingPixelType constraintValue = std::min<OperatingPixelType>(currentValue,mask_b);
// std::cout << "Neighbor(b) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl;
if (neighborValue < constraintValue)
{
reconstruction.at<OperatingPixelType>(y,pre_x) = constraintValue;
if ( constraintValue == currentValue )
{
// std::cout << "Adding ("<< y << "," << pre_x <<") to current list" << std::endl;
locations.push_back( b );
}
else
{
// std::cout << "Moving ("<< y << "," << pre_x <<") from "
// << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl;
valueLocationListMap[neighborValue].remove( b );
valueLocationListMap[constraintValue].push_back( b );
}
}
}
// Neighbor Pixel 'c'
const std::pair<int,int> c = std::make_pair<int,int>(post_y,x);
const OperatingPixelType mask_c = mask.at<OperatingPixelType>(post_y,x);
if ((finalizedPixels.find(c) == finalizedPixels.end()) && (post_y < size.height) && (mask_c > 0))
{
OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(post_y,x);
OperatingPixelType constraintValue = std::min<OperatingPixelType>(currentValue,mask_c);
// std::cout << "Neighbor(c) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl;
if (neighborValue < constraintValue)
{
reconstruction.at<OperatingPixelType>(post_y,x) = constraintValue;
if ( constraintValue == currentValue )
{
// std::cout << "Adding ("<< post_y << "," << x <<") to current list" << std::endl;
locations.push_back( c );
}
else
{
// std::cout << "Moving ("<< post_y << "," << x <<") from "
// << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl;
valueLocationListMap[neighborValue].remove( c );
valueLocationListMap[constraintValue].push_back( c );
}
}
}
// Neighbor Pixel 'd'
const std::pair<int,int> d = std::make_pair<int,int>(y,post_x);
const OperatingPixelType mask_d = mask.at<OperatingPixelType>(y,post_x);
if ((finalizedPixels.find(d) == finalizedPixels.end()) && (post_x < size.width) && (mask_d > 0))
{
OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(y,post_x);
OperatingPixelType constraintValue = std::min<OperatingPixelType>(currentValue,mask_d);
// std::cout << "Neighbor(d) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl;
if (neighborValue < constraintValue)
{
reconstruction.at<OperatingPixelType>(y,post_x) = constraintValue;
if ( constraintValue == currentValue )
{
// std::cout << "Adding ("<< y << "," << post_x <<") to current list" << std::endl;
locations.push_back( d );
}
else
{
// std::cout << "Moving ("<< y << "," << post_x <<") from "
// << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl;
valueLocationListMap[neighborValue].remove( d );
valueLocationListMap[constraintValue].push_back( d );
}
}
}
} // end, a value's position list is emptied.
} // end for each value in the marker
return reconstruction;
};
template <typename OperatingPixelType>
std::vector<cv::Mat> opencvCloseDmp(const cv::Mat& inputImage, const std::vector<int>& ses)
{
//cgi::log::MetaLogStream& log(cgi::log::MetaLogStream::instance());
// ++ Close, then erode by reconstruction
//if (false == std::numeric_limits<T>::is_integer)
// CGI_THROW(std::logic_error,"Invalid template type");
// Build Structuring Elements
std::vector<cv::Mat> structuringElements;
for (std::vector<int>::const_iterator level = ses.begin();level!=ses.end();++level)
{
const int lev = *level;
// Circular structuring element
const int edgeSize = lev+1+lev; // turn radius into edge size
structuringElements.push_back(
cv::getStructuringElement(cv::MORPH_ELLIPSE,cv::Size(edgeSize,edgeSize))
);
}
// Build Morphological Operation Stack (close)
std::vector<cv::Mat> mos;
for (unsigned int level = 0;level<structuringElements.size();++level)
{
cv::Mat filteredImage(inputImage.size().height, inputImage.size().width, cv::DataType<OperatingPixelType>::type);
cv::morphologyEx(inputImage, filteredImage, cv::MORPH_CLOSE, structuringElements.at(level));
mos.push_back(filteredImage);
}
const int n_lvls = mos.size();
// log << cgi::log::Priority::INFO << "opencvCloseDmp" << "MOS Produced, size:" << n_lvls << cgi::log::flush;
// Set the Tile band count to the SEs array size
std::vector<cv::Mat> profile;
profile.reserve(n_lvls);
// ////////////////////////////////////////////////////////////////////////
// USE: erosionByReconstructionUphill(const cv::Mat& mask,const cv::Mat& mark)
cv::Mat tempRec; // Temporary Close Record
cv::Mat lastRec; // previous level Close Record
// Close = (dilate,erode)
//typename MorphologyOperator<DataType>::type morphology(_ses[0]);
//typename ReconstructionOperator<DataType>::type reconstructor;
//erosionByReconstructionUphill<OperatingPixelType>( inputImage, mos.at(0) ).copyTo(tempRec);
tempRec = erosionByReconstructionUphill<OperatingPixelType>( inputImage, mos.at(0) ).clone();
// get the absolute difference of the two images
cv::Mat diffImage(inputImage.size().height, inputImage.size().width, cv::DataType<OperatingPixelType>::type);
absdiff(inputImage, tempRec, diffImage);
profile.push_back(diffImage.clone());
tempRec.copyTo(lastRec);
// Subsequent Levels
for (int i = 1;i < n_lvls;++i)
{
// reconstruction(mask , mark)
// NOTE: Potentially bad line
//erosionByReconstructionUphill<OperatingPixelType>( inputImage, mos.at(i) ).copyTo(tempRec);
tempRec = erosionByReconstructionUphill<OperatingPixelType>( inputImage, mos.at(i) ).clone();
// BEGIN DEBUG
/*
std::stringstream ss;
ss << "reconstruction_from_closing_" << i << ".png";
if(!cv::imwrite(ss.str(), tempRec))
{
throw std::runtime_error("Failed to write");
}
*/
// END DEBUG
// get the absolute difference of the two images
absdiff(lastRec, tempRec, diffImage);
profile.push_back(diffImage.clone());
tempRec.copyTo(lastRec);
}
return profile;
};
template <typename OperatingPixelType>
cv::Mat erosionByReconstructionUphill(const cv::Mat& mask, const cv::Mat& mark)
{
// cgi::log::MetaLogStream& log(cgi::log::MetaLogStream::instance());
if (false == std::numeric_limits<OperatingPixelType>::is_integer)
//CGI_THROW(std::logic_error,"Invalid template / operating-pixel type");
throw new std::logic_error("Invalid template / operating-pixel type");
const cv::Size size = mask.size();
//if (size.width != mark.size().width || size.height != mark.size().height)
if (size != mark.size())
{
//log << cgi::log::Priority::ERROR << "erosionByReconstructionDownhill"
//<< "Size mismatch: ("
//<< size.width << "," << size.height << ") != ("
//<< mark.size().width << "," << mark.size().height << ")" << cgi::log::flush;
}
// --------------------------------
// Place each p : I(p) > 0 into List[I(p)]
// --------------------------------
// Copy the marker into the reconstruction
// we can then grow it in place
// value i has a list of pixels at position (y,x)
cv::Mat reconstruction(mark.size().height, mark.size().width, cv::DataType<OperatingPixelType>::type);
mark.copyTo(reconstruction);
// for template, use typename
// typedef typename std::list<std::pair<int,int> > LocationListType;
// typedef typename std::map< OperatingPixelType, LocationListType > MapOfLocationListType;
typedef std::list<std::pair<int,int> > LocationListType;
typedef std::map< OperatingPixelType, LocationListType > MapOfLocationListType;
// This is essentially an indexed image version of the input `mark' raster
MapOfLocationListType valueLocationListMap;
// Build an in-memory indexed image
// but while we are at it, verify that it is properly bounded by `mask' raster
for (int i = 0; i < size.height; ++i)
for (int j = 0; j < size.width; ++j)
{
const OperatingPixelType pixelValue = reconstruction.at<OperatingPixelType>(i, j);
if (pixelValue < mask.at<OperatingPixelType>(i, j))
{
//std::cout << "Storing ("<< i << "," << j <<") into valueLocationListMap["<< static_cast<int>(pixelValue) << "]" << std::endl;
std::stringstream msg;
msg << "(pixelValue < mask[0](i, j)), for raster location = ("<<i<<","<<j<<")";
//CGI_THROW (std::logic_error, msg.str()); // the marker must always be GTE the mask, by definition
throw new std::logic_error(msg.str());
}
valueLocationListMap[pixelValue].push_back( std::make_pair<int,int>(i,j) );
}
// No valid pixels or values below floor? Return the input as output
if (valueLocationListMap.size() == 0)
return reconstruction;
// --------------------------------
// The farthest uphill we will go
// is to the current max(mark[0])
// therefore, we do not need to
// process the current max, we
// already copied them to output
const OperatingPixelType maxValue = valueLocationListMap.rbegin()->first;
valueLocationListMap[maxValue].clear();
std::set<std::pair<int,int> > finalizedPixels;
// --------------------------------
// Do a forward iteration (uphill)
// through the
// valueLocationListMap[values]
// --------------------------------
// use typename for template version
//for (typename MapOfLocationListType::iterator valueList = valueLocationListMap.begin();
// valueList != valueLocationListMap.end(); ++valueList)
for (typename MapOfLocationListType::iterator valueList = valueLocationListMap.begin();
valueList != valueLocationListMap.end(); ++valueList)
{
// The gray value
const OperatingPixelType currentValue = valueList->first;
// The list of (y,x) tuples
LocationListType locations = valueList->second;
// for each location indexed in the value list
while (!locations.empty())
{
// Debug thing
// if (locations.size() > (size.width * size.height))
// {
// CGI_THROW(std::logic_error, "GrayscaleDilationByReconstructionDownhill has gone out of control, this should never happen!");
// }
// pull/pop the first position from the list, mark it as finalized
std::pair<int,int> frontPosition = locations.front();
finalizedPixels.insert(frontPosition);
locations.pop_front();
const int y = frontPosition.first;
const int x = frontPosition.second;
const int pre_x = x - 1;
const int post_x = x + 1;
const int pre_y = y - 1;
const int post_y = y + 1;
// For each neighbor
// - a -
// b p d
// - c -
// a = (pre_y,x), b = (y,pre_x), c = (post_y,x), d = (y,post_x)
// Neighbor Pixel 'a'
const std::pair<int,int> a = std::make_pair<int,int>(pre_y,x);
const OperatingPixelType mask_a = mask.at<OperatingPixelType>(pre_y,x);
// if neighbor index is within bounds and not finalized
if ((finalizedPixels.find(a) == finalizedPixels.end()) && (pre_y >= 0) && (mask_a > 0))
{
OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(pre_y,x);
OperatingPixelType constraintValue = std::max<OperatingPixelType>(currentValue,mask_a);
// std::cout << "Neighbor(a) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl;
if (neighborValue > constraintValue)
{
reconstruction.at<OperatingPixelType>(pre_y,x) = constraintValue;
if ( constraintValue == currentValue )
{
// std::cout << "Adding ("<< pre_y << "," << x <<") to current list" << std::endl;
locations.push_back( a );
}
else
{
// std::cout << "Moving ("<< pre_y << "," << x <<") from "
// << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl;
valueLocationListMap[neighborValue].remove( a );
valueLocationListMap[constraintValue].push_back( a );
}
}
}
// Neighbor Pixel 'b'
const std::pair<int,int> b = std::make_pair<int,int>(y,pre_x);
const OperatingPixelType mask_b = mask.at<OperatingPixelType>(y,pre_x);
if ((finalizedPixels.find(b) == finalizedPixels.end()) && (pre_x >= 0) && (mask_b > 0))
{
OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(y,pre_x);
OperatingPixelType constraintValue = std::max<OperatingPixelType>(currentValue,mask_b);
// std::cout << "Neighbor(b) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl;
if (neighborValue > constraintValue)
{
reconstruction.at<OperatingPixelType>(y,pre_x) = constraintValue;
if ( constraintValue == currentValue )
{
// std::cout << "Adding ("<< y << "," << pre_x <<") to current list" << std::endl;
locations.push_back( b );
}
else
{
// std::cout << "Moving ("<< y << "," << pre_x <<") from "
// << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl;
valueLocationListMap[neighborValue].remove( b );
valueLocationListMap[constraintValue].push_back( b );
}
}
}
// Neighbor Pixel 'c'
const std::pair<int,int> c = std::make_pair<int,int>(post_y,x);
const OperatingPixelType mask_c = mask.at<OperatingPixelType>(post_y,x);
if ((finalizedPixels.find(c) == finalizedPixels.end()) && (post_y < size.height) && (mask_c > 0))
{
OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(post_y,x);
OperatingPixelType constraintValue = std::max<OperatingPixelType>(currentValue,mask_c);
// std::cout << "Neighbor(c) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl;
if (neighborValue > constraintValue)
{
reconstruction.at<OperatingPixelType>(post_y,x) = constraintValue;
if ( constraintValue == currentValue )
{
// std::cout << "Adding ("<< post_y << "," << x <<") to current list" << std::endl;
locations.push_back( c );
}
else
{
// std::cout << "Moving ("<< post_y << "," << x <<") from "
// << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl;
valueLocationListMap[neighborValue].remove( c );
valueLocationListMap[constraintValue].push_back( c );
}
}
}
// Neighbor Pixel 'd'
const std::pair<int,int> d = std::make_pair<int,int>(y,post_x);
const OperatingPixelType mask_d = mask.at<OperatingPixelType>(y,post_x);
if ((finalizedPixels.find(d) == finalizedPixels.end()) && (post_x < size.width) && (mask_d > 0))
{
OperatingPixelType neighborValue = reconstruction.at<OperatingPixelType>(y,post_x);
OperatingPixelType constraintValue = std::max<OperatingPixelType>(currentValue,mask_d);
// std::cout << "Neighbor(d) = ("<< static_cast<int>(neighborValue) << "), constraint=(" << static_cast<int>(constraintValue) <<")" << std::endl;
if (neighborValue > constraintValue)
{
reconstruction.at<OperatingPixelType>(y,post_x) = constraintValue;
if ( constraintValue == currentValue )
{
// std::cout << "Adding ("<< y << "," << post_x <<") to current list" << std::endl;
locations.push_back( d );
}
else
{
// std::cout << "Moving ("<< y << "," << post_x <<") from "
// << static_cast<int>(neighborValue) << " to " << static_cast<int>(constraintValue) << std::endl;
valueLocationListMap[neighborValue].remove( d );
valueLocationListMap[constraintValue].push_back( d );
}
}
}
} // end, a value's position list is emptied.
} // end for each value in the marker
return reconstruction;
};
#endif //_OPENCV_DMP_HPP_
| 36.317041 | 148 | 0.658337 |
klaricmn
|
654bc48e35c6d43864f860a1bb44b802a040c7d1
| 2,291 |
cpp
|
C++
|
Pimple/CPointerToImplementation.cpp
|
infojg9/CDesignPatterns
|
8e9025c2ec93210d4c6e294a726302c9efc6b94d
|
[
"MIT"
] | null | null | null |
Pimple/CPointerToImplementation.cpp
|
infojg9/CDesignPatterns
|
8e9025c2ec93210d4c6e294a726302c9efc6b94d
|
[
"MIT"
] | null | null | null |
Pimple/CPointerToImplementation.cpp
|
infojg9/CDesignPatterns
|
8e9025c2ec93210d4c6e294a726302c9efc6b94d
|
[
"MIT"
] | null | null | null |
/*
* \file CPointerToImplementation.cpp
* \author https://github.com/infojg9
* \brief An example of the PIMPL Design / Pointer to Implementation.
* \copyright MIT/BSD Redistributable License
*/
#include "CPointerToImplementation.h"
#include <iostream>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
namespace Pimple {
namespace V1 {
/// \class Private Impl class decoupled implementation, kind of Bridge pattern
class CPointerToImplementation::Impl
{
public:
Impl() = default;
virtual ~Impl();
Impl(Impl const&) = default;
Impl& operator=(Impl const&) = default;
Impl(Impl&&) = default;
Impl& operator=(Impl&&) = default;
double GetElapsed() const;
std::string mName;
#ifdef _WIN32
DWORD mStartTime;
#else
struct timeval mStartTime;
#endif
};
CPointerToImplementation::CPointerToImplementation(std::string const& name)
: m_pImpl(std::make_unique<CPointerToImplementation::Impl>())
{
m_pImpl->mName = name;
#ifdef _WIN32
m_pImpl->mStartTime = GetTickCount();
#else
gettimeofday(&m_pImpl->mStartTime, nullptr);
#endif
}
CPointerToImplementation::~CPointerToImplementation()
{
std::cout << m_pImpl->mName << ": consumed : " << m_pImpl->GetElapsed()
<< " secs" << std::endl;
m_pImpl.reset();
m_pImpl = nullptr;
}
CPointerToImplementation::ImplPtr&& CPointerToImplementation::getImplPtr() {
return std::move(m_pImpl);
}
/// Allow explicit deep copy in copy constructor from rImpl object reference
CPointerToImplementation::CPointerToImplementation(
CPointerToImplementation const& rImpl)
: m_pImpl(std::make_unique<Impl>(*rImpl.m_pImpl))
{}
/// Allow explicit deep copy in copy assignment operator from rImpl object reference
CPointerToImplementation&
CPointerToImplementation::operator=(CPointerToImplementation const& rImpl) {
*m_pImpl = *rImpl.m_pImpl;
return *this;
}
double CPointerToImplementation::Impl::GetElapsed() const
{
#ifdef _WIN32
return (GetTickCount() - mStartTime) / 1e3;
#else
struct timeval end_time;
gettimeofday(&end_time, nullptr);
double t1 = mStartTime.tv_usec / 1e6 + mStartTime.tv_sec;
double t2 = end_time.tv_usec / 1e6 + end_time.tv_sec;
return t2 - t1;
#endif
}
CPointerToImplementation::Impl::~Impl() {
}
} /// namespace V1
} /// namespace Pimple
| 23.618557 | 84 | 0.730249 |
infojg9
|
654fcf199103e19bfe2d2396fd21c110466e72ce
| 3,694 |
hpp
|
C++
|
include/http_session.hpp
|
helderthh/imgwriter
|
60877cfa883faf3f0824c2328a75414c41b7110f
|
[
"Apache-2.0"
] | null | null | null |
include/http_session.hpp
|
helderthh/imgwriter
|
60877cfa883faf3f0824c2328a75414c41b7110f
|
[
"Apache-2.0"
] | null | null | null |
include/http_session.hpp
|
helderthh/imgwriter
|
60877cfa883faf3f0824c2328a75414c41b7110f
|
[
"Apache-2.0"
] | null | null | null |
#ifndef __HTTP_SESSION_H__
#define __HTTP_SESSION_H__
#include <memory>
#include <iostream>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/bind_executor.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/strand.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "utils.hpp"
using tcp = boost::asio::ip::tcp;
namespace http = boost::beast::http;
namespace ptree = boost::property_tree;
template<class Body, class Allocator, class Send>
using RequestHandlerType =
void (*) (http::request<Body, http::basic_fields<Allocator>>&& req,
Send&& send);
// Handles an HTTP server connection
template <template<typename, typename> class RequestHandler>
class Session : public std::enable_shared_from_this<Session<RequestHandler>>
{
struct SendLambda
{
Session& session_;
explicit SendLambda(Session& self) : session_(self) { /* */ }
template<bool isRequest, class MsgBody, class Fields>
void operator()(http::message<isRequest, MsgBody, Fields>&& msg) const
{
// The lifetime of the message has to extend
// for the duration of the async operation so
// we use a shared_ptr to manage it.
auto msgSp =
std::make_shared<http::message<isRequest, MsgBody, Fields>>(std::move(msg));
// Store a type-erased version of the shared
// pointer in the class to keep it alive.
session_.res_ = msgSp;
// Write the response
http::async_write(
session_.socket_,
*msgSp,
boost::asio::bind_executor(
session_.strand_,
std::bind(
&Session::on_write,
this->session_.shared_from_this(),
std::placeholders::_1,
std::placeholders::_2,
msgSp->need_eof())));
}
};
tcp::socket socket_;
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
boost::beast::flat_buffer buffer_;
http::request<http::string_body> req_;
std::shared_ptr<void> res_;
SendLambda sendLambda_;
public:
// Take ownership of the socket
explicit
Session(tcp::socket socket) : socket_(std::move(socket)),
strand_(socket_.get_executor()), sendLambda_(*this)
{
}
void run() { do_read(); }
void do_read()
{
req_ = {}; // Clean the request
// And then read it
http::async_read(socket_, buffer_, req_,
boost::asio::bind_executor(
strand_,
std::bind(
&Session::on_read,
this->shared_from_this(),
std::placeholders::_1,
std::placeholders::_2
)
)
);
}
void do_close()
{
boost::system::error_code ec;
socket_.shutdown(tcp::socket::shutdown_send, ec);
}
void on_read(boost::system::error_code ec, std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
// This means they closed the connection
if(ec == http::error::end_of_stream)
return do_close();
if(ec)
return fail(ec, "couldn't read");
// Send the response
RequestHandler<http::string_body, SendLambda>()(std::move(req_), sendLambda_);
}
void on_write(boost::system::error_code ec,
std::size_t bytes_transferred,
bool close)
{
boost::ignore_unused(bytes_transferred);
if(ec)
return fail(ec, "write");
if(close)
{
// This means we should close the connection, usually because
// the response indicated the "Connection: close" semantic.
return do_close();
}
// We're done with the response so delete it
res_ = nullptr;
// Read another request
do_read();
}
};
#endif
| 25.30137 | 84 | 0.641581 |
helderthh
|
655173af20362868fcf825b3926a1482336f67a4
| 9,104 |
cpp
|
C++
|
TCPManager.cpp
|
Stefania12/Client-Server-Subscription
|
941ba8615fcf2451d4851f439a7496b325018639
|
[
"MIT"
] | null | null | null |
TCPManager.cpp
|
Stefania12/Client-Server-Subscription
|
941ba8615fcf2451d4851f439a7496b325018639
|
[
"MIT"
] | null | null | null |
TCPManager.cpp
|
Stefania12/Client-Server-Subscription
|
941ba8615fcf2451d4851f439a7496b325018639
|
[
"MIT"
] | null | null | null |
#include "TCPManager.h"
TCPManager* TCPManager::instance = nullptr;
TCPManager::TCPManager()
{
}
TCPManager::~TCPManager()
{
for (std::string id : online_subscribers)
close(subscribers_by_id[id]);
close(listen_fd);
}
TCPManager* TCPManager::get_instance()
{
if (!instance)
instance = new TCPManager();
return instance;
}
bool TCPManager::init(int port)
{
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0)
return false;
int flag = 1;
// Disable Neagle.
if (setsockopt(listen_fd, IPPROTO_TCP, TCP_NODELAY,
(char*)&flag, sizeof(int)) < 0)
return -1;
struct sockaddr_in serv_addr;
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(listen_fd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
return false;
if (listen(listen_fd, MAX_CLIENTS) < 0)
return false;
return true;
}
int TCPManager::get_listen_fd()
{
return listen_fd;
}
void TCPManager::close_subscriber(std::string id)
{
printf("Client %s disconnected.\n", id.c_str());
close(subscribers_by_id[id]);
online_subscribers.erase(id);
subscribers_by_fd.erase(subscribers_by_id[id]);
subscribers_by_id.erase(id);
}
void TCPManager::close_fd(int fd)
{
close(fd);
if (subscribers_by_fd.find(fd) != subscribers_by_fd.end())
{
printf("Client %s disconnected.\n", subscribers_by_fd[fd].c_str());
online_subscribers.erase(subscribers_by_fd[fd]);
subscribers_by_id.erase(subscribers_by_fd[fd]);
subscribers_by_fd.erase(fd);
}
}
int TCPManager::manage_new_connection()
{
int new_sock_fd;
socklen_t sock_len = sizeof(sockaddr_in);
sockaddr_in client_addr;
new_sock_fd = accept(listen_fd, (sockaddr*)&client_addr, &sock_len);
subscriber_fd_info[new_sock_fd] = client_addr;
return new_sock_fd;
}
bool TCPManager::receive_client_commands(int fd)
{
auto node = last_unfinished.find(fd);
client_command last_command;
int last_command_len;
// Check for a previous unfinished command.
if (node == last_unfinished.end())
{
memset((char*)&last_command, 0, sizeof(last_command));
last_command_len = 0;
}
else
{
last_command = last_unfinished[fd].first;
last_command_len = last_unfinished[fd].second;
last_unfinished.erase(fd);
}
int n;
unsigned char buf[1500];
memset(buf, 0, 1500);
// Receive some data.
if ((n = recv(fd, buf, 1500, 0)) < 0)
{
perror("An error occurred while receiving a command from client");
close_fd(fd);
return false;
}
// Client closed connection.
if (n == 0)
{
close_fd(fd);
return false;
}
int offset = 0;
// Add to the unfinished command as much as possible.
if (n < (int)sizeof(client_command) - last_command_len)
{
memcpy(((char*)&last_command) + last_command_len, buf, n);
last_unfinished[fd] =
std::pair<client_command, int>(last_command, last_command_len+n);
return true;
}
// Finish last command and process it.
memcpy(((char*)&last_command) + last_command_len, buf,
sizeof(client_command)-last_command_len);
if (!manage_command(last_command, fd))
return false;
offset = sizeof(client_command)-last_command_len;
// Read full commands and process them.
while (offset + (int)sizeof(client_command) <= n)
{
memcpy((char*)&last_command, buf+offset, sizeof(client_command));
if (!manage_command(last_command, fd))
return false;
offset += sizeof(client_command);
}
// Add the beginning of a new unfinished command.
if (offset < n)
{
memcpy((char*)&last_command, buf+offset, n-offset);
last_command_len = n-offset;
last_unfinished[fd] =
std::pair<client_command, int>(last_command, last_command_len);
}
return true;
}
bool TCPManager::manage_command(client_command &command, int fd)
{
sockaddr_in client_addr = subscriber_fd_info[fd];
if (command.cmd_type == APPROVAL_REQUEST)
{
std::string id;
char buf[100];
memset(buf, 0, 100);
memcpy(buf, &command.id, sizeof(command.id));
id.assign(buf, buf+strlen(buf));
// There is already a client with the same id, connection refused.
if (online_subscribers.find(id) != online_subscribers.end())
{
send_approval_reply(fd, false);
close_fd(fd);
return false;
}
else
{
// Add new id-fd links.
online_subscribers.insert(id);
subscribers_by_fd.insert(std::pair<int, std::string>(fd, id));
subscribers_by_id.insert(std::pair<std::string, int>(id, fd));
char* ip = (char*)&(client_addr.sin_addr.s_addr);
printf("New client %s connected from %d.%d.%d.%d:%d.\n",
id.c_str(), ip[0], ip[1], ip[2], ip[3],
ntohs(client_addr.sin_port));
if (!send_approval_reply(fd, true))
{
close_fd(fd);
return false;
}
if (!send_pending_notifications(fd))
{
close_subscriber(id);
return false;
}
}
}
else
{
if (command.cmd_type == UPDATE)
{
std::string topic, cmd;
char buf[100];
memset(buf, 0, 100);
memcpy(buf, command.topic, sizeof(command.topic));
topic.assign(buf, buf+strlen(buf));
memset(buf, 0, 100);
memcpy(buf, command.command, sizeof(command.command));
cmd.assign(buf, buf+strlen(buf));
if (cmd.compare("subscribe") == 0)
{
subscribe(subscribers_by_fd[fd], topic, command.SF);
}
else
{
if (cmd.compare("unsubscribe") == 0)
unsubscribe(subscribers_by_fd[fd], topic, command.SF);
}
}
}
return true;
}
void TCPManager::subscribe(std::string id, std::string topic, unsigned char SF)
{
if (subscriptions.find(topic) == subscriptions.end())
subscriptions[topic] = std::map<std::string, int>();
if (subscriptions[topic].find(id) != subscriptions[topic].end())
subscriptions[topic].erase(id);
subscriptions[topic].insert(std::pair<std::string, int>(id, (int)SF));
}
void TCPManager::unsubscribe(std::string id, std::string topic,
unsigned char SF)
{
if (subscriptions.find(topic) != subscriptions.end())
subscriptions[topic].erase(id);
}
void TCPManager::manage_notification(notification notif, fd_set *read_fds)
{
char buf[1600];
memset(buf, 0, sizeof(buf));
std::string topic;
memcpy(buf, notif.topic, sizeof(notif.topic));
topic.assign(buf, buf+strlen(buf));
std::map<std::string, int>::iterator it;
for (it = subscriptions[topic].begin(); it != subscriptions[topic].end();
it++)
{
std::string id = it->first;
int sf = it->second;
if (online_subscribers.find(id) != online_subscribers.end())
{
if (!send_notification(id, notif))
{
FD_CLR(subscribers_by_id[id], read_fds);
close_subscriber(id);
}
}
else
{
if (sf == 1)
{
if (pending_notificatons.find(id) == pending_notificatons.end())
pending_notificatons[id] = std::queue<notification>();
pending_notificatons[id].push(notif);
}
}
}
}
bool TCPManager::send_notification(std::string id, notification notif)
{
int len = sizeof(notification) - sizeof(notif.payload) + notif.len;
if (send(subscribers_by_id[id], ¬if, len, 0) < 0)
{
perror("An error occurred while sending notification to client");
return false;
}
return true;
}
bool TCPManager::send_pending_notifications(int fd)
{
std::string id = subscribers_by_fd[fd];
if (pending_notificatons.find(id) != pending_notificatons.end())
{
while (pending_notificatons[id].size() > 0)
{
notification notif = pending_notificatons[id].front();
if (!send_notification(id, notif))
return false;
pending_notificatons[id].pop();
}
}
return true;
}
bool TCPManager::send_approval_reply(int fd, bool accepted)
{
notification notif;
memset((char*)¬if, 0, sizeof(notification));
notif.len = sizeof(notif.payload);
if (accepted)
notif.data_type = 1;
else
notif.data_type = 0;
if (send(fd, (char*)¬if, sizeof(notification), 0) < 0)
{
perror("An error occurred while sending approval of connection");
return false;
}
return true;
}
| 27.504532 | 80 | 0.591608 |
Stefania12
|
6556f4983bc032317b66cc62684efb4da9ef46a1
| 106 |
cpp
|
C++
|
Engine/Source/Runtime/Core/Private/Misc/Exec.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | 1 |
2022-01-29T18:36:12.000Z
|
2022-01-29T18:36:12.000Z
|
Engine/Source/Runtime/Core/Private/Misc/Exec.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | null | null | null |
Engine/Source/Runtime/Core/Private/Misc/Exec.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | null | null | null |
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "Misc/Exec.h"
FExec::~FExec()
{
}
| 13.25 | 60 | 0.679245 |
windystrife
|
65574902b30d43ae2e1fd8b7957f113e08eb03f7
| 1,512 |
cpp
|
C++
|
src/PihaDeviceProvider.cpp
|
jbitoniau/Piha
|
9f346066bf09a93abc5753b5dd996c7f598c9d38
|
[
"MIT"
] | null | null | null |
src/PihaDeviceProvider.cpp
|
jbitoniau/Piha
|
9f346066bf09a93abc5753b5dd996c7f598c9d38
|
[
"MIT"
] | null | null | null |
src/PihaDeviceProvider.cpp
|
jbitoniau/Piha
|
9f346066bf09a93abc5753b5dd996c7f598c9d38
|
[
"MIT"
] | null | null | null |
#include "PihaDeviceProvider.h"
#include <assert.h>
#include <algorithm>
#include "PihaDevice.h"
namespace Piha
{
DeviceProvider::DeviceProvider()
{
}
DeviceProvider::~DeviceProvider()
{
deleteDevices();
}
void DeviceProvider::addDevice( Device* device )
{
mDevices.push_back( device );
for ( Listeners::iterator itrListener=mListeners.begin(); itrListener!=mListeners.end(); ++itrListener )
(*itrListener)->onDeviceAdded( this, device );
}
void DeviceProvider::deleteDevice( Device* device )
{
Devices::iterator itr = std::find( mDevices.begin(), mDevices.end(), device );
if ( itr==mDevices.end() )
return;
for ( Listeners::iterator itrListener=mListeners.begin(); itrListener!=mListeners.end(); ++itrListener )
(*itrListener)->onDeviceRemoving( this, device );
mDevices.erase( itr );
delete device;
}
void DeviceProvider::deleteDevices()
{
Devices devices = mDevices; // The copy is on purpose here
for ( Devices::iterator itr=devices.begin(); itr!=devices.end(); itr++ )
{
Device* device = *itr;
deleteDevice( device );
}
assert( mDevices.empty() );
}
const Devices& DeviceProvider::getDevices() const
{
return mDevices;
}
void DeviceProvider::addListener( Listener* listener )
{
assert(listener);
mListeners.push_back(listener);
}
bool DeviceProvider::removeListener( Listener* listener )
{
Listeners::iterator itr = std::find( mListeners.begin(), mListeners.end(), listener );
if ( itr==mListeners.end() )
return false;
mListeners.erase( itr );
return true;
}
}
| 22.235294 | 105 | 0.71627 |
jbitoniau
|
6557c36df0718bdbe577a9f48111d44fc834df2c
| 914 |
cpp
|
C++
|
source/hougfx/src/hou/gfx/mesh_draw_mode.cpp
|
DavideCorradiDev/houzi-game-engine
|
d704aa9c5b024300578aafe410b7299c4af4fcec
|
[
"MIT"
] | 2 |
2018-04-12T20:59:20.000Z
|
2018-07-26T16:04:07.000Z
|
source/hougfx/src/hou/gfx/mesh_draw_mode.cpp
|
DavideCorradiDev/houzi-game-engine
|
d704aa9c5b024300578aafe410b7299c4af4fcec
|
[
"MIT"
] | null | null | null |
source/hougfx/src/hou/gfx/mesh_draw_mode.cpp
|
DavideCorradiDev/houzi-game-engine
|
d704aa9c5b024300578aafe410b7299c4af4fcec
|
[
"MIT"
] | null | null | null |
// Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#include "hou/gfx/mesh_draw_mode.hpp"
#include "hou/cor/core_functions.hpp"
#define MESH_DRAW_MODE_CASE(mdm, os) \
case mesh_draw_mode::mdm: \
return (os) << #mdm
namespace hou
{
std::ostream& operator<<(std::ostream& os, mesh_draw_mode mdm)
{
switch(mdm)
{
MESH_DRAW_MODE_CASE(points, os);
MESH_DRAW_MODE_CASE(line_strip, os);
MESH_DRAW_MODE_CASE(line_loop, os);
MESH_DRAW_MODE_CASE(lines, os);
MESH_DRAW_MODE_CASE(line_strip_adjacency, os);
MESH_DRAW_MODE_CASE(line_adjacency, os);
MESH_DRAW_MODE_CASE(triangle_strip, os);
MESH_DRAW_MODE_CASE(triangle_fan, os);
MESH_DRAW_MODE_CASE(triangles, os);
MESH_DRAW_MODE_CASE(triangle_strip_adjacency, os);
MESH_DRAW_MODE_CASE(patches, os);
}
return STREAM_VALUE(os, mesh_draw_mode, mdm);
}
} // namespace hou
| 24.052632 | 62 | 0.730853 |
DavideCorradiDev
|
6559fb3179769f5671f90cd3402cfd258384eda6
| 2,487 |
cpp
|
C++
|
test/test.cpp
|
smahajan07/advanced-lane-detection
|
56b116c27d16210be4679ac7e0f5a5db2e31d397
|
[
"MIT"
] | null | null | null |
test/test.cpp
|
smahajan07/advanced-lane-detection
|
56b116c27d16210be4679ac7e0f5a5db2e31d397
|
[
"MIT"
] | 1 |
2018-10-19T19:44:50.000Z
|
2018-11-26T04:46:17.000Z
|
test/test.cpp
|
smahajan07/advanced-lane-detection
|
56b116c27d16210be4679ac7e0f5a5db2e31d397
|
[
"MIT"
] | null | null | null |
/** MIT License
Copyright (c) 2018 Sarthak Mahajan
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.
*/
/**
*@copyright Copyright (c) 2018 Sarthak Mahajan
*@file test.cpp
*@author Sarthak Mahajan
*@brief All tests are defined here.
* Primarily to check image channels and predicted turns.
*/
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/opencv.hpp"
#include "../include/lanedetector.hpp"
#include "../include/preProcess.hpp"
#include "include/mockpreProcess.hpp"
TEST(channels, testNumOfChannelsReturned) {
preProcess helperObj;
cv::Mat testImg, retImg;
std::string imgPath("test.png");
testImg = cv::imread(imgPath, cv::IMREAD_COLOR);
retImg = helperObj.grayImage(testImg);
EXPECT_EQ(1, retImg.channels());
}
TEST(turns, checkTurnDirectionLeft) {
lanedetector testObj(true, true, 1.5, -1.5, cv::Point(200, 0),
cv::Point(800, 0), 640, 12);
EXPECT_EQ("LEFT", testObj.predictTurn());
}
TEST(turns, checkTurnDirectionRight) {
lanedetector testObj(true, true, 1.5, 1.5, cv::Point(200, 0),
cv::Point(400, 0), 640, 12);
EXPECT_EQ("RIGHT", testObj.predictTurn());
}
TEST(preProcess, testPreProcessFuncs) {
std::string imgPath("test.png");
mockpreProcess mockObj;
EXPECT_CALL(mockObj, performAllOps(imgPath)).Times(1).WillOnce(
::testing::Return(1));
mockObj.performAllOps(imgPath);
}
| 36.043478 | 79 | 0.735022 |
smahajan07
|
655d1fdd8d3026f21c1059d361f944aa9d1b3a63
| 1,327 |
cpp
|
C++
|
Practice/2018/2018.8.8/BZOJ1046.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | 4 |
2017-10-31T14:25:18.000Z
|
2018-06-10T16:10:17.000Z
|
Practice/2018/2018.8.8/BZOJ1046.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
Practice/2018/2018.8.8/BZOJ1046.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
#define lowbit(x) ((x)&(-x))
const int maxN=101000;
const int inf=2147483647;
int n,Seq[maxN];
int numcnt,Num[maxN];
int BIT[maxN],F[maxN];
int GetMax(int pos);
void Modify(int pos,int key);
int main(){
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",&Seq[i]),Num[i]=Seq[i]=-Seq[i];
numcnt=n;
sort(&Num[1],&Num[n+1]);numcnt=unique(&Num[1],&Num[n+1])-Num-1;
int Mx=0;
for (int i=n;i>=1;i--){
int p=lower_bound(&Num[1],&Num[numcnt+1],Seq[i])-Num;//cout<<"p:"<<p<<endl;
F[i]=GetMax(p-1)+1;
Modify(p,F[i]);
Mx=max(Mx,F[i]);
}
//for (int i=1;i<=n;i++) cout<<F[i]<<" ";cout<<endl;
for (int i=1;i<=n;i++) Seq[i]=-Seq[i];
int Q;scanf("%d",&Q);
while (Q--){
int k;scanf("%d",&k);
if (k>Mx) printf("Impossible\n");
else{
for (int i=1,j=1,mn=-inf;(j<=k)&&(i<=n);i++)
if ((F[i]+j-1>=k)&&(Seq[i]>mn)){
printf("%d ",Seq[i]);mn=max(mn,Seq[i]);j++;
}
printf("\n");
}
}
return 0;
}
int GetMax(int pos){
int ret=0;
while (pos){
ret=max(ret,BIT[pos]);pos-=lowbit(pos);
}
return ret;
}
void Modify(int pos,int key){
while (pos<=numcnt){
BIT[pos]=max(BIT[pos],key);pos+=lowbit(pos);
}
return;
}
| 18.957143 | 77 | 0.57272 |
SYCstudio
|
655e6fa04c5577c4ff5ecec8e498b656508f6fb3
| 2,338 |
hpp
|
C++
|
model/CellVisitorConcepts.hpp
|
cuzdav/illum
|
b78b6477f8d3fbf31408e419f671dbfe421b4e9e
|
[
"MIT"
] | null | null | null |
model/CellVisitorConcepts.hpp
|
cuzdav/illum
|
b78b6477f8d3fbf31408e419f671dbfe421b4e9e
|
[
"MIT"
] | null | null | null |
model/CellVisitorConcepts.hpp
|
cuzdav/illum
|
b78b6477f8d3fbf31408e419f671dbfe421b4e9e
|
[
"MIT"
] | null | null | null |
#pragma once
#include "CellState.hpp"
#include "Coord.hpp"
#include "Direction.hpp"
#include <concepts>
#include <cstdint>
namespace model {
enum class VisitStatus : std::uint8_t { STOP_VISITING, KEEP_VISITING };
using enum VisitStatus;
// Non-directional visitors don't have a direction. They are used with
// visit-algorithms that are not "linear", but involve mult-direction scans,
// such as the whole board, or "what's adjacent to this cell"
//
// returning void indicates there is no early-stop while visiting
// If you don't care about short-circuiting the visit, don't return true.
//
template <typename T>
concept CellVisitorAll = requires(T visitor, CellState cell) {
{ visitor(Coord{0, 0}, cell) } -> std::same_as<void>;
};
//
// returning a VisitStatus indicates the visit may be stopped prematurely
//
template <typename T>
concept CellVisitorSome = requires(T visitor, CellState cell) {
{ visitor(Coord{0, 0}, cell) } -> std::same_as<VisitStatus>;
};
//
// Unify both Some/All cell visitors
// Many visit algos can work with either - when undirected
//
template <typename T>
concept CellVisitor = CellVisitorAll<T> || CellVisitorSome<T>;
// ==============
// Directed visitors are CellVisitors but are also notified of the direction
// they are going. This is generally associated with the visitors that travel
// along lines.
template <typename T>
concept DirectedCellVisitorAll = requires(T visitor, CellState cell) {
{ visitor(Direction{}, Coord{0, 0}, cell) } -> std::same_as<void>;
};
template <typename T>
concept DirectedCellVisitorSome = requires(T visitor, CellState cell) {
{ visitor(Direction{}, Coord{0, 0}, cell) } -> std::same_as<VisitStatus>;
};
//
// Short circuitable or not, up to the caller
//
template <typename T>
concept DirectedCellVisitor =
DirectedCellVisitorAll<T> || DirectedCellVisitorSome<T>;
// The most flexible of all for the caller, short-circuitable or not, directed
// or not.
template <typename T>
concept OptDirCellVisitor = DirectedCellVisitor<T> || CellVisitor<T>;
// for determining if we should visit a cell or not, for when the visit function
// queries a predicate before dispatching.
template <typename T>
concept CellVisitPredicate = requires(T visitor, CellState cell) {
{ visitor(Coord{0, 0}, cell) } -> std::same_as<bool>;
};
} // namespace model
| 29.974359 | 80 | 0.729256 |
cuzdav
|
65684aca3d0f6ead9f417e45624f69dd11df2f73
| 105,085 |
cpp
|
C++
|
drlvm/vm/jitrino/src/codegenerator/ia32/Ia32IRManager.cpp
|
sirinath/Harmony
|
724deb045a85b722c961d8b5a83ac7a697319441
|
[
"Apache-2.0"
] | 8 |
2015-11-04T06:06:35.000Z
|
2021-07-04T13:47:36.000Z
|
drlvm/vm/jitrino/src/codegenerator/ia32/Ia32IRManager.cpp
|
sirinath/Harmony
|
724deb045a85b722c961d8b5a83ac7a697319441
|
[
"Apache-2.0"
] | 1 |
2021-10-17T13:07:28.000Z
|
2021-10-17T13:07:28.000Z
|
drlvm/vm/jitrino/src/codegenerator/ia32/Ia32IRManager.cpp
|
sirinath/Harmony
|
724deb045a85b722c961d8b5a83ac7a697319441
|
[
"Apache-2.0"
] | 13 |
2015-11-27T03:14:50.000Z
|
2022-02-26T15:12:20.000Z
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
/**
* @author Vyacheslav P. Shakin
*/
#include "Ia32IRManager.h"
#include "Ia32Encoder.h"
#include "Ia32Printer.h"
#include "Log.h"
#include "EMInterface.h"
#include "Ia32Printer.h"
#include "Ia32CodeGenerator.h"
#include "Dominator.h"
#include <math.h>
namespace Jitrino
{
namespace Ia32
{
using namespace std;
//=========================================================================================================
static void appendToInstList(Inst *& head, Inst * listToAppend) {
if (head==NULL) {
head=listToAppend;
} else if (listToAppend!=NULL){
listToAppend->insertBefore(head);
}
}
//_________________________________________________________________________________________________
const char * newString(MemoryManager& mm, const char * str, U_32 length)
{
assert(str!=NULL);
if (length==EmptyUint32)
length=(U_32)strlen(str);
char * psz=new(mm) char[length+1];
strncpy(psz, str, length);
psz[length]=0;
return psz;
}
//_____________________________________________________________________________________________
IRManager::IRManager(MemoryManager& memManager, TypeManager& tm, MethodDesc& md, CompilationInterface& compIface)
:memoryManager(memManager), typeManager(tm), methodDesc(md), compilationInterface(compIface),
opndId(0), instId(0),
opnds(memManager), gpTotalRegUsage(0), entryPointInst(NULL), _hasLivenessInfo(false),
internalHelperInfos(memManager), infoMap(memManager), verificationLevel(0),
hasCalls(false), hasNonExceptionCalls(false), laidOut(false), codeStartAddr(NULL),
refsCompressed(VMInterface::areReferencesCompressed())
{
for (U_32 i=0; i<lengthof(regOpnds); i++) regOpnds[i]=NULL;
fg = new (memManager) ControlFlowGraph(memManager, this);
fg->setEntryNode(fg->createBlockNode());
fg->setLoopTree(new (memManager) LoopTree(memManager, fg));
initInitialConstraints();
registerInternalHelperInfo("printRuntimeOpndInternalHelper", IRManager::InternalHelperInfo((void*)&printRuntimeOpndInternalHelper, &CallingConvention_STDCALL));
}
//_____________________________________________________________________________________________
void IRManager::addOpnd(Opnd * opnd)
{
assert(opnd->id>=opnds.size());
opnds.push_back(opnd);
opnd->id=(U_32)opnds.size()-1;
}
//_____________________________________________________________________________________________
Opnd * IRManager::newOpnd(Type * type)
{
Opnd * opnd=new(memoryManager) Opnd(opndId++, type, getInitialConstraint(type));
addOpnd(opnd);
return opnd;
}
//_____________________________________________________________________________________________
Opnd * IRManager::newOpnd(Type * type, Constraint c)
{
c.intersectWith(Constraint(OpndKind_Any, getTypeSize(type)));
assert(!c.isNull());
Opnd * opnd=new(memoryManager) Opnd(opndId++, type, c);
addOpnd(opnd);
return opnd;
}
//_____________________________________________________________________________________________
Opnd * IRManager::newImmOpnd(Type * type, int64 immediate)
{
Opnd * opnd = newOpnd(type);
opnd->assignImmValue(immediate);
return opnd;
}
//____________________________________________________________________________________________
Opnd * IRManager::newImmOpnd(Type * type, Opnd::RuntimeInfo::Kind kind, void * arg0, void * arg1, void * arg2, void * arg3)
{
Opnd * opnd=newImmOpnd(type, 0);
opnd->setRuntimeInfo(new(memoryManager) Opnd::RuntimeInfo(kind, arg0, arg1, arg2, arg3));
return opnd;
}
//_____________________________________________________________________________________________
ConstantAreaItem * IRManager::newConstantAreaItem(float f)
{
return new(memoryManager) ConstantAreaItem(
ConstantAreaItem::Kind_FPSingleConstantAreaItem, sizeof(float),
new(memoryManager) float(f)
);
}
//_____________________________________________________________________________________________
ConstantAreaItem * IRManager::newConstantAreaItem(double d)
{
return new(memoryManager) ConstantAreaItem(
ConstantAreaItem::Kind_FPDoubleConstantAreaItem, sizeof(double),
new(memoryManager) double(d)
);
}
//_____________________________________________________________________________________________
ConstantAreaItem * IRManager::newSwitchTableConstantAreaItem(U_32 numTargets)
{
return new(memoryManager) ConstantAreaItem(
ConstantAreaItem::Kind_SwitchTableConstantAreaItem, sizeof(BasicBlock*)*numTargets,
new(memoryManager) BasicBlock*[numTargets]
);
}
//_____________________________________________________________________________________________
ConstantAreaItem * IRManager::newInternalStringConstantAreaItem(const char * str)
{
if (str==NULL)
str="";
return new(memoryManager) ConstantAreaItem(
ConstantAreaItem::Kind_InternalStringConstantAreaItem, (U_32)strlen(str)+1,
(void*)newInternalString(str)
);
}
//_____________________________________________________________________________________________
ConstantAreaItem * IRManager::newBinaryConstantAreaItem(U_32 size, const void * pv)
{
return new(memoryManager) ConstantAreaItem(ConstantAreaItem::Kind_BinaryConstantAreaItem, size, pv);
}
//_____________________________________________________________________________________________
Opnd * IRManager::newFPConstantMemOpnd(float f, Opnd * baseOpnd, BasicBlock* bb)
{
ConstantAreaItem * item=newConstantAreaItem(f);
Opnd * addr=newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getSingleType()), Opnd::RuntimeInfo::Kind_ConstantAreaItem, item);
#ifdef _EM64T_
bb->appendInst(newCopyPseudoInst(Mnemonic_MOV, baseOpnd, addr));
return newMemOpndAutoKind(typeManager.getSingleType(), MemOpndKind_ConstantArea, baseOpnd);
#else
return newMemOpndAutoKind(typeManager.getSingleType(), MemOpndKind_ConstantArea, addr);
#endif
}
//_____________________________________________________________________________________________
Opnd * IRManager::newFPConstantMemOpnd(double d, Opnd * baseOpnd, BasicBlock* bb)
{
ConstantAreaItem * item=newConstantAreaItem(d);
Opnd * addr=newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getDoubleType()), Opnd::RuntimeInfo::Kind_ConstantAreaItem, item);
#ifdef _EM64T_
bb->appendInst(newCopyPseudoInst(Mnemonic_MOV, baseOpnd, addr));
return newMemOpndAutoKind(typeManager.getDoubleType(), MemOpndKind_ConstantArea, baseOpnd);
#else
return newMemOpndAutoKind(typeManager.getDoubleType(), MemOpndKind_ConstantArea, addr);
#endif
}
//_____________________________________________________________________________________________
Opnd * IRManager::newInternalStringConstantImmOpnd(const char * str)
{
ConstantAreaItem * item=newInternalStringConstantAreaItem(str);
return newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getIntPtrType()), Opnd::RuntimeInfo::Kind_ConstantAreaItem, item);
}
//_____________________________________________________________________________________________
Opnd * IRManager::newBinaryConstantImmOpnd(U_32 size, const void * pv)
{
ConstantAreaItem * item=newBinaryConstantAreaItem(size, pv);
return newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getIntPtrType()), Opnd::RuntimeInfo::Kind_ConstantAreaItem, item);
}
//_____________________________________________________________________________________________
SwitchInst * IRManager::newSwitchInst(U_32 numTargets, Opnd * index)
{
assert(numTargets>0);
assert(index!=NULL);
Inst * instList = NULL;
ConstantAreaItem * item=newSwitchTableConstantAreaItem(numTargets);
// This tableAddress in SwitchInst is kept separately [from getOpnd(0)]
// so it allows to replace an Opnd (used in SpillGen) and keep the table
// itself intact.
Opnd * tableAddr=newImmOpnd(typeManager.getIntPtrType(), Opnd::RuntimeInfo::Kind_ConstantAreaItem, item);
#ifndef _EM64T_
Opnd * targetOpnd = newMemOpnd(typeManager.getIntPtrType(),
MemOpndKind_ConstantArea, 0, index, newImmOpnd(typeManager.getInt32Type(), sizeof(POINTER_SIZE_INT)), tableAddr);
#else
// on EM64T immediate displacement cannot be of 64 bit size, so move it to a register first
Opnd * baseOpnd = newOpnd(typeManager.getInt64Type());
appendToInstList(instList, newCopyPseudoInst(Mnemonic_MOV, baseOpnd, tableAddr));
Opnd * targetOpnd = newMemOpnd(typeManager.getUnmanagedPtrType(typeManager.getIntPtrType()),
MemOpndKind_ConstantArea, baseOpnd, index, newImmOpnd(typeManager.getInt32Type(), sizeof(POINTER_SIZE_INT)), 0);
#endif
SwitchInst * inst=new(memoryManager, 1) SwitchInst(Mnemonic_JMP, instId++, tableAddr);
inst->insertOpnd(0, targetOpnd, Inst::OpndRole_Explicit);
inst->assignOpcodeGroup(this);
appendToInstList(instList, inst);
return (SwitchInst *)instList;
}
//_____________________________________________________________________________________________
Opnd * IRManager::newRegOpnd(Type * type, RegName reg)
{
Opnd * opnd = newOpnd(type, Constraint(getRegKind(reg)));
opnd->assignRegName(reg);
return opnd;
}
//_____________________________________________________________________________________________
Opnd * IRManager::newMemOpnd(Type * type, MemOpndKind k, Opnd * base, Opnd * index, Opnd * scale, Opnd * displacement, RegName segReg)
{
Opnd * opnd = newOpnd(type);
opnd->assignMemLocation(k,base,index,scale,displacement);
if (segReg != RegName_Null)
opnd->setSegReg(segReg);
return opnd;
}
//_________________________________________________________________________________________________
Opnd * IRManager::newMemOpnd(Type * type, Opnd * base, Opnd * index, Opnd * scale, Opnd * displacement, RegName segReg)
{
return newMemOpnd(type, MemOpndKind_Heap, base, index, scale, displacement, segReg);
}
//_____________________________________________________________________________________________
Opnd * IRManager::newMemOpnd(Type * type, MemOpndKind k, Opnd * base, I_32 displacement, RegName segReg)
{
return newMemOpnd(type, k, base, 0, 0, newImmOpnd(typeManager.getInt32Type(), displacement), segReg);
}
//_____________________________________________________________________________________________
Opnd * IRManager::newMemOpndAutoKind(Type * type, MemOpndKind k, Opnd * opnd0, Opnd * opnd1, Opnd * opnd2)
{
Opnd * base=NULL, * displacement=NULL;
Constraint c=opnd0->getConstraint(Opnd::ConstraintKind_Current);
if (!(c&OpndKind_GPReg).isNull()){
base=opnd0;
}else if (!(c&OpndKind_Imm).isNull()){
displacement=opnd0;
}else
assert(0);
if (opnd1!=NULL){
c=opnd1->getConstraint(Opnd::ConstraintKind_Current);
if (!(c&OpndKind_GPReg).isNull()){
base=opnd1;
}else if (!(c&OpndKind_Imm).isNull()){
displacement=opnd1;
}else
assert(0);
}
return newMemOpnd(type, k, base, 0, 0, displacement);
}
//_____________________________________________________________________________________________
void IRManager::initInitialConstraints()
{
for (U_32 i=0; i<lengthof(initialConstraints); i++)
initialConstraints[i] = createInitialConstraint((Type::Tag)i);
}
//_____________________________________________________________________________________________
Constraint IRManager::createInitialConstraint(Type::Tag t)const
{
OpndSize sz=getTypeSize(t);
if (t==Type::Single||t==Type::Double||t==Type::Float)
return Constraint(OpndKind_XMMReg, sz)|Constraint(OpndKind_Mem, sz);
if (sz<=Constraint::getDefaultSize(OpndKind_GPReg))
return Constraint(OpndKind_GPReg, sz)|Constraint(OpndKind_Mem, sz)|Constraint(OpndKind_Imm, sz);
if (sz==OpndSize_64)
return Constraint(OpndKind_Mem, sz)|Constraint(OpndKind_Imm, sz); // imm before lowering
return Constraint(OpndKind_Memory, sz);
}
//_____________________________________________________________________________________________
Inst * IRManager::newInst(Mnemonic mnemonic, Opnd * opnd0, Opnd * opnd1, Opnd * opnd2)
{
Inst * inst = new(memoryManager, 4) Inst(mnemonic, instId++, Inst::Form_Native);
U_32 i=0;
Opnd ** opnds = inst->getOpnds();
U_32 * roles = inst->getOpndRoles();
if (opnd0!=NULL){ opnds[i] = opnd0; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd1!=NULL){ opnds[i] = opnd1; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd2!=NULL){ opnds[i] = opnd2; roles[i] = Inst::OpndRole_Explicit; i++;
}}}
inst->opndCount = i;
inst->assignOpcodeGroup(this);
return inst;
}
//_____________________________________________________________________________________________
Inst * IRManager::newInst(Mnemonic mnemonic,
Opnd * opnd0, Opnd * opnd1, Opnd * opnd2, Opnd * opnd3,
Opnd * opnd4, Opnd * opnd5, Opnd * opnd6, Opnd * opnd7
)
{
Inst * inst = new(memoryManager, 8) Inst(mnemonic, instId++, Inst::Form_Native);
U_32 i=0;
Opnd ** opnds = inst->getOpnds();
U_32 * roles = inst->getOpndRoles();
if (opnd0!=NULL){ opnds[i] = opnd0; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd1!=NULL){ opnds[i] = opnd1; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd2!=NULL){ opnds[i] = opnd2; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd3!=NULL){ opnds[i] = opnd3; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd4!=NULL){ opnds[i] = opnd4; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd5!=NULL){ opnds[i] = opnd5; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd6!=NULL){ opnds[i] = opnd6; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd7!=NULL){ opnds[i] = opnd7; roles[i] = Inst::OpndRole_Explicit; i++;
}}}}}}}};
inst->opndCount = i;
inst->assignOpcodeGroup(this);
return inst;
}
//_____________________________________________________________________________________________
Inst * IRManager::newInstEx(Mnemonic mnemonic, U_32 defCount, Opnd * opnd0, Opnd * opnd1, Opnd * opnd2)
{
Inst * inst = new(memoryManager, 4) Inst(mnemonic, instId++, Inst::Form_Extended);
U_32 i=0;
Opnd ** opnds = inst->getOpnds();
U_32 * roles = inst->getOpndRoles();
if (opnd0!=NULL){
opnds[i] = opnd0; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd1!=NULL){
opnds[i] = opnd1; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd2!=NULL){
opnds[i] = opnd2; roles[i] = Inst::OpndRole_Explicit; i++;
}}}
inst->opndCount = i;
inst->defOpndCount=defCount;
inst->assignOpcodeGroup(this);
return inst;
}
//_____________________________________________________________________________________________
Inst * IRManager::newInstEx(Mnemonic mnemonic, U_32 defCount,
Opnd * opnd0, Opnd * opnd1, Opnd * opnd2, Opnd * opnd3,
Opnd * opnd4, Opnd * opnd5, Opnd * opnd6, Opnd * opnd7
)
{
Inst * inst = new(memoryManager, 8) Inst(mnemonic, instId++, Inst::Form_Extended);
U_32 i=0;
Opnd ** opnds = inst->getOpnds();
U_32 * roles = inst->getOpndRoles();
if (opnd0!=NULL){
opnds[i] = opnd0; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd1!=NULL){
opnds[i] = opnd1; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd2!=NULL){
opnds[i] = opnd2; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd3!=NULL){
opnds[i] = opnd3; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd4!=NULL){
opnds[i] = opnd4; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd5!=NULL){
opnds[i] = opnd5; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd6!=NULL){
opnds[i] = opnd6; roles[i] = Inst::OpndRole_Explicit; i++;
if (opnd7!=NULL){
opnds[i] = opnd7; roles[i] = Inst::OpndRole_Explicit; i++;
}}}}}}}};
inst->opndCount = i;
inst->defOpndCount=defCount;
inst->assignOpcodeGroup(this);
return inst;
}
//_________________________________________________________________________________________________
Inst * IRManager::newI8PseudoInst(Mnemonic mnemonic, U_32 defCount,
Opnd * opnd0, Opnd * opnd1, Opnd * opnd2, Opnd * opnd3
)
{
Inst * inst=new (memoryManager, 4) Inst(mnemonic, instId++, Inst::Form_Extended);
inst->kind = Inst::Kind_I8PseudoInst;
U_32 i=0;
Opnd ** opnds = inst->getOpnds();
assert(opnd0->getType()->isInteger() ||opnd0->getType()->isPtr());
if (opnd0!=NULL){ opnds[i] = opnd0; i++;
if (opnd1!=NULL){ opnds[i] = opnd1; i++;
if (opnd2!=NULL){ opnds[i] = opnd2; i++;
if (opnd3!=NULL){ opnds[i] = opnd3; i++;
}}}};
inst->defOpndCount=defCount;
inst->opndCount = i;
inst->assignOpcodeGroup(this);
return inst;
}
//_____________________________________________________________________________________________
SystemExceptionCheckPseudoInst * IRManager::newSystemExceptionCheckPseudoInst(CompilationInterface::SystemExceptionId exceptionId, Opnd * opnd0, Opnd * opnd1, bool checksThisForInlinedMethod)
{
SystemExceptionCheckPseudoInst * inst=new (memoryManager, 8) SystemExceptionCheckPseudoInst(exceptionId, instId++, checksThisForInlinedMethod);
U_32 i=0;
Opnd ** opnds = inst->getOpnds();
if (opnd0!=NULL){ opnds[i++] = opnd0;
if (opnd1!=NULL){ opnds[i++] = opnd1;
}}
inst->opndCount = i;
inst->assignOpcodeGroup(this);
return inst;
}
//_________________________________________________________________________________________________
BranchInst * IRManager::newBranchInst(Mnemonic mnemonic, Node* trueTarget, Node* falseTarget, Opnd * targetOpnd)
{
BranchInst * inst=new(memoryManager, 2) BranchInst(mnemonic, instId++);
if (targetOpnd==0)
targetOpnd=newImmOpnd(typeManager.getInt32Type(), 0);
inst->insertOpnd(0, targetOpnd, Inst::OpndRole_Explicit);
inst->assignOpcodeGroup(this);
inst->setFalseTarget(falseTarget);
inst->setTrueTarget(trueTarget);
return inst;
}
//_________________________________________________________________________________________________
JumpInst * IRManager::newJumpInst(Opnd * targetOpnd)
{
JumpInst * inst=new(memoryManager, 2) JumpInst(instId++);
if (targetOpnd==0) {
targetOpnd=newImmOpnd(typeManager.getInt32Type(), 0);
}
inst->insertOpnd(0, targetOpnd, Inst::OpndRole_Explicit);
inst->assignOpcodeGroup(this);
return inst;
}
//_________________________________________________________________________________________________
EntryPointPseudoInst * IRManager::newEntryPointPseudoInst(const CallingConvention * cc)
{
// there is nothing wrong with calling this method several times.
// it's just a self-check, as the currently assumed behaviour is that this method is invoked only once.
assert(NULL == entryPointInst);
EntryPointPseudoInst * inst=new(memoryManager, methodDesc.getNumParams() * 2) EntryPointPseudoInst(this, instId++, cc);
fg->getEntryNode()->appendInst(inst);
inst->assignOpcodeGroup(this);
entryPointInst = inst;
if (getCompilationInterface().getCompilationParams().exe_notify_method_entry) {
Opnd **hlpArgs = new (memoryManager) Opnd* [1];
hlpArgs[0] = newImmOpnd(typeManager.getIntPtrType(),
Opnd::RuntimeInfo::Kind_MethodRuntimeId, &methodDesc);
Node* prolog = getFlowGraph()->getEntryNode();
prolog->appendInst(newRuntimeHelperCallInst(VM_RT_JVMTI_METHOD_ENTER_CALLBACK,
1, (Opnd**)hlpArgs, NULL));
}
return inst;
}
//_________________________________________________________________________________________________
CallInst * IRManager::newCallInst(Opnd * targetOpnd, const CallingConvention * cc,
U_32 argCount, Opnd ** args, Opnd * retOpnd)
{
CallInst * callInst=new(memoryManager, (argCount + (retOpnd ? 1 : 0)) * 2 + 1) CallInst(this, instId++, cc, targetOpnd->getRuntimeInfo());
CallingConventionClient & ccc = callInst->callingConventionClient;
U_32 i=0;
if (retOpnd!=NULL){
ccc.pushInfo(Inst::OpndRole_Def, retOpnd->getType()->tag);
callInst->insertOpnd(i++, retOpnd, Inst::OpndRole_Auxilary|Inst::OpndRole_Def);
}
callInst->defOpndCount = i;
callInst->insertOpnd(i++, targetOpnd, Inst::OpndRole_Explicit|Inst::OpndRole_Use);
if (argCount>0){
for (U_32 j=0; j<argCount; j++){
ccc.pushInfo(Inst::OpndRole_Use, args[j]->getType()->tag);
callInst->insertOpnd(i++, args[j], Inst::OpndRole_Auxilary|Inst::OpndRole_Use);
}
}
callInst->opndCount = i;
callInst->assignOpcodeGroup(this);
return callInst;
}
//_________________________________________________________________________________________________
CallInst * IRManager::newRuntimeHelperCallInst(VM_RT_SUPPORT helperId,
U_32 numArgs, Opnd ** args, Opnd * retOpnd)
{
Inst * instList = NULL;
Opnd * target=newImmOpnd(typeManager.getInt32Type(), Opnd::RuntimeInfo::Kind_HelperAddress, (void*)helperId);
const CallingConvention * cc=getCallingConvention(helperId);
appendToInstList(instList,newCallInst(target, cc, numArgs, args, retOpnd));
return (CallInst *)instList;
}
//_________________________________________________________________________________________________
CallInst * IRManager::newInternalRuntimeHelperCallInst(const char * internalHelperID, U_32 numArgs, Opnd ** args, Opnd * retOpnd)
{
const InternalHelperInfo * info=getInternalHelperInfo(internalHelperID);
assert(info!=NULL);
Inst * instList = NULL;
Opnd * target=newImmOpnd(typeManager.getInt32Type(), Opnd::RuntimeInfo::Kind_InternalHelperAddress, (void*)newInternalString(internalHelperID));
const CallingConvention * cc=info->callingConvention;
appendToInstList(instList,newCallInst(target, cc, numArgs, args, retOpnd));
return (CallInst *)instList;
}
//_________________________________________________________________________________________________
Inst* IRManager::newEmptyPseudoInst() {
return new(memoryManager, 0) EmptyPseudoInst(instId++);
}
//_________________________________________________________________________________________________
MethodMarkerPseudoInst* IRManager::newMethodEntryPseudoInst(MethodDesc* mDesc) {
return new(memoryManager, 0) MethodMarkerPseudoInst(mDesc, instId++, Inst::Kind_MethodEntryPseudoInst);
}
//_________________________________________________________________________________________________
MethodMarkerPseudoInst* IRManager::newMethodEndPseudoInst(MethodDesc* mDesc) {
return new(memoryManager, 0) MethodMarkerPseudoInst(mDesc, instId++, Inst::Kind_MethodEndPseudoInst);
}
//_________________________________________________________________________________________________
void IRManager::registerInternalHelperInfo(const char * internalHelperID, const InternalHelperInfo& info)
{
assert(internalHelperID!=NULL && internalHelperID[0]!=0);
internalHelperInfos[newInternalString(internalHelperID)]=info;
}
//_________________________________________________________________________________________________
RetInst * IRManager::newRetInst(Opnd * retOpnd)
{
RetInst * retInst=new (memoryManager, 4) RetInst(this, instId++);
assert( NULL != entryPointInst && NULL != entryPointInst->getCallingConventionClient().getCallingConvention() );
retInst->insertOpnd(0, newImmOpnd(typeManager.getInt16Type(), 0), Inst::OpndRole_Explicit|Inst::OpndRole_Use);
if (retOpnd!=NULL){
retInst->insertOpnd(1, retOpnd, Inst::OpndRole_Auxilary|Inst::OpndRole_Use);
retInst->getCallingConventionClient().pushInfo(Inst::OpndRole_Use, retOpnd->getType()->tag);
retInst->opndCount = 2;
} else retInst->opndCount = 1;
retInst->assignOpcodeGroup(this);
return retInst;
}
//_________________________________________________________________________________________________
void IRManager::applyCallingConventions()
{
const Nodes& nodes = fg->getNodes();
for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) {
Node* node = *it;
if (node->isBlockNode()){
for (Inst * inst= (Inst*)node->getFirstInst(); inst!=NULL; inst=inst->getNextInst()){
if (inst->hasKind(Inst::Kind_EntryPointPseudoInst)){
EntryPointPseudoInst * eppi=(EntryPointPseudoInst*)inst;
eppi->callingConventionClient.finalizeInfos(Inst::OpndRole_Def, CallingConvention::ArgKind_InArg);
eppi->callingConventionClient.layoutAuxilaryOpnds(Inst::OpndRole_Def, OpndKind_Memory);
}else if (inst->hasKind(Inst::Kind_CallInst)){
CallInst * callInst=(CallInst*)inst;
callInst->callingConventionClient.finalizeInfos(Inst::OpndRole_Use, CallingConvention::ArgKind_InArg);
callInst->callingConventionClient.layoutAuxilaryOpnds(Inst::OpndRole_Use, OpndKind_Any);
callInst->callingConventionClient.finalizeInfos(Inst::OpndRole_Def, CallingConvention::ArgKind_RetArg);
callInst->callingConventionClient.layoutAuxilaryOpnds(Inst::OpndRole_Def, OpndKind_Null);
}else if (inst->hasKind(Inst::Kind_RetInst)){
RetInst * retInst=(RetInst*)inst;
retInst->callingConventionClient.finalizeInfos(Inst::OpndRole_Use, CallingConvention::ArgKind_RetArg);
retInst->callingConventionClient.layoutAuxilaryOpnds(Inst::OpndRole_Use, OpndKind_Null);
if (retInst->getCallingConventionClient().getCallingConvention()->calleeRestoresStack()){
U_32 stackDepth=getEntryPointInst()->getArgStackDepth();
retInst->getOpnd(0)->assignImmValue(stackDepth);
}
}
}
}
}
}
//_________________________________________________________________________________________________
CatchPseudoInst * IRManager::newCatchPseudoInst(Opnd * exception)
{
CatchPseudoInst * inst=new (memoryManager, 1) CatchPseudoInst(instId++);
inst->insertOpnd(0, exception, Inst::OpndRole_Def);
inst->setConstraint(0, RegName_EAX);
inst->defOpndCount = 1;
inst->opndCount = 1;
inst->assignOpcodeGroup(this);
return inst;
}
//_________________________________________________________________________________________________
GCInfoPseudoInst* IRManager::newGCInfoPseudoInst(const StlVector<Opnd*>& basesAndMptrs) {
#ifdef _DEBUG
for (StlVector<Opnd*>::const_iterator it = basesAndMptrs.begin(), end = basesAndMptrs.end(); it!=end; ++it) {
Opnd* opnd = *it;
assert(opnd->getType()->isObject() || opnd->getType()->isManagedPtr());
}
#endif
GCInfoPseudoInst* inst = new(memoryManager, (U_32)basesAndMptrs.size()) GCInfoPseudoInst(this, instId++);
Opnd ** opnds = inst->getOpnds();
Constraint * constraints = inst->getConstraints();
for (U_32 i = 0, n = (U_32)basesAndMptrs.size(); i < n; i++){
Opnd * opnd = basesAndMptrs[i];
opnds[i] = opnd;
constraints[i] = Constraint(OpndKind_Any, opnd->getSize());
}
inst->opndCount = (U_32)basesAndMptrs.size();
inst->assignOpcodeGroup(this);
return inst;
}
//_________________________________________________________________________________________________
CMPXCHG8BPseudoInst * IRManager::newCMPXCHG8BPseudoInst(Opnd* mem, Opnd* edx, Opnd* eax, Opnd* ecx, Opnd* ebx)
{
CMPXCHG8BPseudoInst* inst = new (memoryManager, 8) CMPXCHG8BPseudoInst(instId++);
Opnd** opnds = inst->getOpnds();
Constraint* opndConstraints = inst->getConstraints();
// we do not set mem as a use in the inst
// just to cheat cg::verifier (see IRManager::verifyOpnds() function)
opnds[0] = mem;
opnds[1] = edx;
opnds[2] = eax;
opnds[3] = getRegOpnd(RegName_EFLAGS);
opnds[4] = edx;
opnds[5] = eax;
opnds[6] = ecx;
opnds[7] = ebx;
opndConstraints[0] = Constraint(OpndKind_Memory, OpndSize_64);
opndConstraints[1] = Constraint(RegName_EDX);
opndConstraints[2] = Constraint(RegName_EAX);
opndConstraints[3] = Constraint(RegName_EFLAGS);
opndConstraints[4] = Constraint(RegName_EDX);
opndConstraints[5] = Constraint(RegName_EAX);
opndConstraints[6] = Constraint(RegName_ECX);
opndConstraints[7] = Constraint(RegName_EBX);
inst->opndCount = 8;
inst->defOpndCount = 4;
inst->assignOpcodeGroup(this);
return inst;
}
//_________________________________________________________________________________________________
Inst * IRManager::newCopyPseudoInst(Mnemonic mn, Opnd * opnd0, Opnd * opnd1)
{
assert(mn==Mnemonic_MOV||mn==Mnemonic_PUSH||mn==Mnemonic_POP);
U_32 allOpndCnt = opnd0->getType()->isInt8() ? 4 : 2;
Inst * inst=new (memoryManager, allOpndCnt) Inst(mn, instId++, Inst::Form_Extended);
inst->kind = Inst::Kind_CopyPseudoInst;
assert(opnd0!=NULL);
assert(opnd1==NULL||opnd0->getSize()<=opnd1->getSize());
Opnd ** opnds = inst->getOpnds();
Constraint * opndConstraints = inst->getConstraints();
opnds[0] = opnd0;
opndConstraints[0] = Constraint(OpndKind_Any, opnd0->getSize());
if (opnd1!=NULL){
opnds[1] = opnd1;
opndConstraints[1] = Constraint(OpndKind_Any, opnd0->getSize());
inst->opndCount = 2;
}else
inst->opndCount = 1;
if (mn != Mnemonic_PUSH)
inst->defOpndCount = 1;
inst->assignOpcodeGroup(this);
return inst;
}
//_________________________________________________________________________________________________
AliasPseudoInst * IRManager::newAliasPseudoInst(Opnd * targetOpnd, Opnd * sourceOpnd, U_32 offset)
{
assert(sourceOpnd->isPlacedIn(OpndKind_Memory));
assert(!targetOpnd->hasAssignedPhysicalLocation());
assert(targetOpnd->canBePlacedIn(OpndKind_Memory));
Type * sourceType=sourceOpnd->getType();
OpndSize sourceSize=getTypeSize(sourceType);
Type * targetType=targetOpnd->getType();
OpndSize targetSize=getTypeSize(targetType);
#ifdef _DEBUG
U_32 sourceByteSize=getByteSize(sourceSize);
U_32 targetByteSize=getByteSize(targetSize);
assert(getByteSize(sourceSize)>0 && getByteSize(targetSize)>0);
assert(offset+targetByteSize<=sourceByteSize);
#endif
U_32 allocOpndNum = sourceOpnd->getType()->isInt8() ? 3 : 2;
AliasPseudoInst * inst=new (memoryManager, allocOpndNum) AliasPseudoInst(instId++);
inst->getOpnds()[0] = targetOpnd;
inst->getConstraints()[0] = Constraint(OpndKind_Mem, targetSize);
inst->getOpnds()[1] = sourceOpnd;
inst->getConstraints()[1] = Constraint(OpndKind_Mem, sourceSize);
if (sourceOpnd->getType()->isInt8()) {
inst->getConstraints()[2] = Constraint(OpndKind_Mem, targetSize);
}
inst->defOpndCount = 1;
inst->opndCount = 2;
inst->offset=offset;
layoutAliasPseudoInstOpnds(inst);
inst->assignOpcodeGroup(this);
return inst;
}
//_________________________________________________________________________________________________
AliasPseudoInst * IRManager::newAliasPseudoInst(Opnd * targetOpnd, U_32 sourceOpndCount, Opnd ** sourceOpnds)
{
assert(targetOpnd->isPlacedIn(OpndKind_Memory));
Type * targetType=targetOpnd->getType();
OpndSize targetSize=getTypeSize(targetType);
assert(getByteSize(targetSize)>0);
U_32 allocOpnNum = 0;
for (U_32 i=0; i<sourceOpndCount; i++) allocOpnNum += getByteSize(getTypeSize(sourceOpnds[i]->getType()));
allocOpnNum += getByteSize(getTypeSize(targetOpnd->getType()));
AliasPseudoInst * inst=new (memoryManager, allocOpnNum) AliasPseudoInst(instId++);
Opnd ** opnds = inst->getOpnds();
Constraint * opndConstraints = inst->getConstraints();
opnds[0] = targetOpnd;
opndConstraints[0] = Constraint(OpndKind_Mem, targetSize);
U_32 offset=0;
for (U_32 i=0; i<sourceOpndCount; i++){
assert(!sourceOpnds[i]->hasAssignedPhysicalLocation() ||
(sourceOpnds[i]->isPlacedIn(OpndKind_Memory) &&
sourceOpnds[i]->getMemOpndKind() == targetOpnd->getMemOpndKind())
);
assert(sourceOpnds[i]->canBePlacedIn(OpndKind_Memory));
Type * sourceType=sourceOpnds[i]->getType();
OpndSize sourceSize=getTypeSize(sourceType);
U_32 sourceByteSize=getByteSize(sourceSize);
assert(sourceByteSize>0);
assert(offset+sourceByteSize<=getByteSize(targetSize));
opnds[1 + i] = sourceOpnds[i];
opndConstraints[1 + i] = Constraint(OpndKind_Mem, sourceSize);
offset+=sourceByteSize;
}
inst->defOpndCount = 1;
inst->opndCount = sourceOpndCount + 1;
layoutAliasPseudoInstOpnds(inst);
inst->assignOpcodeGroup(this);
return inst;
}
//_________________________________________________________________________________________________
void IRManager::layoutAliasPseudoInstOpnds(AliasPseudoInst * inst)
{
assert(inst->getOpndCount(Inst::OpndRole_InstLevel|Inst::OpndRole_Def) == 1);
Opnd * const * opnds = inst->getOpnds();
Opnd * defOpnd=opnds[0];
Opnd * const * useOpnds = opnds + 1;
U_32 useCount = inst->getOpndCount(Inst::OpndRole_InstLevel|Inst::OpndRole_Use);
assert(useCount > 0);
if (inst->offset==EmptyUint32){
U_32 offset=0;
for (U_32 i=0; i<useCount; i++){
Opnd * innerOpnd=useOpnds[i];
assignInnerMemOpnd(defOpnd, innerOpnd, offset);
offset+=getByteSize(innerOpnd->getSize());
}
}else
assignInnerMemOpnd(useOpnds[0], defOpnd, inst->offset);
}
//_________________________________________________________________________________________________
void IRManager::addAliasRelation(AliasRelation * relations, Opnd * outerOpnd, Opnd * innerOpnd, U_32 offset)
{
if (outerOpnd==innerOpnd){
assert(offset==0);
return;
}
const AliasRelation& outerRel=relations[outerOpnd->getId()];
if (outerRel.outerOpnd!=NULL){
addAliasRelation(relations, outerRel.outerOpnd, innerOpnd, outerRel.offset+offset);
return;
}
AliasRelation& innerRel=relations[innerOpnd->getId()];
if (innerRel.outerOpnd!=NULL){
addAliasRelation(relations, outerOpnd, innerRel.outerOpnd, offset-(int)innerRel.offset);
}
#ifdef _DEBUG
Type * outerType=outerOpnd->getType();
OpndSize outerSize=getTypeSize(outerType);
U_32 outerByteSize=getByteSize(outerSize);
assert(offset<outerByteSize);
Type * innerType=innerOpnd->getType();
OpndSize innerSize=getTypeSize(innerType);
U_32 innerByteSize=getByteSize(innerSize);
assert(outerByteSize>0 && innerByteSize>0);
assert(offset+innerByteSize<=outerByteSize);
#endif
innerRel.outerOpnd=outerOpnd;
innerRel.offset=offset;
}
//_________________________________________________________________________________________________
void IRManager::getAliasRelations(AliasRelation * relations)
{
const Nodes& nodes = fg->getNodes();
for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) {
Node* node = *it;
if (node->isBlockNode()) {
for (Inst * inst=(Inst*)node->getFirstInst(); inst!=NULL; inst=inst->getNextInst()) {
if (inst->hasKind(Inst::Kind_AliasPseudoInst)){
AliasPseudoInst * aliasInst=(AliasPseudoInst *)inst;
Opnd * const * opnds = inst->getOpnds();
U_32 useCount = inst->getOpndCount(Inst::OpndRole_InstLevel|Inst::OpndRole_Use);
assert(inst->getOpndCount(Inst::OpndRole_InstLevel|Inst::OpndRole_Def) == 1 && useCount > 0);
Opnd * defOpnd=opnds[0];
Opnd * const * useOpnds = opnds + 1;
if (aliasInst->offset==EmptyUint32){
U_32 offset=0;
for (U_32 i=0; i<useCount; i++){
Opnd * innerOpnd=useOpnds[i];
addAliasRelation(relations, defOpnd, innerOpnd, offset);
offset+=getByteSize(innerOpnd->getSize());
}
}else{
addAliasRelation(relations, useOpnds[0], defOpnd, aliasInst->offset);
}
}
}
}
}
}
//_________________________________________________________________________________________________
void IRManager::layoutAliasOpnds()
{
MemoryManager mm("layoutAliasOpnds");
U_32 opndCount=getOpndCount();
AliasRelation * relations=new (memoryManager) AliasRelation[opndCount];
getAliasRelations(relations);
for (U_32 i=0; i<opndCount; i++){
if (relations[i].outerOpnd!=NULL){
Opnd * innerOpnd=getOpnd(i);
assert(innerOpnd->isPlacedIn(OpndKind_Mem));
assert(relations[i].outerOpnd->isPlacedIn(OpndKind_Mem));
Opnd * innerDispOpnd=innerOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Displacement);
if (innerDispOpnd==NULL){
innerDispOpnd=newImmOpnd(typeManager.getInt32Type(), 0);
innerOpnd->setMemOpndSubOpnd(MemOpndSubOpndKind_Displacement, innerDispOpnd);
}
Opnd * outerDispOpnd=relations[i].outerOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Displacement);
U_32 outerDispValue=(U_32)(outerDispOpnd!=NULL?outerDispOpnd->getImmValue():0);
innerDispOpnd->assignImmValue(outerDispValue+relations[i].offset);
}
}
}
//_________________________________________________________________________________________________
U_32 IRManager::assignInnerMemOpnd(Opnd * outerOpnd, Opnd* innerOpnd, U_32 offset)
{
assert(outerOpnd->isPlacedIn(OpndKind_Memory));
Opnd * outerDisp=outerOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Displacement);
MemOpndKind outerMemOpndKind=outerOpnd->getMemOpndKind();
Opnd::RuntimeInfo * outerDispRI=outerDisp!=NULL?outerDisp->getRuntimeInfo():NULL;
uint64 outerDispValue=outerDisp!=NULL?outerDisp->getImmValue():0;
Opnd * outerBase=outerOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Base);
Opnd * outerIndex=outerOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Index);
Opnd * outerScale=outerOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Scale);
OpndSize innerSize = innerOpnd->getSize();
U_32 innerByteSize = getByteSize(innerSize);
Opnd * innerDisp=newImmOpnd(outerDisp!=NULL?outerDisp->getType():typeManager.getInt32Type(), outerDispValue+offset);
if (outerDispRI){
Opnd::RuntimeInfo * innerDispRI=new(memoryManager)
Opnd::RuntimeInfo(
outerDispRI->getKind(),
outerDispRI->getValue(0),
outerDispRI->getValue(1),
outerDispRI->getValue(2),
outerDispRI->getValue(3),
offset
);
innerDisp->setRuntimeInfo(innerDispRI);
}
innerOpnd->assignMemLocation(outerMemOpndKind, outerBase, outerIndex, outerScale, innerDisp);
return innerByteSize;
}
//_________________________________________________________________________________________________
void IRManager::assignInnerMemOpnds(Opnd * outerOpnd, Opnd** innerOpnds, U_32 innerOpndCount)
{
#ifdef _DEBUG
U_32 outerByteSize = getByteSize(outerOpnd->getSize());
#endif
for (U_32 i=0, offset=0; i<innerOpndCount; i++){
offset+=assignInnerMemOpnd(outerOpnd, innerOpnds[i], offset);
assert(offset<=outerByteSize);
}
}
//_________________________________________________________________________________________________
U_32 getLayoutOpndAlignment(Opnd * opnd)
{
OpndSize size=opnd->getSize();
if (size==OpndSize_80 || size==OpndSize_128)
return 16;
if (size==OpndSize_64)
return 8;
else
return 4;
}
//_________________________________________________________________________________________________
Inst * IRManager::newCopySequence(Mnemonic mn, Opnd * opnd0, Opnd * opnd1, U_32 gpRegUsageMask, U_32 flagsRegUsageMask)
{
if (mn==Mnemonic_MOV)
return newCopySequence(opnd0, opnd1, gpRegUsageMask, flagsRegUsageMask);
else if (mn==Mnemonic_PUSH||mn==Mnemonic_POP)
return newPushPopSequence(mn, opnd0, gpRegUsageMask);
assert(0);
return NULL;
}
//_________________________________________________________________________________________________
Inst * IRManager::newMemMovSequence(Opnd * targetOpnd, Opnd * sourceOpnd, U_32 regUsageMask, bool checkSource)
{
Inst * instList=NULL;
RegName tmpRegName=RegName_Null, unusedTmpRegName=RegName_Null;
bool registerSetNotLocked = !isRegisterSetLocked(OpndKind_GPReg);
#ifdef _EM64T_
for (U_32 reg = RegName_RAX; reg<=RegName_R15/*(U_32)(targetOpnd->getSize()<OpndSize_64?RegName_RBX:RegName_RDI)*/; reg++) {
#else
for (U_32 reg = RegName_EAX; reg<=(U_32)(targetOpnd->getSize()<OpndSize_32?RegName_EBX:RegName_EDI); reg++) {
#endif
RegName regName = (RegName) reg;
if (regName == STACK_REG)
continue;
Opnd * subOpnd = targetOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Base);
if(subOpnd && subOpnd->isPlacedIn(regName))
continue;
subOpnd = targetOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Index);
if(subOpnd && subOpnd->isPlacedIn(regName))
continue;
if (checkSource){
subOpnd = sourceOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Base);
if(subOpnd && subOpnd->isPlacedIn(regName))
continue;
subOpnd = sourceOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Index);
if(subOpnd && subOpnd->isPlacedIn(regName))
continue;
}
tmpRegName=regName;
if (registerSetNotLocked || (getRegMask(tmpRegName)®UsageMask)==0){
unusedTmpRegName=tmpRegName;
break;
}
}
assert(tmpRegName!=RegName_Null);
Opnd * tmp=getRegOpnd(tmpRegName);
Opnd * tmpAdjusted=newRegOpnd(targetOpnd->getType(), tmpRegName);
Opnd * tmpRegStackOpnd = newMemOpnd(tmp->getType(), MemOpndKind_StackAutoLayout, getRegOpnd(STACK_REG), 0);
if (unusedTmpRegName==RegName_Null)
appendToInstList(instList, newInst(Mnemonic_MOV, tmpRegStackOpnd, tmp));
appendToInstList(instList, newInst(Mnemonic_MOV, tmpAdjusted, sourceOpnd)); // must satisfy constraints
appendToInstList(instList, newInst(Mnemonic_MOV, targetOpnd, tmpAdjusted)); // must satisfy constraints
if (unusedTmpRegName==RegName_Null)
appendToInstList(instList, newInst(Mnemonic_MOV, tmp, tmpRegStackOpnd));
return instList;
}
//_________________________________________________________________________________________________
Inst * IRManager::newCopySequence(Opnd * targetBOpnd, Opnd * sourceBOpnd, U_32 regUsageMask, U_32 flagsRegUsageMask)
{
Opnd * targetOpnd=(Opnd*)targetBOpnd, * sourceOpnd=(Opnd*)sourceBOpnd;
Constraint targetConstraint = targetOpnd->getConstraint(Opnd::ConstraintKind_Location);
Constraint sourceConstraint = sourceOpnd->getConstraint(Opnd::ConstraintKind_Location);
if (targetConstraint.isNull() || sourceConstraint.isNull()){
return newCopyPseudoInst(Mnemonic_MOV, targetOpnd, sourceOpnd);
}
OpndSize sourceSize=sourceConstraint.getSize();
U_32 sourceByteSize=getByteSize(sourceSize);
OpndKind targetKind=(OpndKind)targetConstraint.getKind();
OpndKind sourceKind=(OpndKind)sourceConstraint.getKind();
#if defined(_DEBUG) || !defined(_EM64T_)
OpndSize targetSize=targetConstraint.getSize();
assert(targetSize<=sourceSize); // only same size or truncating conversions are allowed
#endif
if (targetKind&OpndKind_Reg) {
if(sourceOpnd->isPlacedIn(OpndKind_Imm) && sourceOpnd->getImmValue()==0 && targetKind==OpndKind_GPReg &&
!sourceOpnd->getRuntimeInfo() && !(getRegMask(RegName_EFLAGS)&flagsRegUsageMask)) {
return newInst(Mnemonic_XOR,targetOpnd, targetOpnd);
}
else if (targetKind==OpndKind_XMMReg && sourceOpnd->getMemOpndKind()==MemOpndKind_ConstantArea) {
#ifdef _EM64T_
Opnd * addr = NULL;
Opnd * base = sourceOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Base);
if(base) {
Inst * defInst = base->getDefiningInst();
if(defInst && defInst->getMnemonic() == Mnemonic_MOV) {
addr = defInst->getOpnd(1);
if(!addr->getRuntimeInfo()) {
// addr opnd may be spilled. Let's try deeper
defInst = addr->getDefiningInst();
if(defInst && defInst->getMnemonic() == Mnemonic_MOV) {
addr = defInst->getOpnd(1);
} else {
addr = NULL;
}
}
}
}
#else
Opnd * addr = sourceOpnd->getMemOpndSubOpnd(MemOpndSubOpndKind_Displacement);
#endif
Opnd::RuntimeInfo* addrRI = addr == NULL ? NULL : addr->getRuntimeInfo();
if( addrRI && addrRI->getKind()==Opnd::RuntimeInfo::Kind_ConstantAreaItem) {
void * fpPtr = (void *)((ConstantAreaItem *)addrRI->getValue(0))->getValue();
if (sourceByteSize==4) {
float val = *(float *)fpPtr;
if(val == 0 && !signbit(val)) {
return newInst(Mnemonic_XORPS,targetOpnd, targetOpnd);
}
}else if (sourceByteSize==8) {
double val = *(double *)fpPtr;
if(val == 0 && !signbit(val)) {
return newInst(Mnemonic_XORPD,targetOpnd, targetOpnd);
}
}
}
}
}
if ( (targetKind==OpndKind_GPReg||targetKind==OpndKind_Mem) &&
(sourceKind==OpndKind_GPReg||sourceKind==OpndKind_Mem||sourceKind==OpndKind_Imm)
){
if (sourceKind==OpndKind_Mem && targetKind==OpndKind_Mem){
Inst * instList=NULL;
#ifndef _EM64T_
U_32 targetByteSize=getByteSize(targetSize);
if (sourceByteSize<=4){
instList=newMemMovSequence(targetOpnd, sourceOpnd, regUsageMask);
}else{
Opnd * targetOpnds[IRMaxOperandByteSize/4]; // limitation because we are currently don't support large memory operands
U_32 targetOpndCount = 0;
for (U_32 cb=0; cb<sourceByteSize && cb<targetByteSize; cb+=4)
targetOpnds[targetOpndCount++] = newOpnd(typeManager.getInt32Type());
AliasPseudoInst * targetAliasInst=newAliasPseudoInst(targetOpnd, targetOpndCount, targetOpnds);
layoutAliasPseudoInstOpnds(targetAliasInst);
for (U_32 cb=0, targetOpndSlotIndex=0; cb<sourceByteSize && cb<targetByteSize; cb+=4, targetOpndSlotIndex++){
Opnd * sourceOpndSlot=newOpnd(typeManager.getInt32Type());
appendToInstList(instList, newAliasPseudoInst(sourceOpndSlot, sourceOpnd, cb));
Opnd * targetOpndSlot=targetOpnds[targetOpndSlotIndex];
appendToInstList(instList, newMemMovSequence(targetOpndSlot, sourceOpndSlot, regUsageMask, true));
}
appendToInstList(instList, targetAliasInst);
}
#else
instList=newMemMovSequence(targetOpnd, sourceOpnd, regUsageMask);
#endif
assert(instList!=NULL);
return instList;
}else{
#ifdef _EM64T_
if((targetOpnd->getMemOpndKind() == MemOpndKind_StackAutoLayout) && (sourceKind==OpndKind_Imm) && (sourceOpnd->getSize() == OpndSize_64))
return newMemMovSequence(targetOpnd, sourceOpnd, regUsageMask, false);
else
#else
assert(sourceByteSize<=4);
#endif
return newInst(Mnemonic_MOV, targetOpnd, sourceOpnd); // must satisfy constraints
}
}else if (
(targetKind==OpndKind_XMMReg||targetKind==OpndKind_Mem) &&
(sourceKind==OpndKind_XMMReg||sourceKind==OpndKind_Mem)
){
targetOpnd->setMemOpndAlignment(Opnd::MemOpndAlignment_16);
sourceOpnd->setMemOpndAlignment(Opnd::MemOpndAlignment_16);
if (sourceByteSize==4){
return newInst(Mnemonic_MOVSS,targetOpnd, sourceOpnd);
}else if (sourceByteSize==8){
bool regsOnly = targetKind==OpndKind_XMMReg && sourceKind==OpndKind_XMMReg;
if (regsOnly && CPUID::isSSE2Supported()) {
return newInst(Mnemonic_MOVAPD, targetOpnd, sourceOpnd);
} else {
return newInst(Mnemonic_MOVSD, targetOpnd, sourceOpnd);
}
}
}else if (targetKind==OpndKind_FPReg && sourceKind==OpndKind_Mem){
sourceOpnd->setMemOpndAlignment(Opnd::MemOpndAlignment_16);
return newInst(Mnemonic_FLD, targetOpnd, sourceOpnd);
}else if (targetKind==OpndKind_Mem && sourceKind==OpndKind_FPReg){
targetOpnd->setMemOpndAlignment(Opnd::MemOpndAlignment_16);
return newInst(Mnemonic_FSTP, targetOpnd, sourceOpnd);
}else if (targetKind==OpndKind_XMMReg && (sourceKind==OpndKind_Mem || sourceKind==OpndKind_GPReg)){
if (sourceKind==OpndKind_Mem)
sourceOpnd->setMemOpndAlignment(Opnd::MemOpndAlignment_16);
return newInst(Mnemonic_MOVD, targetOpnd, sourceOpnd);
}else if ((targetKind==OpndKind_Mem || targetKind==OpndKind_GPReg) && sourceKind==OpndKind_XMMReg){
if (targetKind==OpndKind_Mem)
targetOpnd->setMemOpndAlignment(Opnd::MemOpndAlignment_16);
return newInst(Mnemonic_MOVD, targetOpnd, sourceOpnd);
}else if (
(targetKind==OpndKind_FPReg && sourceKind==OpndKind_XMMReg)||
(targetKind==OpndKind_XMMReg && sourceKind==OpndKind_FPReg)
){
Inst * instList=NULL;
Opnd * tmp = newMemOpnd(targetOpnd->getType(), MemOpndKind_StackAutoLayout, getRegOpnd(STACK_REG), 0);
tmp->setMemOpndAlignment(Opnd::MemOpndAlignment_16);
appendToInstList(instList, newCopySequence(tmp, sourceOpnd, regUsageMask));
appendToInstList(instList, newCopySequence(targetOpnd, tmp, regUsageMask));
return instList;
}
assert(0);
return NULL;
}
//_________________________________________________________________________________________________
Inst * IRManager::newPushPopSequence(Mnemonic mn, Opnd * opnd, U_32 regUsageMask)
{
assert(opnd!=NULL);
Constraint constraint = opnd->getConstraint(Opnd::ConstraintKind_Location);
if (constraint.isNull())
return newCopyPseudoInst(mn, opnd);
OpndKind kind=(OpndKind)constraint.getKind();
OpndSize size=constraint.getSize();
Inst * instList=NULL;
#ifdef _EM64T_
if ( ((kind==OpndKind_GPReg ||kind==OpndKind_Mem)&& size!=OpndSize_32)||(kind==OpndKind_Imm && size<OpndSize_32)){
return newInst(mn, opnd);
#else
if ( kind==OpndKind_GPReg||kind==OpndKind_Mem||kind==OpndKind_Imm ){
if (size==OpndSize_32){
return newInst(mn, opnd);
}else if (size<OpndSize_32){
}else if (size==OpndSize_64){
if (mn==Mnemonic_PUSH){
Opnd * opndLo=newOpnd(typeManager.getUInt32Type());
appendToInstList(instList, newAliasPseudoInst(opndLo, opnd, 0));
Opnd * opndHi=newOpnd(typeManager.getIntPtrType());
appendToInstList(instList, newAliasPseudoInst(opndHi, opnd, 4));
appendToInstList(instList, newInst(Mnemonic_PUSH, opndHi));
appendToInstList(instList, newInst(Mnemonic_PUSH, opndLo));
}else{
Opnd * opnds[2]={ newOpnd(typeManager.getUInt32Type()), newOpnd(typeManager.getInt32Type()) };
appendToInstList(instList, newInst(Mnemonic_POP, opnds[0]));
appendToInstList(instList, newInst(Mnemonic_POP, opnds[1]));
appendToInstList(instList, newAliasPseudoInst(opnd, 2, opnds));
}
return instList;
}
#endif
}
Opnd * espOpnd=getRegOpnd(STACK_REG);
Opnd * tmp=newMemOpnd(opnd->getType(), MemOpndKind_StackManualLayout, espOpnd, 0);
#ifdef _EM64T_
Opnd * sizeOpnd=newImmOpnd(typeManager.getInt32Type(), sizeof(POINTER_SIZE_INT));
if(kind==OpndKind_Imm) {
assert(mn==Mnemonic_PUSH);
appendToInstList(instList, newInst(Mnemonic_SUB, espOpnd, sizeOpnd));
appendToInstList(instList, newMemMovSequence(tmp, opnd, regUsageMask));
} else if (kind == OpndKind_GPReg){
assert(mn==Mnemonic_PUSH);
appendToInstList(instList, newInst(Mnemonic_SUB, espOpnd, sizeOpnd));
appendToInstList(instList, newInst(Mnemonic_MOV, tmp, opnd));
} else {
if (mn==Mnemonic_PUSH){
appendToInstList(instList, newInst(Mnemonic_SUB, espOpnd, sizeOpnd));
appendToInstList(instList, newCopySequence(tmp, opnd, regUsageMask));
}else{
appendToInstList(instList, newCopySequence(opnd, tmp, regUsageMask));
appendToInstList(instList, newInst(Mnemonic_ADD, espOpnd, sizeOpnd));
}
}
#else
U_32 cb=getByteSize(size);
U_32 slotSize=4;
cb=(cb+slotSize-1)&~(slotSize-1);
Opnd * sizeOpnd=newImmOpnd(typeManager.getInt32Type(), cb);
if (mn==Mnemonic_PUSH){
appendToInstList(instList, newInst(Mnemonic_SUB, espOpnd, sizeOpnd));
appendToInstList(instList, newCopySequence(tmp, opnd, regUsageMask));
}else{
appendToInstList(instList, newCopySequence(opnd, tmp, regUsageMask));
appendToInstList(instList, newInst(Mnemonic_ADD, espOpnd, sizeOpnd));
}
#endif
return instList;
}
//_________________________________________________________________________________________________
const CallingConvention * IRManager::getCallingConvention(VM_RT_SUPPORT helperId)const
{
HELPER_CALLING_CONVENTION callConv = compilationInterface.getRuntimeHelperCallingConvention(helperId);
switch (callConv){
case CALLING_CONVENTION_DRL:
return &CallingConvention_Managed;
case CALLING_CONVENTION_STDCALL:
return &CallingConvention_STDCALL;
case CALLING_CONVENTION_CDECL:
return &CallingConvention_CDECL;
case CALLING_CONVENTION_MULTIARRAY:
return &CallingConvention_MultiArray;
default:
assert(0);
return NULL;
}
}
//_________________________________________________________________________________________________
const CallingConvention * IRManager::getCallingConvention(MethodDesc * methodDesc)const
{
return &CallingConvention_Managed;
}
//_________________________________________________________________________________________________
Opnd * IRManager::defArg(Type * type, U_32 position)
{
assert(NULL != entryPointInst);
Opnd * opnd=newOpnd(type);
entryPointInst->insertOpnd(position, opnd, Inst::OpndRole_Auxilary|Inst::OpndRole_Def);
entryPointInst->callingConventionClient.pushInfo(Inst::OpndRole_Def, type->tag);
return opnd;
}
//_________________________________________________________________________________________________
Opnd * IRManager::getRegOpnd(RegName regName)
{
assert(getRegSize(regName)==Constraint::getDefaultSize(getRegKind(regName))); // are we going to change this?
U_32 idx=( (getRegKind(regName) & 0x1f) << 4 ) | ( getRegIndex(regName)&0xf );
if (!regOpnds[idx]){
#ifdef _EM64T_
Type * t = (getRegSize(regName) == OpndSize_64 ? typeManager.getUInt64Type() : typeManager.getUInt32Type());
regOpnds[idx]=newRegOpnd(t, regName);
#else
regOpnds[idx]=newRegOpnd(typeManager.getUInt32Type(), regName);
#endif
}
return regOpnds[idx];
}
void IRManager::calculateTotalRegUsage(OpndKind regKind) {
assert(regKind == OpndKind_GPReg);
U_32 opndCount=getOpndCount();
for (U_32 i=0; i<opndCount; i++){
Opnd * opnd=getOpnd(i);
if (opnd->isPlacedIn(regKind)) {
RegName reg = opnd->getRegName();
unsigned mask = getRegMask(reg);
#if !defined(_EM64T_)
if ((reg == RegName_AH) || (reg == RegName_CH) || (reg == RegName_DH) || (reg == RegName_BH))
mask >>= 4;
#endif
gpTotalRegUsage |= mask;
}
}
}
//_________________________________________________________________________________________________
U_32 IRManager::getTotalRegUsage(OpndKind regKind)const {
return gpTotalRegUsage;
}
//_________________________________________________________________________________________________
bool IRManager::isPreallocatedRegOpnd(Opnd * opnd)
{
RegName regName=opnd->getRegName();
if (regName==RegName_Null || getRegSize(regName)!=Constraint::getDefaultSize(getRegKind(regName)))
return false;
U_32 idx=( (getRegKind(regName) & 0x1f) << 4 ) | ( getRegIndex(regName)&0xf );
return regOpnds[idx]==opnd;
}
//_______________________________________________________________________________________________________________
Type * IRManager::getManagedPtrType(Type * sourceType)
{
return typeManager.getManagedPtrType(sourceType);
}
//_________________________________________________________________________________________________
Type * IRManager::getTypeFromTag(Type::Tag tag)const
{
switch (tag) {
case Type::Void:
case Type::Tau:
case Type::Int8:
case Type::Int16:
case Type::Int32:
case Type::IntPtr:
case Type::Int64:
case Type::UInt8:
case Type::UInt16:
case Type::UInt32:
case Type::UInt64:
case Type::Single:
case Type::Double:
case Type::Boolean:
case Type::Float: return typeManager.getPrimitiveType(tag);
default: return new(memoryManager) Type(tag);
}
}
//_____________________________________________________________________________________________
OpndSize IRManager::getTypeSize(Type::Tag tag)
{
OpndSize size;
switch (tag) {
case Type::Int8:
case Type::UInt8:
case Type::Boolean:
size = OpndSize_8;
break;
case Type::Int16:
case Type::UInt16:
case Type::Char:
size = OpndSize_16;
break;
#ifndef _EM64T_
case Type::IntPtr:
case Type::UIntPtr:
#endif
case Type::Int32:
case Type::UInt32:
size = OpndSize_32;
break;
#ifdef _EM64T_
case Type::IntPtr:
case Type::UIntPtr:
#endif
case Type::Int64:
case Type::UInt64:
size = OpndSize_64;
break;
case Type::Single:
size = OpndSize_32;
break;
case Type::Double:
size = OpndSize_64;
break;
case Type::Float:
size = OpndSize_80;
break;
default:
#ifdef _EM64T_
size = (tag>=Type::CompressedSystemObject && tag<=Type::CompressedVTablePtr)?OpndSize_32:OpndSize_64;
#else
size = OpndSize_32;
#endif
break;
}
return size;
}
//_____________________________________________________________________________________________
void IRManager::indexInsts() {
const Nodes& postOrder = fg->getNodesPostOrder();
U_32 idx=0;
for (Nodes::const_reverse_iterator it = postOrder.rbegin(), end = postOrder.rend(); it!=end; ++it) {
Node* node = *it;
if (node->isBlockNode()){
for (Inst* inst = (Inst*)node->getFirstInst(); inst!=NULL; inst = inst->getNextInst()) {
inst->index=idx++;
}
}
}
}
//_____________________________________________________________________________________________
U_32 IRManager::calculateOpndStatistics(bool reindex)
{
POpnd * arr=&opnds.front();
for (U_32 i=0, n=(U_32)opnds.size(); i<n; i++){
Opnd * opnd=arr[i];
if (opnd==NULL) {
continue;
}
opnd->defScope=Opnd::DefScope_Temporary;
opnd->definingInst=NULL;
opnd->refCount=0;
if (reindex) {
opnd->id=EmptyUint32;
}
}
U_32 index=0;
U_32 instIdx=0;
const Nodes& nodes = fg->getNodesPostOrder();
for (Nodes::const_reverse_iterator it = nodes.rbegin(), end = nodes.rend(); it!=end; ++it) {
Node* node = *it;
if (!node->isBlockNode()) {
continue;
}
I_32 execCount=1;//(I_32)node->getExecCount()*100;
for (Inst * inst=(Inst*)node->getFirstInst(); inst!=NULL; inst=inst->getNextInst()){
inst->index=instIdx++;
for (U_32 i=0, n=inst->getOpndCount(Inst::OpndRole_InstLevel|Inst::OpndRole_UseDef); i<n; i++){
Opnd * opnd=inst->getOpnd(i);
opnd->addRefCount(index, execCount);
if ((inst->getOpndRoles(i)&Inst::OpndRole_Def)!=0){
opnd->setDefiningInst(inst);
}
}
}
}
for (U_32 i=0; i<IRMaxRegNames; i++){ // update predefined regOpnds to prevent losing them from the ID space
if (regOpnds[i]!=NULL) {
regOpnds[i]->addRefCount(index, 1);
}
}
return index;
}
//_____________________________________________________________________________________________
void IRManager::packOpnds()
{
static CountTime packOpndsTimer("ia32::packOpnds");
AutoTimer tm(packOpndsTimer);
_hasLivenessInfo=false;
U_32 maxIndex=calculateOpndStatistics(true);
U_32 opndsBefore=(U_32)opnds.size();
opnds.resize(opnds.size()+maxIndex);
POpnd * arr=&opnds.front();
for (U_32 i=0; i<opndsBefore; i++){
Opnd * opnd=arr[i];
if (opnd->id!=EmptyUint32)
arr[opndsBefore+opnd->id]=opnd;
}
opnds.erase(opnds.begin(), opnds.begin()+opndsBefore);
_hasLivenessInfo=false;
}
//_____________________________________________________________________________________________
void IRManager::fixLivenessInfo( U_32 * map )
{
U_32 opndCount = getOpndCount();
const Nodes& nodes = fg->getNodes();
for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) {
CGNode* node = (CGNode*)*it;
BitSet * ls = node->getLiveAtEntry();
ls->resize(opndCount);
}
}
//_____________________________________________________________________________________________
void IRManager::calculateLivenessInfo()
{
static CountTime livenessTimer("ia32::liveness");
AutoTimer tm(livenessTimer);
_hasLivenessInfo=false;
LoopTree* lt = fg->getLoopTree();
lt->rebuild(false);
const U_32 opndCount = getOpndCount();
const Nodes& nodes = fg->getNodesPostOrder();
//clean all prev. liveness info
for (Nodes::const_iterator it = nodes.begin(),end = nodes.end();it!=end; ++it) {
CGNode* node = (CGNode*)*it;
node->getLiveAtEntry()->resizeClear(opndCount);
}
U_32 loopDepth = lt->getMaxLoopDepth();
U_32 nIterations = loopDepth + 1;
#ifdef _DEBUG
nIterations++; //one more extra iteration to prove that nothing changed
#endif
BitSet tmpLs(memoryManager, opndCount);
bool changed = true;
Node* exitNode = fg->getExitNode();
for (U_32 iteration=0; iteration < nIterations; iteration++) {
changed = false;
for (Nodes::const_iterator it = nodes.begin(),end = nodes.end();it!=end; ++it) {
CGNode* node = (CGNode*)*it;
if (node == exitNode) {
if (!methodDesc.isStatic()
&& (methodDesc.isSynchronized() || methodDesc.isParentClassIsLikelyExceptionType()))
{
BitSet * exitLs = node->getLiveAtEntry();
EntryPointPseudoInst * entryPointInst = getEntryPointInst();
#ifdef _EM64T_
Opnd * thisOpnd = entryPointInst->thisOpnd;
//on EM64T 'this' opnd is spilled to stack only after finalizeCallSites call (copy expansion pass)
//TODO: do it after code selector and tune early propagation and regalloc to skip this opnd from optimizations.
if (thisOpnd == NULL) continue;
#else
Opnd * thisOpnd = entryPointInst->getOpnd(0);
#endif
exitLs->setBit(thisOpnd->getId(), true);
}
continue;
}
bool processNode = true;
if (iteration > 0) {
U_32 depth = lt->getLoopDepth(node);
processNode = iteration <= depth;
#ifdef _DEBUG
processNode = processNode || iteration == nIterations-1; //last iteration will check all blocks
#endif
}
if (processNode) {
getLiveAtExit(node, tmpLs);
if (node->isBlockNode()){
for (Inst * inst=(Inst*)node->getLastInst(); inst!=NULL; inst=inst->getPrevInst()){
updateLiveness(inst, tmpLs);
}
}
BitSet * ls = node->getLiveAtEntry();
if (iteration == 0 || !ls->isEqual(tmpLs)) {
changed = true;
ls->copyFrom(tmpLs);
}
}
}
if (!changed) {
break;
}
}
#ifdef _DEBUG
assert(!changed);
#endif
_hasLivenessInfo=true;
}
//_____________________________________________________________________________________________
bool IRManager::ensureLivenessInfoIsValid() {
return true;
}
//_____________________________________________________________________________________________
void IRManager::getLiveAtExit(const Node * node, BitSet & ls) const
{
assert(ls.getSetSize()<=getOpndCount());
const Edges& edges=node->getOutEdges();
U_32 i=0;
for (Edges::const_iterator ite = edges.begin(), ende = edges.end(); ite!=ende; ++ite, ++i) {
Edge* edge = *ite;
CGNode * succ=(CGNode*)edge->getTargetNode();
const BitSet * succLs=succ->getLiveAtEntry();
if (i==0) {
ls.copyFrom(*succLs);
} else {
ls.unionWith(*succLs);
}
}
}
//_____________________________________________________________________________________________
void IRManager::updateLiveness(const Inst * inst, BitSet & ls) const
{
const Opnd * const * opnds = inst->getOpnds();
U_32 opndCount = inst->getOpndCount();
for (U_32 i = 0; i < opndCount; i++){
const Opnd * opnd = opnds[i];
U_32 id = opnd->getId();
if (inst->isLiveRangeEnd(i))
ls.setBit(id, false);
else if (inst->isLiveRangeStart(i))
ls.setBit(id, true);
}
for (U_32 i = 0; i < opndCount; i++){
const Opnd * opnd = opnds[i];
if (opnd->getMemOpndKind() != MemOpndKind_Null){
const Opnd * const * subOpnds = opnd->getMemOpndSubOpnds();
for (U_32 j = 0; j < MemOpndSubOpndKind_Count; j++){
const Opnd * subOpnd = subOpnds[j];
if (subOpnd != NULL && subOpnd->isSubjectForLivenessAnalysis())
ls.setBit(subOpnd->getId(), true);
}
}
}
}
//_____________________________________________________________________________________________
U_32 IRManager::getRegUsageFromLiveSet(BitSet * ls, OpndKind regKind)const
{
assert(ls->getSetSize()<=getOpndCount());
U_32 mask=0;
BitSet::IterB ib(*ls);
for (int i = ib.getNext(); i != -1; i = ib.getNext()){
Opnd * opnd=getOpnd(i);
if (opnd->isPlacedIn(regKind))
mask |= getRegMask(opnd->getRegName());
}
return mask;
}
//_____________________________________________________________________________________________
void IRManager::getRegUsageAtExit(const Node * node, OpndKind regKind, U_32 & mask)const
{
assert(node->isBlockNode());
const Edges& edges=node->getOutEdges();
mask=0;
for (Edges::const_iterator ite = edges.begin(), ende = edges.end(); ite!=ende; ++ite) {
Edge* edge = *ite;
mask |= getRegUsageAtEntry(edge->getTargetNode(), regKind);
}
}
//_____________________________________________________________________________________________
void IRManager::updateRegUsage(const Inst * inst, OpndKind regKind, U_32 & mask)const
{
Inst::Opnds opnds(inst, Inst::OpndRole_All);
for (Inst::Opnds::iterator it = opnds.begin(); it != opnds.end(); it = opnds.next(it)){
Opnd * opnd=inst->getOpnd(it);
if (opnd->isPlacedIn(regKind)){
U_32 m=getRegMask(opnd->getRegName());
if (inst->isLiveRangeEnd(it))
mask &= ~m;
else if (inst->isLiveRangeStart(it))
mask |= m;
}
}
}
//_____________________________________________________________________________________________
void IRManager::resetOpndConstraints()
{
for (U_32 i=0, n=getOpndCount(); i<n; i++){
Opnd * opnd=getOpnd(i);
opnd->setCalculatedConstraint(opnd->getConstraint(Opnd::ConstraintKind_Initial));
}
}
void IRManager::finalizeCallSites()
{
#ifdef _EM64T_
MethodDesc& md = getMethodDesc();
if (!md.isStatic()
&& (md.isSynchronized() || md.isParentClassIsLikelyExceptionType())) {
Type* thisType = entryPointInst->getOpnd(0)->getType();
entryPointInst->thisOpnd = newMemOpnd(thisType, MemOpndKind_StackAutoLayout, getRegOpnd(STACK_REG), 0);
entryPointInst->getBasicBlock()->appendInst(newCopyPseudoInst(Mnemonic_MOV, entryPointInst->thisOpnd, entryPointInst->getOpnd(0)));
}
#endif
const Nodes& nodes = fg->getNodes();
for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it != end; ++it) {
Node* node = *it;
if (node->isBlockNode()) {
for (Inst * inst = (Inst*)node->getLastInst(), * prevInst = NULL; inst != NULL; inst = prevInst) {
prevInst = inst->getPrevInst();
if (inst->getMnemonic() == Mnemonic_CALL) {
const CallInst * callInst = (const CallInst*)inst;
const CallingConvention * cc =
callInst->getCallingConventionClient().getCallingConvention();
const StlVector<CallingConventionClient::StackOpndInfo>& stackOpndInfos =
callInst->getCallingConventionClient().getStackOpndInfos(Inst::OpndRole_Use);
Inst * instToPrepend = inst;
Opnd * const * opnds = callInst->getOpnds();
unsigned shadowSize = 0;
// Align stack.
if (callInst->getArgStackDepthAlignment() > 0) {
node->prependInst(newInst(Mnemonic_SUB, getRegOpnd(STACK_REG),
newImmOpnd(typeManager.getInt32Type(), callInst->getArgStackDepthAlignment())), inst);
}
// Put inputs on the stack.
for (U_32 i = 0, n = (U_32)stackOpndInfos.size(); i < n; i++) {
Opnd* opnd = opnds[stackOpndInfos[i].opndIndex];
Inst * pushInst = newCopyPseudoInst(Mnemonic_PUSH, opnd);
pushInst->insertBefore(instToPrepend);
instToPrepend = pushInst;
}
#ifdef _WIN64
// Assert that shadow doesn't break stack alignment computed earlier.
assert((shadowSize & (STACK_ALIGNMENT - 1)) == 0);
Opnd::RuntimeInfo * rt = callInst->getRuntimeInfo();
//TODO (Low priority): Strictly speaking we should allocate shadow area for CDECL
// calling convention. Currently it is used in one case only (see VM_RT_MULTIANEWARRAY_RESOLVED).
// But this helper is not aware about shadow area.
if (rt && cc == &CallingConvention_STDCALL) {
// Stack size for parameters: "number of entries is equal to 4 or the maximum number of parameters"
// See http://msdn2.microsoft.com/en-gb/library/ms794596.aspx for details.
// Shadow - is an area on stack reserved to map parameters passed with registers.
shadowSize = 4 * sizeof(POINTER_SIZE_INT);
node->prependInst(newInst(Mnemonic_SUB, getRegOpnd(STACK_REG), newImmOpnd(typeManager.getInt32Type(), shadowSize)), inst);
}
#endif
unsigned stackPopSize = cc->calleeRestoresStack() ? 0 : callInst->getArgStackDepth();
stackPopSize += shadowSize;
// Restore stack pointer.
if(stackPopSize != 0) {
Inst* newIns = newInst(Mnemonic_ADD, getRegOpnd(STACK_REG), newImmOpnd(typeManager.getInt32Type(), stackPopSize));
newIns->insertAfter(inst);
}
}
}
}
}
}
//_____________________________________________________________________________________________
U_32 IRManager::calculateStackDepth()
{
MemoryManager mm("calculateStackDepth");
StlVector<I_32> stackDepths(mm, fg->getNodeCount(), -1);
I_32 maxMethodStackDepth = -1;
const Nodes& nodes = fg->getNodesPostOrder();
//iterating in topological (reverse postorder) order
for (Nodes::const_reverse_iterator itn = nodes.rbegin(), endn = nodes.rend(); itn!=endn; ++itn) {
Node* node = *itn;
if (node->isBlockNode() || (node->isDispatchNode() && node!=fg->getUnwindNode())) {
I_32 stackDepth=-1;
const Edges& edges=node->getInEdges();
for (Edges::const_iterator ite = edges.begin(), ende = edges.end(); ite!=ende; ++ite) {
Edge* edge = *ite;
Node * pred=edge->getSourceNode();
I_32 predStackDepth=stackDepths[pred->getDfNum()];
if (predStackDepth>=0){
assert(stackDepth==-1 || stackDepth==predStackDepth);
stackDepth=predStackDepth;
}
}
if (stackDepth<0) {
stackDepth=0;
}
if (node->isBlockNode()){
for (Inst * inst=(Inst*)node->getFirstInst(); inst!=NULL; inst=inst->getNextInst()){
inst->setStackDepth(stackDepth);
Inst::Opnds opnds(inst, Inst::OpndRole_Explicit | Inst::OpndRole_Auxilary | Inst::OpndRole_UseDef);
Inst::Opnds::iterator it = opnds.begin();
if (it != opnds.end() && inst->getOpnd(it)->isPlacedIn(STACK_REG)) {
if (inst->getMnemonic()==Mnemonic_ADD)
stackDepth -= (I_32)inst->getOpnd(opnds.next(it))->getImmValue();
else if (inst->getMnemonic()==Mnemonic_SUB)
stackDepth += (I_32)inst->getOpnd(opnds.next(it))->getImmValue();
else
assert(0);
}else{
if(inst->getMnemonic()==Mnemonic_PUSH) {
stackDepth+=getByteSize(inst->getOpnd(it)->getSize());
} else if (inst->getMnemonic() == Mnemonic_POP) {
stackDepth-=getByteSize(inst->getOpnd(it)->getSize());
} else if (inst->getMnemonic() == Mnemonic_PUSHFD) {
stackDepth+=sizeof(POINTER_SIZE_INT);
} else if (inst->getMnemonic() == Mnemonic_POPFD) {
stackDepth-=sizeof(POINTER_SIZE_INT);
} else if (inst->getMnemonic() == Mnemonic_CALL && ((CallInst *)inst)->getCallingConventionClient().getCallingConvention()->calleeRestoresStack()) {
stackDepth -= ((CallInst *)inst)->getArgStackDepth();
}
}
maxMethodStackDepth = std::max(maxMethodStackDepth, stackDepth);
}
assert(stackDepth>=0);
}
stackDepths[node->getDfNum()]=stackDepth;
}
}
assert(maxMethodStackDepth>=0);
return (U_32)maxMethodStackDepth;
}
//_____________________________________________________________________________________________
bool IRManager::isOnlyPrologSuccessor(Node * bb) {
Node * predBB = bb;
for(; ; ) {
if(predBB == fg->getEntryNode()) {
return true;
}
if (predBB != bb && predBB->getOutDegree() > 1) {
return false;
}
if (predBB->getInDegree() > 1) {
return false;
}
predBB = predBB->getInEdges().front()->getSourceNode();
}
}
//_____________________________________________________________________________________________
void IRManager::expandSystemExceptions(U_32 reservedForFlags)
{
calculateOpndStatistics();
StlMap<Opnd *, POINTER_SIZE_INT> checkOpnds(getMemoryManager());
StlVector<Inst *> excInsts(memoryManager);
const Nodes& nodes = fg->getNodes();
for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) {
Node* node = *it;
if (node->isBlockNode()){
Inst * inst=(Inst*)node->getLastInst();
if (inst && inst->hasKind(Inst::Kind_SystemExceptionCheckPseudoInst)) {
excInsts.push_back(inst);
Node* dispatchNode = node->getExceptionEdgeTarget();
if (dispatchNode==NULL || dispatchNode==fg->getUnwindNode()) {
checkOpnds[inst->getOpnd(0)] =
((SystemExceptionCheckPseudoInst*)inst)->checksThisOfInlinedMethod() ?
(POINTER_SIZE_INT)-1:
(POINTER_SIZE_INT)inst;
}
}
if(checkOpnds.size() == 0)
continue;
for (inst=(Inst*)node->getFirstInst(); inst!=NULL; inst = inst->getNextInst()){
if (inst->getMnemonic() == Mnemonic_CALL && !inst->hasKind(Inst::Kind_SystemExceptionCheckPseudoInst) && ((CallInst *)inst)->isDirect()) {
Opnd::RuntimeInfo * rt = inst->getOpnd(((ControlTransferInst*)inst)->getTargetOpndIndex())->getRuntimeInfo();
if(rt->getKind() == Opnd::RuntimeInfo::Kind_MethodDirectAddr && !((MethodDesc *)rt->getValue(0))->isStatic()) {
Inst::Opnds opnds(inst, Inst::OpndRole_Auxilary | Inst::OpndRole_Use);
for (Inst::Opnds::iterator it = opnds.begin(); it != opnds.end(); it = opnds.next(it)){
Opnd * opnd = inst->getOpnd(it);
if(checkOpnds.find(opnd) != checkOpnds.end())
checkOpnds[opnd] = (POINTER_SIZE_INT)-1;
}
}
}
}
}
}
for(StlVector<Inst *>::iterator it = excInsts.begin(); it != excInsts.end(); it++) {
Inst * lastInst = *it;
Node* bb = lastInst->getNode();
switch (((SystemExceptionCheckPseudoInst*)lastInst)->getExceptionId()){
case CompilationInterface::Exception_NullPointer:
{
Node* oldTarget = bb->getUnconditionalEdge()->getTargetNode(); //must exist
Opnd * opnd = lastInst->getOpnd(0);
Edge* dispatchEdge = bb->getExceptionEdge();
assert(dispatchEdge!=NULL);
Node* dispatchNode= dispatchEdge->getTargetNode();
if ((dispatchNode!=fg->getUnwindNode()) ||(checkOpnds[opnd] == (POINTER_SIZE_INT)-1
#ifdef _EM64T_
||!Type::isCompressedReference(opnd->getType()->tag)
#endif
)){
Node* throwBasicBlock = fg->createBlockNode();
ObjectType* excType = compilationInterface.findClassUsingBootstrapClassloader(NULL_POINTER_EXCEPTION);
assert(lastInst->getBCOffset()!=ILLEGAL_BC_MAPPING_VALUE);
throwException(excType, lastInst->getBCOffset(), throwBasicBlock);
//Inst* throwInst = newRuntimeHelperCallInst(VM_RT_NULL_PTR_EXCEPTION, 0, NULL, NULL);
//throwInst->setBCOffset(lastInst->getBCOffset());
//throwBasicBlock->appendInst(throwInst);
int64 zero = 0;
if( refsCompressed && opnd->getType()->isReference() ) {
assert(!Type::isCompressedReference(opnd->getType()->tag));
zero = (int64)(POINTER_SIZE_INT)VMInterface::getHeapBase();
}
Opnd* zeroOpnd = NULL;
if((POINTER_SIZE_INT)zero == (U_32)zero) { // heap base fits into 32 bits
zeroOpnd = newImmOpnd(opnd->getType(), zero);
} else { // zero can not be an immediate at comparison
Opnd* zeroImm = newImmOpnd(typeManager.getIntPtrType(), zero);
zeroOpnd = newOpnd(opnd->getType());
Inst* copy = newCopyPseudoInst(Mnemonic_MOV, zeroOpnd, zeroImm);
bb->appendInst(copy);
copy->setBCOffset(lastInst->getBCOffset());
}
Inst* cmpInst = newInst(Mnemonic_CMP, opnd, zeroOpnd);
bb->appendInst(cmpInst);
cmpInst->setBCOffset(lastInst->getBCOffset());
bb->appendInst(newBranchInst(Mnemonic_JZ, throwBasicBlock, oldTarget));
fg->addEdge(bb, throwBasicBlock, 0);
assert(dispatchNode!=NULL);
fg->addEdge(throwBasicBlock, dispatchNode, 1);
if((checkOpnds[opnd] == (POINTER_SIZE_INT)-1) && (opnd->getDefScope() == Opnd::DefScope_Temporary) && isOnlyPrologSuccessor(bb)) {
checkOpnds[opnd] = (POINTER_SIZE_INT)lastInst;
}
} else { //hardware exception handling
if (bb->getFirstInst() == lastInst) {
fg->removeEdge(dispatchEdge);
}
}
break;
}
default:
assert(0);
}
lastInst->unlink();
}
}
void IRManager::throwException(ObjectType* excType, uint16 bcOffset, Node* basicBlock){
assert(excType);
#ifdef _EM64T_
bool lazy = false;
#else
bool lazy = true;
#endif
Inst* throwInst = NULL;
assert(bcOffset!=ILLEGAL_BC_MAPPING_VALUE);
if (lazy){
Opnd * helperOpnds[] = {
// first parameter exception class
newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getIntPtrType()),
Opnd::RuntimeInfo::Kind_TypeRuntimeId, excType),
// second is constructor method handle, 0 - means default constructor
newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getIntPtrType()), 0)
};
throwInst=newRuntimeHelperCallInst(
VM_RT_THROW_LAZY, lengthof(helperOpnds), helperOpnds, NULL);
} else {
Opnd * helperOpnds1[] = {
newImmOpnd(typeManager.getInt32Type(), Opnd::RuntimeInfo::Kind_Size, excType),
newImmOpnd(typeManager.getUnmanagedPtrType(typeManager.getIntPtrType()),
Opnd::RuntimeInfo::Kind_AllocationHandle, excType)
};
Opnd * retOpnd=newOpnd(excType);
CallInst * callInst=newRuntimeHelperCallInst(
VM_RT_NEW_RESOLVED_USING_VTABLE_AND_SIZE,
lengthof(helperOpnds1), helperOpnds1, retOpnd);
callInst->setBCOffset(bcOffset);
basicBlock->appendInst(callInst);
MethodDesc* md = compilationInterface.resolveMethod( excType,
DEFAUlT_COSTRUCTOR_NAME, DEFAUlT_COSTRUCTOR_DESCRIPTOR);
Opnd * target = newImmOpnd(typeManager.getIntPtrType(), Opnd::RuntimeInfo::Kind_MethodDirectAddr, md);
Opnd * helperOpnds2[] = { (Opnd*)retOpnd };
callInst=newCallInst(target, getDefaultManagedCallingConvention(),
lengthof(helperOpnds2), helperOpnds2, NULL);
callInst->setBCOffset(bcOffset);
basicBlock->appendInst(callInst);
Opnd * helperOpnds3[] = { (Opnd*)retOpnd };
throwInst=newRuntimeHelperCallInst(
VM_RT_THROW,
lengthof(helperOpnds3), helperOpnds3, NULL);
}
throwInst->setBCOffset(bcOffset);
basicBlock->appendInst(throwInst);
}
//_____________________________________________________________________________________________
void IRManager::translateToNativeForm()
{
const Nodes& nodes = fg->getNodes();
for (Nodes::const_iterator it = nodes.begin(),end = nodes.end();it!=end; ++it) {
Node* node = *it;
if (node->isBlockNode()){
for (Inst * inst=(Inst*)node->getFirstInst(); inst!=NULL; inst=inst->getNextInst()){
if (inst->getForm()==Inst::Form_Extended) {
inst->makeNative(this);
}
}
}
}
}
//_____________________________________________________________________________________________
void IRManager::eliminateSameOpndMoves()
{
const Nodes& nodes = fg->getNodes();
for (Nodes::const_iterator it = nodes.begin(),end = nodes.end();it!=end; ++it) {
Node* node = *it;
if (node->isBlockNode()){
for (Inst * inst=(Inst*)node->getFirstInst(), *nextInst=NULL; inst!=NULL; inst=nextInst){
nextInst=inst->getNextInst();
if (inst->getMnemonic()==Mnemonic_MOV && inst->getOpnd(0)==inst->getOpnd(1)) {
inst->unlink();
}
}
}
}
}
//_____________________________________________________________________________________________
void IRManager::resolveRuntimeInfo()
{
for (U_32 i=0, n=getOpndCount(); i<n; i++){
Opnd * opnd=getOpnd(i);
resolveRuntimeInfo(opnd);
}
}
void IRManager::resolveRuntimeInfo(Opnd* opnd) const {
if (!opnd->isPlacedIn(OpndKind_Imm))
return;
Opnd::RuntimeInfo * info=opnd->getRuntimeInfo();
if (info==NULL)
return;
int64 value=0;
switch(info->getKind()){
case Opnd::RuntimeInfo::Kind_HelperAddress:
/** The value of the operand is compilationInterface->getRuntimeHelperAddress */
value=(POINTER_SIZE_INT)compilationInterface.getRuntimeHelperAddress(
(VM_RT_SUPPORT)(POINTER_SIZE_INT)info->getValue(0)
);
assert(value!=0);
break;
case Opnd::RuntimeInfo::Kind_InternalHelperAddress:
/** The value of the operand is irManager.getInternalHelperInfo((const char*)[0]).pfn */
value=(POINTER_SIZE_INT)getInternalHelperInfo((const char*)info->getValue(0))->pfn;
assert(value!=0);
break;
case Opnd::RuntimeInfo::Kind_TypeRuntimeId:
/* The value of the operand is [0]->ObjectType::getRuntimeIdentifier() */
value=(POINTER_SIZE_INT)((NamedType*)info->getValue(0))->getRuntimeIdentifier();
break;
case Opnd::RuntimeInfo::Kind_MethodRuntimeId:
value=(POINTER_SIZE_INT)((MethodDesc*)info->getValue(0))->getMethodHandle();
break;
case Opnd::RuntimeInfo::Kind_AllocationHandle:
/* The value of the operand is [0]->ObjectType::getAllocationHandle() */
value=(POINTER_SIZE_INT)((ObjectType*)info->getValue(0))->getAllocationHandle();
break;
case Opnd::RuntimeInfo::Kind_StringDescription:
/* [0] - Type * - the containing class, [1] - string token */
assert(0);
break;
case Opnd::RuntimeInfo::Kind_Size:
/* The value of the operand is [0]->ObjectType::getObjectSize() */
value=(POINTER_SIZE_INT)((ObjectType*)info->getValue(0))->getObjectSize();
break;
case Opnd::RuntimeInfo::Kind_StringAddress:
/** The value of the operand is the address where the interned version of the string is stored*/
{
MethodDesc* mDesc = (MethodDesc*)info->getValue(0);
U_32 token = (U_32)(POINTER_SIZE_INT)info->getValue(1);
value = (POINTER_SIZE_INT) compilationInterface.getStringInternAddr(mDesc,token);
}break;
case Opnd::RuntimeInfo::Kind_StaticFieldAddress:
/** The value of the operand is [0]->FieldDesc::getAddress() */
value=(POINTER_SIZE_INT)((FieldDesc*)info->getValue(0))->getAddress();
break;
case Opnd::RuntimeInfo::Kind_FieldOffset:
/** The value of the operand is [0]->FieldDesc::getOffset() */
value=(POINTER_SIZE_INT)((FieldDesc*)info->getValue(0))->getOffset();
break;
case Opnd::RuntimeInfo::Kind_VTableAddrOffset:
/** The value of the operand is compilationInterface.getVTableOffset(), zero args */
value = (int64)VMInterface::getVTableOffset();
break;
case Opnd::RuntimeInfo::Kind_VTableConstantAddr:
/** The value of the operand is [0]->ObjectType::getVTable() */
value=(POINTER_SIZE_INT)((ObjectType*)info->getValue(0))->getVTable();
break;
case Opnd::RuntimeInfo::Kind_MethodVtableSlotOffset:
/** The value of the operand is [0]->MethodDesc::getOffset() */
value=(POINTER_SIZE_INT)((MethodDesc*)info->getValue(0))->getOffset();
break;
case Opnd::RuntimeInfo::Kind_MethodIndirectAddr:
/** The value of the operand is [0]->MethodDesc::getIndirectAddress() */
value=(POINTER_SIZE_INT)((MethodDesc*)info->getValue(0))->getIndirectAddress();
break;
case Opnd::RuntimeInfo::Kind_MethodDirectAddr:
/** The value of the operand is *[0]->MethodDesc::getIndirectAddress() */
value=*(POINTER_SIZE_INT*)((MethodDesc*)info->getValue(0))->getIndirectAddress();
break;
case Opnd::RuntimeInfo::Kind_ConstantAreaItem:
/** The value of the operand is address of constant pool item ((ConstantPoolItem*)[0])->getAddress() */
value=(POINTER_SIZE_INT)((ConstantAreaItem*)info->getValue(0))->getAddress();
break;
case Opnd::RuntimeInfo::Kind_EM_ProfileAccessInterface:
/** The value of the operand is a pointer to the EM_ProfileAccessInterface */
value=(POINTER_SIZE_INT)(getProfilingInterface()->getEMProfileAccessInterface());
break;
case Opnd::RuntimeInfo::Kind_Method_Value_Profile_Handle:
/** The value of the operand is Method_Profile_Handle for the value profile of the compiled method */
value=(POINTER_SIZE_INT)(getProfilingInterface()->getMethodProfileHandle(ProfileType_Value, getMethodDesc()));
break;
default:
assert(0);
}
opnd->assignImmValue(value+info->getAdditionalOffset());
}
//_____________________________________________________________________________________________
bool IRManager::verify()
{
if (!verifyOpnds())
return false;
updateLivenessInfo();
if (!verifyLiveness())
return false;
if (!verifyHeapAddressTypes())
return false;
#ifdef _DEBUG
//check unwind node;
Node* unwind = fg->getUnwindNode();
Node* exit = fg->getExitNode();
assert(exit!=NULL);
assert(unwind == NULL || (unwind->getOutDegree() == 1 && unwind->isConnectedTo(true, exit)));
const Edges& exitInEdges = exit->getInEdges();
for (Edges::const_iterator ite = exitInEdges.begin(), ende = exitInEdges.end(); ite!=ende; ++ite) {
Edge* edge = *ite;
Node* source = edge->getSourceNode();
assert(source == unwind || source->isBlockNode());
}
const Nodes& nodes = fg->getNodesPostOrder();//check only reachable nodes.
for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) {
CGNode* node = (CGNode*)*it;
node->verify();
}
#endif
return true;
}
//_____________________________________________________________________________________________
//
// This routine checks that every memory heap operand is referenced by single instruction only.
//
// There are two kinds of operands - instruction-level, which are saved in Ia32::Inst structure,
// and sub-operands (of instruction-level operands), which are saved in Ia32::Opnd structure.
// Of course, not all instruction-level operands have sub-operands.
//
// With this design, it would be impossible to replace sub-operand in one instruction without
// affecting all other instructions that reference the same instruction-level operand of which
// the sub-operand is part of.
//
// For some codegen modules (SpillGen, ConstraintResolver) it is critically important to be able
// to replace operand (Inst::replaceOpnd) in one instruction, without side-effect on all other
// instruction. More specifically, only heap operands are manipulated in such way.
//
// NOTE
// For some obscure reason, AliasPseudoInst violates this principle, but experiments show
// that AliasPseudoInst can be ignored. Otherwise, massive errors from this instruction
// make the check meanigless.
//
bool IRManager::verifyOpnds() const
{
bool ok = true;
typedef StlVector<Inst*> InstList; // to register all instruction referenced an operand
typedef StlVector<InstList*> OpndList; // one entry for each operand, instruction register or 0
const U_32 opnd_count = getOpndCount();
OpndList opnd_list(getMemoryManager(), opnd_count); // fixed size
// Watch only MemOpndKind_Heap operands - all others are simply ignored.
for (U_32 i = 0; i != opnd_count; ++i) {
InstList* ilp = 0;
if (getOpnd(i)->getMemOpndKind() == MemOpndKind_Heap)
ilp = new (getMemoryManager()) InstList(getMemoryManager());
opnd_list[i] = ilp;
}
const Nodes& nodes = fg->getNodes();
for (Nodes::const_iterator nd = nodes.begin(), nd_end = nodes.end(); nd != nd_end; ++nd) {
Node* node = *nd;
if (node->isBlockNode()) {
for (Inst* inst = (Inst*)node->getFirstInst(); inst != NULL; inst = inst->getNextInst())
if (!inst->hasKind(Inst::Kind_AliasPseudoInst)) {
// Inspect instruction-level operand only (but all of them), ignore sub-operands.
Inst::Opnds opnds(inst, Inst::OpndRole_InstLevel | Inst::OpndRole_UseDef);
for (Inst::Opnds::iterator op = opnds.begin(), op_end = opnds.end(); op != op_end; op = opnds.next(op)) {
Opnd* opnd = opnds.getOpnd(op);
// If this is a watched operand, then register the instruction that referenced it.
InstList* ilp = opnd_list.at(opnd->getId());
if (ilp != 0)
ilp->push_back(inst);
}
}
}
}
for (U_32 i = 0; i != opnd_count; ++i) {
InstList* ilp = opnd_list.at(i);
if (ilp != 0 && ilp->size() > 1) {
// Error found
ok = false;
VERIFY_OUT("MemOpnd " << getOpnd(i) << " was referenced in the instructions:");
for (InstList::iterator it = ilp->begin(), end = ilp->end(); it != end; ++it) {
Inst* inst = *it;
VERIFY_OUT(" I" << inst->getId());
}
VERIFY_OUT(std::endl);
}
}
return ok;
}
//_____________________________________________________________________________________________
bool IRManager::verifyLiveness()
{
Node* prolog=fg->getEntryNode();
bool failed=false;
BitSet * ls=getLiveAtEntry(prolog);
assert(ls!=NULL);
Constraint calleeSaveRegs=getCallingConvention()->getCalleeSavedRegs(OpndKind_GPReg);
BitSet::IterB lives(*ls);
for (int i = lives.getNext(); i != -1; i = lives.getNext()){
Opnd * opnd=getOpnd(i);
assert(opnd!=NULL);
if (
opnd->isSubjectForLivenessAnalysis() &&
(opnd->isPlacedIn(RegName_EFLAGS)||!isPreallocatedRegOpnd(opnd))
){
VERIFY_OUT("Operand live at entry: " << opnd << ::std::endl);
VERIFY_OUT("This means there is a use of the operand when it is not yet defined" << ::std::endl);
failed=true;
};
}
if (failed)
VERIFY_OUT(::std::endl << "Liveness verification failure" << ::std::endl);
return !failed;
}
//_____________________________________________________________________________________________
bool IRManager::verifyHeapAddressTypes()
{
bool failed=false;
for (U_32 i=0, n=getOpndCount(); i<n; i++){
Opnd * opnd = getOpnd(i);
if (opnd->isPlacedIn(OpndKind_Mem) && opnd->getMemOpndKind()==MemOpndKind_Heap){
Opnd * properTypeSubOpnd=NULL;
for (U_32 j=0; j<MemOpndSubOpndKind_Count; j++){
Opnd * subOpnd=opnd->getMemOpndSubOpnd((MemOpndSubOpndKind)j);
if (subOpnd!=NULL){
Type * type=subOpnd->getType();
if (type->isManagedPtr() || type->isObject() || type->isMethodPtr() || type->isVTablePtr() || type->isUnmanagedPtr()
#ifdef _EM64T_
|| subOpnd->getRegName() == RegName_RSP/*SOE handler*/
#else
|| subOpnd->getRegName() == RegName_ESP/*SOE handler*/
#endif
){
if (properTypeSubOpnd!=NULL){
VERIFY_OUT("Heap operand " << opnd << " contains more than 1 sub-operands of type Object or ManagedPointer "<<::std::endl);
VERIFY_OUT("Opnd 1: " << properTypeSubOpnd << ::std::endl);
VERIFY_OUT("Opnd 2: " << subOpnd << ::std::endl);
failed=true;
break;
}
properTypeSubOpnd=subOpnd;
}
}
}
if (failed)
break;
if (properTypeSubOpnd==NULL){
VERIFY_OUT("Heap operand " << opnd << " contains no sub-operands of type Object or ManagedPointer "<<::std::endl);
failed=true;
break;
}
}
}
if (failed)
VERIFY_OUT(::std::endl << "Heap address type verification failure" << ::std::endl);
return !failed;
}
ControlFlowGraph* IRManager::createSubCFG(bool withReturn, bool withUnwind) {
ControlFlowGraph* cfg = new (memoryManager) ControlFlowGraph(memoryManager, this);
cfg->setEntryNode(cfg->createBlockNode());
cfg->setExitNode(cfg->createExitNode());
if (withReturn) {
cfg->setReturnNode(cfg->createBlockNode());
cfg->addEdge(cfg->getReturnNode(), cfg->getExitNode(), 1);
}
if (withUnwind) {
cfg->setUnwindNode(cfg->createDispatchNode());
cfg->addEdge(cfg->getUnwindNode(), cfg->getExitNode(), 1);
}
return cfg;
}
// factory method for ControlFlowGraph
Node* IRManager::createNode(MemoryManager& mm, Node::Kind kind) {
if (kind == Node::Kind_Block) {
return new (mm) BasicBlock(mm, *this);
}
return new (mm) CGNode(mm, *this, kind);
}
// factory method for ControlFlowGraph
Edge* IRManager::createEdge(MemoryManager& mm, Node::Kind srcKind, Node::Kind dstKind) {
if (srcKind == Node::Kind_Dispatch && dstKind == Node::Kind_Block) {
return new (mm) CatchEdge();
}
return ControlFlowGraphFactory::createEdge(mm, srcKind, dstKind);
}
bool IRManager::isGCSafePoint(const Inst* inst) {
if (inst->getMnemonic() == Mnemonic_CALL) {
const CallInst* callInst = (const CallInst*)inst;
Opnd::RuntimeInfo * rt = callInst->getRuntimeInfo();
bool isInternalHelper = rt && rt->getKind() == Opnd::RuntimeInfo::Kind_InternalHelperAddress;
bool isNonGCVMHelper = false;
if (!isInternalHelper) {
CompilationInterface* ci = CompilationContext::getCurrentContext()->getVMCompilationInterface();
isNonGCVMHelper = rt && rt->getKind() == Opnd::RuntimeInfo::Kind_HelperAddress
&& !ci->mayBeInterruptible((VM_RT_SUPPORT)(POINTER_SIZE_INT)rt->getValue(0));
}
bool isGCPoint = !isInternalHelper && !isNonGCVMHelper;
return isGCPoint;
}
return false;
}
//=============================================================================================
// class Ia32::SessionAction implementation
//=============================================================================================
void SessionAction::run()
{
irManager = &getIRManager();
stageId=Log::getStageId();
if (isLogEnabled(LogStream::IRDUMP))
Log::printStageBegin(log(LogStream::IRDUMP).out(), stageId, "IA32", getName(), getTagName());
U_32 needInfo=getNeedInfo();
if (needInfo & NeedInfo_LivenessInfo)
irManager->updateLivenessInfo();
if (needInfo & NeedInfo_LoopInfo)
irManager->updateLoopInfo();
runImpl();
U_32 sideEffects=getSideEffects();
if (sideEffects & SideEffect_InvalidatesLivenessInfo)
irManager->invalidateLivenessInfo();
if (sideEffects & SideEffect_InvalidatesLoopInfo)
irManager->invalidateLoopInfo();
debugOutput("after");
if (!verify())
crash("\nVerification failure after %s\n", getName());
if (isLogEnabled(LogStream::IRDUMP))
Log::printStageEnd(log(LogStream::IRDUMP).out(), stageId, "IA32", getName(), getTagName());
}
U_32 SessionAction::getSideEffects()const
{
return ~(U_32)0;
}
U_32 SessionAction::getNeedInfo()const
{
return ~(U_32)0;
}
bool SessionAction::verify(bool force)
{
if (force || getVerificationLevel()>=2)
return getIRManager().verify();
return true;
}
void SessionAction::dumpIR(const char * subKind1, const char * subKind2)
{
Ia32::dumpIR(irManager, stageId, "IA32 LIR CFG after ", getName(), getTagName(),
subKind1, subKind2);
}
void SessionAction::printDot(const char * subKind1, const char * subKind2)
{
Ia32::printDot(irManager, stageId, "IA32 LIR CFG after ", getName(), getTagName(),
subKind1, subKind2);
}
void SessionAction::debugOutput(const char * subKind)
{
if (!isIRDumpEnabled())
return;
if (isLogEnabled(LogStream::IRDUMP)) {
irManager->updateLoopInfo();
irManager->updateLivenessInfo();
if (isLogEnabled("irdump_verbose")) {
dumpIR(subKind, "opnds");
dumpIR(subKind, "liveness");
}
dumpIR(subKind);
}
if (isLogEnabled(LogStream::DOTDUMP)) {
irManager->updateLoopInfo();
irManager->updateLivenessInfo();
printDot(subKind);
printDot(subKind, "liveness");
}
}
void SessionAction::computeDominators(void)
{
ControlFlowGraph* cfg = irManager->getFlowGraph();
DominatorTree* dominatorTree = cfg->getDominatorTree();
if(dominatorTree != NULL && dominatorTree->isValid()) {
// Already valid.
return;
}
static CountTime computeDominatorsTimer("ia32::helper::computeDominators");
AutoTimer tm(computeDominatorsTimer);
DominatorBuilder db;
dominatorTree = db.computeDominators(irManager->getMemoryManager(), cfg,false,true);
cfg->setDominatorTree(dominatorTree);
}
} //namespace Ia32
} //namespace Jitrino
| 42.118236 | 191 | 0.650607 |
sirinath
|
6568b57847c8770d90b2b97afb1f876db99c1bc1
| 1,087 |
hpp
|
C++
|
srcs/common/freespacebox.hpp
|
starxiang/heif
|
be43efdf273ae9cf90e552b99f16ac43983f3d19
|
[
"BSD-3-Clause"
] | 1,593 |
2015-10-22T15:47:43.000Z
|
2022-03-25T15:06:54.000Z
|
srcs/common/freespacebox.hpp
|
starxiang/heif
|
be43efdf273ae9cf90e552b99f16ac43983f3d19
|
[
"BSD-3-Clause"
] | 99 |
2016-06-18T10:14:41.000Z
|
2022-02-09T08:13:31.000Z
|
srcs/common/freespacebox.hpp
|
starxiang/heif
|
be43efdf273ae9cf90e552b99f16ac43983f3d19
|
[
"BSD-3-Clause"
] | 224 |
2016-01-09T00:40:16.000Z
|
2022-03-29T11:31:46.000Z
|
/* This file is part of Nokia HEIF library
*
* Copyright (c) 2015-2021 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
*
* Contact: heif@nokia.com
*
* This software, including documentation, is protected by copyright controlled by Nokia Corporation and/ or its
* subsidiaries. All rights are reserved.
*
* Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior
* written consent of Nokia.
*/
#ifndef FREESPACEBOX_HPP
#define FREESPACEBOX_HPP
#include "bbox.hpp"
#include "bitstream.hpp"
class FreeSpaceBox : public Box
{
public:
FreeSpaceBox();
~FreeSpaceBox() override = default;
/**
* @brief setSize Set FreeSpaceBox size.
* @param size FreeSpaceBox size in bytes. Must be 8 or more because of the box header size.
* @return True if size was set successfully (size >= 8), false otherwise.
*/
bool setSize(std::uint32_t size);
void writeBox(ISOBMFF::BitStream& bitstr) const override;
void parseBox(ISOBMFF::BitStream& bitstr) override;
};
#endif
| 28.605263 | 115 | 0.720331 |
starxiang
|
65692f61ce76acbf17fda313272d5a1f7d65a77b
| 19,279 |
cpp
|
C++
|
src/lug/Graphics/GltfLoader.cpp
|
Lugdunum3D/Lugdunum3D
|
b6d6907d034fdba1ffc278b96598eba1d860f0d4
|
[
"MIT"
] | 275 |
2016-10-08T15:33:17.000Z
|
2022-03-30T06:11:56.000Z
|
src/lug/Graphics/GltfLoader.cpp
|
Lugdunum3D/Lugdunum3D
|
b6d6907d034fdba1ffc278b96598eba1d860f0d4
|
[
"MIT"
] | 24 |
2016-09-29T20:51:20.000Z
|
2018-05-09T21:41:36.000Z
|
src/lug/Graphics/GltfLoader.cpp
|
Lugdunum3D/Lugdunum3D
|
b6d6907d034fdba1ffc278b96598eba1d860f0d4
|
[
"MIT"
] | 37 |
2017-02-25T05:03:48.000Z
|
2021-05-10T19:06:29.000Z
|
#include <lug/Graphics/GltfLoader.hpp>
#if defined(LUG_SYSTEM_ANDROID)
#include <android/asset_manager.h>
#include <lug/Window/Android/WindowImplAndroid.hpp>
#include <lug/Window/Window.hpp>
#endif
#include <gltf2/Exceptions.hpp>
#include <lug/System/Logger/Logger.hpp>
#include <lug/Graphics/Builder/Scene.hpp>
#include <lug/Graphics/Builder/Material.hpp>
#include <lug/Graphics/Builder/Mesh.hpp>
#include <lug/Graphics/Builder/Texture.hpp>
#include <lug/Graphics/Scene/Scene.hpp>
namespace lug {
namespace Graphics {
GltfLoader::GltfLoader(Renderer& renderer): Loader(renderer) {}
static void* getBufferViewData(const gltf2::Asset& asset, const gltf2::Accessor& accessor) {
const gltf2::BufferView& bufferView = asset.bufferViews[accessor.bufferView];
const gltf2::Buffer& buffer = asset.buffers[bufferView.buffer];
if (!buffer.data) {
LUG_LOG.error("GltfLoader::createMesh Buffer data can't be null");
return nullptr;
}
// TODO(nokitoo): handle uri
return buffer.data + bufferView.byteOffset + accessor.byteOffset;
}
static uint32_t getAttributeSize(const gltf2::Accessor& accessor) {
uint32_t componentSize = 0;
switch (accessor.componentType) {
case gltf2::Accessor::ComponentType::Byte:
componentSize = sizeof(char);
break;
case gltf2::Accessor::ComponentType::UnsignedByte:
componentSize = sizeof(unsigned char);
break;
case gltf2::Accessor::ComponentType::Short:
componentSize = sizeof(short);
break;
case gltf2::Accessor::ComponentType::UnsignedShort:
componentSize = sizeof(unsigned short);
break;
case gltf2::Accessor::ComponentType::UnsignedInt:
componentSize = sizeof(unsigned int);
break;
case gltf2::Accessor::ComponentType::Float:
componentSize = sizeof(float);
break;
}
// Mutliply the componentSize according to the type
switch (accessor.type) {
case gltf2::Accessor::Type::Scalar:
return componentSize;
case gltf2::Accessor::Type::Vec2:
return componentSize * 2;
case gltf2::Accessor::Type::Vec3:
return componentSize * 3;
case gltf2::Accessor::Type::Vec4:
return componentSize * 4;
case gltf2::Accessor::Type::Mat2:
return componentSize * 4;
case gltf2::Accessor::Type::Mat3:
return componentSize * 9;
case gltf2::Accessor::Type::Mat4:
return componentSize * 16;
}
return componentSize;
}
Resource::SharedPtr<Render::Texture> GltfLoader::createTexture(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index) {
const gltf2::Texture& gltfTexture = asset.textures[index];
if (loadedAssets.textures[index]) {
return loadedAssets.textures[index];
}
Builder::Texture textureBuilder(renderer);
if (gltfTexture.source != -1) {
// TODO: Handle correctly the load with bufferView / uri data
if (!textureBuilder.addLayer(asset.images[gltfTexture.source].uri)) {
LUG_LOG.error("GltfLoader::createTexture: Can't load the texture \"{}\"", asset.images[gltfTexture.source].uri);
return nullptr;
}
}
if (gltfTexture.sampler != -1) {
const gltf2::Sampler& sampler = asset.samplers[gltfTexture.sampler];
switch(sampler.magFilter) {
case gltf2::Sampler::MagFilter::None:
break;
case gltf2::Sampler::MagFilter::Nearest:
textureBuilder.setMagFilter(Render::Texture::Filter::Nearest);
break;
case gltf2::Sampler::MagFilter::Linear:
textureBuilder.setMagFilter(Render::Texture::Filter::Linear);
break;
}
switch(sampler.minFilter) {
case gltf2::Sampler::MinFilter::None:
break;
case gltf2::Sampler::MinFilter::Nearest:
textureBuilder.setMinFilter(Render::Texture::Filter::Nearest);
break;
case gltf2::Sampler::MinFilter::Linear:
textureBuilder.setMinFilter(Render::Texture::Filter::Linear);
break;
case gltf2::Sampler::MinFilter::NearestMipMapNearest:
textureBuilder.setMinFilter(Render::Texture::Filter::Nearest);
textureBuilder.setMipMapFilter(Render::Texture::Filter::Nearest);
break;
case gltf2::Sampler::MinFilter::LinearMipMapNearest:
textureBuilder.setMinFilter(Render::Texture::Filter::Linear);
textureBuilder.setMipMapFilter(Render::Texture::Filter::Nearest);
break;
case gltf2::Sampler::MinFilter::NearestMipMapLinear:
textureBuilder.setMinFilter(Render::Texture::Filter::Nearest);
textureBuilder.setMipMapFilter(Render::Texture::Filter::Linear);
break;
case gltf2::Sampler::MinFilter::LinearMipMapLinear:
textureBuilder.setMinFilter(Render::Texture::Filter::Linear);
textureBuilder.setMipMapFilter(Render::Texture::Filter::Linear);
break;
}
switch(sampler.wrapS) {
case gltf2::Sampler::WrappingMode::ClampToEdge:
textureBuilder.setWrapS(Render::Texture::WrappingMode::ClampToEdge);
break;
case gltf2::Sampler::WrappingMode::MirroredRepeat:
textureBuilder.setWrapS(Render::Texture::WrappingMode::MirroredRepeat);
break;
case gltf2::Sampler::WrappingMode::Repeat:
textureBuilder.setWrapS(Render::Texture::WrappingMode::Repeat);
break;
}
switch(sampler.wrapT) {
case gltf2::Sampler::WrappingMode::ClampToEdge:
textureBuilder.setWrapT(Render::Texture::WrappingMode::ClampToEdge);
break;
case gltf2::Sampler::WrappingMode::MirroredRepeat:
textureBuilder.setWrapT(Render::Texture::WrappingMode::MirroredRepeat);
break;
case gltf2::Sampler::WrappingMode::Repeat:
textureBuilder.setWrapT(Render::Texture::WrappingMode::Repeat);
break;
}
}
loadedAssets.textures[index] = textureBuilder.build();
return loadedAssets.textures[index];
}
Resource::SharedPtr<Render::Material> GltfLoader::createMaterial(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index) {
if (index == -1) {
return createDefaultMaterial(renderer, loadedAssets);
}
if (loadedAssets.materials[index]) {
return loadedAssets.materials[index];
}
const gltf2::Material& gltfMaterial = asset.materials[index];
Builder::Material materialBuilder(renderer);
materialBuilder.setName(gltfMaterial.name);
materialBuilder.setBaseColorFactor({
gltfMaterial.pbr.baseColorFactor[0],
gltfMaterial.pbr.baseColorFactor[1],
gltfMaterial.pbr.baseColorFactor[2],
gltfMaterial.pbr.baseColorFactor[3]
});
if (gltfMaterial.pbr.baseColorTexture.index != -1) {
Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.pbr.baseColorTexture.index);
if (!texture) {
LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource");
return nullptr;
}
materialBuilder.setBaseColorTexture(texture, gltfMaterial.pbr.baseColorTexture.texCoord);
}
materialBuilder.setMetallicFactor(gltfMaterial.pbr.metallicFactor);
materialBuilder.setRoughnessFactor(gltfMaterial.pbr.roughnessFactor);
if (gltfMaterial.pbr.metallicRoughnessTexture.index != -1) {
Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.pbr.metallicRoughnessTexture.index);
if (!texture) {
LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource");
return nullptr;
}
materialBuilder.setMetallicRoughnessTexture(texture, gltfMaterial.pbr.metallicRoughnessTexture.texCoord);
}
if (gltfMaterial.normalTexture.index != -1) {
Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.normalTexture.index);
if (!texture) {
LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource");
return nullptr;
}
materialBuilder.setNormalTexture(texture, gltfMaterial.normalTexture.texCoord);
}
if (gltfMaterial.occlusionTexture.index != -1) {
Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.occlusionTexture.index);
if (!texture) {
LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource");
return nullptr;
}
materialBuilder.setOcclusionTexture(texture, gltfMaterial.occlusionTexture.texCoord);
}
if (gltfMaterial.emissiveTexture.index != -1) {
Resource::SharedPtr<Render::Texture> texture = createTexture(renderer, asset, loadedAssets, gltfMaterial.emissiveTexture.index);
if (!texture) {
LUG_LOG.error("GltfLoader::createMaterial Can't create the texture resource");
return nullptr;
}
materialBuilder.setEmissiveTexture(texture, gltfMaterial.emissiveTexture.texCoord);
}
materialBuilder.setEmissiveFactor({
gltfMaterial.emissiveFactor[0],
gltfMaterial.emissiveFactor[1],
gltfMaterial.emissiveFactor[2]
});
loadedAssets.materials[index] = materialBuilder.build();
return loadedAssets.materials[index];
}
Resource::SharedPtr<Render::Material> GltfLoader::createDefaultMaterial(Renderer& renderer, GltfLoader::LoadedAssets& loadedAssets) {
if (loadedAssets.defaultMaterial) {
return loadedAssets.defaultMaterial;
}
Builder::Material materialBuilder(renderer);
loadedAssets.defaultMaterial = materialBuilder.build();
return loadedAssets.defaultMaterial;
}
static void* generateNormals(float* positions, uint32_t accessorCount) {
Math::Vec3f* data = new Math::Vec3f[accessorCount];
uint32_t trianglesCount = accessorCount / 3;
uint32_t positionsIdx = 0;
for (uint32_t i = 0; i < trianglesCount; ++i) {
Math::Vec3f a{positions[positionsIdx], positions[positionsIdx + 1], positions[positionsIdx + 2]};
Math::Vec3f b{positions[positionsIdx + 3], positions[positionsIdx + 4], positions[positionsIdx + 5]};
Math::Vec3f c{positions[positionsIdx + 6], positions[positionsIdx + 7], positions[positionsIdx + 8]};
Math::Vec3f edge1 = b - a;
Math::Vec3f edge2 = c - a;
data[i++] = cross(edge1, edge2);
}
return data;
}
Resource::SharedPtr<Render::Mesh> GltfLoader::createMesh(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index) {
const gltf2::Mesh& gltfMesh = asset.meshes[index];
if (loadedAssets.meshes[index]) {
return loadedAssets.meshes[index];
}
Builder::Mesh meshBuilder(renderer);
meshBuilder.setName(gltfMesh.name);
for (const gltf2::Primitive& gltfPrimitive : gltfMesh.primitives) {
Builder::Mesh::PrimitiveSet* primitiveSet = meshBuilder.addPrimitiveSet();
// Mode
switch (gltfPrimitive.mode) {
case gltf2::Primitive::Mode::Points:
primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::Points);
break;
case gltf2::Primitive::Mode::Lines:
primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::Lines);
break;
case gltf2::Primitive::Mode::LineLoop:
LUG_LOG.error("GltfLoader::createMesh Unsupported mode LineLoop");
return nullptr;
case gltf2::Primitive::Mode::LineStrip:
primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::LineStrip);
break;
case gltf2::Primitive::Mode::Triangles:
primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::Triangles);
break;
case gltf2::Primitive::Mode::TriangleStrip:
primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::TriangleStrip);
break;
case gltf2::Primitive::Mode::TriangleFan:
primitiveSet->setMode(Render::Mesh::PrimitiveSet::Mode::TriangleFan);
break;
}
// Indices
if (gltfPrimitive.indices != -1) {
const gltf2::Accessor& accessor = asset.accessors[gltfPrimitive.indices]; // Get the accessor from its index (directly from indices)
uint32_t componentSize = getAttributeSize(accessor);
void* data = getBufferViewData(asset, accessor);
if (!data) {
return nullptr;
}
primitiveSet->addAttributeBuffer(
data,
componentSize,
accessor.count,
Render::Mesh::PrimitiveSet::Attribute::Type::Indice
);
}
// Attributes
struct {
void* data{nullptr};
uint32_t accessorCount{0};
} positions; // Store positions for normals generation
bool hasNormals = false;
for (auto& attribute : gltfPrimitive.attributes) {
Render::Mesh::PrimitiveSet::Attribute::Type type;
if (attribute.first == "POSITION") {
type = Render::Mesh::PrimitiveSet::Attribute::Type::Position;
} else if (attribute.first == "NORMAL") {
type = Render::Mesh::PrimitiveSet::Attribute::Type::Normal;
hasNormals = true;
} else if (attribute.first == "TANGENT") {
type = Render::Mesh::PrimitiveSet::Attribute::Type::Tangent;
} else if (attribute.first.find("TEXCOORD_") != std::string::npos) {
type = Render::Mesh::PrimitiveSet::Attribute::Type::TexCoord;
} else if (attribute.first.find("COLOR_") != std::string::npos) {
type = Render::Mesh::PrimitiveSet::Attribute::Type::Color;
} else {
LUG_LOG.warn("GltfLoader::createMesh Unsupported attribute {}", attribute.first);
continue;
}
// TODO(nokitoo): See if we can use COLOR_0 or if we just discard it
const gltf2::Accessor& accessor = asset.accessors[attribute.second]; // Get the accessor from its index (second in the pair)
uint32_t componentSize = getAttributeSize(accessor);
void* data = getBufferViewData(asset, accessor);
if (!data) {
return nullptr;
}
if (type == Render::Mesh::PrimitiveSet::Attribute::Type::Position) { // Store positions in case we need to generate the normals later
positions.data = data;
positions.accessorCount = accessor.count;
}
primitiveSet->addAttributeBuffer(data, componentSize, accessor.count, type);
}
// Generate flat normals if there is not any
if (!hasNormals) {
void* data = generateNormals((float*)positions.data, positions.accessorCount);
if (!data) {
return nullptr;
}
primitiveSet->addAttributeBuffer(
data, sizeof(Math::Vec3f), positions.accessorCount,
Render::Mesh::PrimitiveSet::Attribute::Type::Normal
);
}
// Material
Resource::SharedPtr<Render::Material> material = createMaterial(renderer, asset, loadedAssets, gltfPrimitive.material);
if (!material) {
LUG_LOG.error("GltfLoader::createMesh Can't create the material resource");
return nullptr;
}
primitiveSet->setMaterial(material);
// TODO(nokitoo): set node transformations
}
loadedAssets.meshes[index] = meshBuilder.build();
return loadedAssets.meshes[index];
}
bool GltfLoader::createNode(Renderer& renderer, const gltf2::Asset& asset, GltfLoader::LoadedAssets& loadedAssets, int32_t index, Scene::Node& parent) {
const gltf2::Node& gltfNode = asset.nodes[index];
Scene::Node* node = parent.createSceneNode(gltfNode.name);
parent.attachChild(*node);
if (gltfNode.mesh != -1) {
Resource::SharedPtr<Render::Mesh> mesh = createMesh(renderer, asset, loadedAssets, gltfNode.mesh);
if (!mesh) {
LUG_LOG.error("GltfLoader::createNode Can't create the mesh resource");
return false;
}
node->attachMeshInstance(mesh);
}
node->setPosition({
gltfNode.translation[0],
gltfNode.translation[1],
gltfNode.translation[2]
}, Node::TransformSpace::Parent);
node->setRotation(Math::Quatf{
gltfNode.rotation[3],
gltfNode.rotation[0],
gltfNode.rotation[1],
gltfNode.rotation[2]
}, Node::TransformSpace::Parent);
node->scale({
gltfNode.scale[0],
gltfNode.scale[1],
gltfNode.scale[2]
});
for (uint32_t nodeIdx : gltfNode.children) {
if (!createNode(renderer, asset, loadedAssets, nodeIdx, *node)) {
return false;
}
}
return true;
}
Resource::SharedPtr<Resource> GltfLoader::loadFile(const std::string& filename) {
gltf2::Asset asset;
try {
#if defined(LUG_SYSTEM_ANDROID)
asset = gltf2::load(filename, (lug::Window::priv::WindowImpl::activity)->assetManager);
#else
asset = gltf2::load(filename);
#endif
// TODO(nokitoo): Format the asset if not already done
// Should we store the version of format in asset.extensions or asset.copyright/asset.version ?
} catch (gltf2::MisformattedException& e) {
LUG_LOG.error("GltfLoader::loadFile Can't load the file \"{}\": {}", filename, e.what());
return nullptr;
}
// Create the container for the already loaded assets
GltfLoader::LoadedAssets loadedAssets;
loadedAssets.textures.resize(asset.textures.size());
loadedAssets.materials.resize(asset.materials.size());
loadedAssets.meshes.resize(asset.meshes.size());
// Load the scene
if (asset.scene == -1) { // No scene to load
return nullptr;
}
const gltf2::Scene& gltfScene = asset.scenes[asset.scene];
Builder::Scene sceneBuilder(_renderer);
sceneBuilder.setName(gltfScene.name);
Resource::SharedPtr<lug::Graphics::Scene::Scene> scene = sceneBuilder.build();
if (!scene) {
LUG_LOG.error("GltfLoader::loadFile Can't create the scene resource");
return nullptr;
}
for (uint32_t nodeIdx : gltfScene.nodes) {
if (!createNode(_renderer, asset, loadedAssets, nodeIdx, scene->getRoot())) {
return nullptr;
}
}
return Resource::SharedPtr<Resource>::cast(scene);
}
} // Graphics
} // lug
| 38.868952 | 168 | 0.635147 |
Lugdunum3D
|
656e2da18bebbd4f035afda333be8b0dbf5ec7a9
| 550 |
cpp
|
C++
|
app/hibp_convert.cpp
|
oschonrock/hibp
|
690309ed4b13f89b4622155a15da1a344e2f63dd
|
[
"Apache-2.0"
] | null | null | null |
app/hibp_convert.cpp
|
oschonrock/hibp
|
690309ed4b13f89b4622155a15da1a344e2f63dd
|
[
"Apache-2.0"
] | null | null | null |
app/hibp_convert.cpp
|
oschonrock/hibp
|
690309ed4b13f89b4622155a15da1a344e2f63dd
|
[
"Apache-2.0"
] | null | null | null |
#include "flat_file.hpp"
#include "hibp.hpp"
#include <cstdlib>
int main(int /* argc */, char* argv[]) {
std::ios_base::sync_with_stdio(false);
std::cerr << argv[0] << ": reading `have i been pawned` text database from stdin,\n"
"converting to binary format and writing to stdout."
<< std::endl;
auto writer = flat_file::stream_writer<hibp::pawned_pw>(std::cout);
for (std::string line; std::getline(std::cin, line);)
writer.write(hibp::convert_to_binary(line));
return EXIT_SUCCESS;
}
| 28.947368 | 88 | 0.630909 |
oschonrock
|
656f71c8f3474b223f685bbdb0ce01589dce8a63
| 4,126 |
cpp
|
C++
|
heap.cpp
|
MichaelRFairhurst/vaiven
|
47a0ae7fbfd10aee7bed1d6c25bdb566b1a10174
|
[
"Apache-2.0"
] | 61 |
2017-03-22T11:25:15.000Z
|
2021-11-19T23:12:48.000Z
|
heap.cpp
|
MichaelRFairhurst/vaiven
|
47a0ae7fbfd10aee7bed1d6c25bdb566b1a10174
|
[
"Apache-2.0"
] | 2 |
2019-07-05T23:41:36.000Z
|
2019-07-14T23:32:18.000Z
|
heap.cpp
|
MichaelRFairhurst/vaiven
|
47a0ae7fbfd10aee7bed1d6c25bdb566b1a10174
|
[
"Apache-2.0"
] | 2 |
2018-06-27T16:11:24.000Z
|
2018-07-05T07:31:44.000Z
|
#include "heap.h"
#include <algorithm>
#include <cassert>
#include "stack.h"
using namespace vaiven;
using std::min;
using std::max;
// set by interpreter
Heap* vaiven::globalHeap = NULL;
GcableType vaiven::Gcable::getType() {
return (GcableType) (((GcableType) this->type) & ~GcableMarkBit);
}
bool vaiven::Gcable::isMarked() {
return (this->type & GcableMarkBit) == GcableMarkBit;
}
bool vaiven::Gcable::mark() {
if (isMarked()) {
return false;
}
this->type = (GcableType) (((GcableType) this->type) | GcableMarkBit);
return true;
}
void vaiven::Gcable::unmark() {
this->type = (GcableType) (((GcableType) this->type) & ~GcableMarkBit);
}
GcableList* vaiven::Heap::newList() {
if (isFull()) {
gc();
}
GcableList* ptr = new GcableList();
owned_ptrs.insert(ptr);
heap_min = min(heap_min, (uint64_t) ptr);
heap_max = max(heap_max, (uint64_t) ptr);
return ptr;
}
GcableString* vaiven::Heap::newString() {
if (isFull()) {
gc();
}
GcableString* ptr = new GcableString();
owned_ptrs.insert(ptr);
heap_min = min(heap_min, (uint64_t) ptr);
heap_max = max(heap_max, (uint64_t) ptr);
return ptr;
}
GcableObject* vaiven::Heap::newObject() {
if (isFull()) {
gc();
}
GcableObject* ptr = new GcableObject();
owned_ptrs.insert(ptr);
heap_min = min(heap_min, (uint64_t) ptr);
heap_max = max(heap_max, (uint64_t) ptr);
return ptr;
}
bool vaiven::Heap::owns(void* ptr) {
uint64_t addr = (uint64_t) ptr;
// inside heap and is aligned to 64 bits
if (addr < heap_min || addr > heap_max || addr & 7 != 1) {
return false;
}
return owned_ptrs.find((Gcable*) ptr) != owned_ptrs.end();
}
bool vaiven::Heap::isFull() {
return owned_ptrs.size() >= size;
}
void vaiven::Heap::mark(Gcable* ptr) {
if (!owns(ptr)) {
return;
}
if (ptr->mark()) {
return;
}
switch (ptr->getType()) {
case GCABLE_TYPE_LIST:
{
GcableList* list = (GcableList*) ptr;
for (vector<Value>::iterator it = list->list.begin(); it != list->list.end(); ++it) {
mark(it->getPtr());
}
break;
}
case GCABLE_TYPE_STRING:
// already marked, nothing to do
break;
case GCABLE_TYPE_OBJECT:
{
GcableObject* object = (GcableObject*) ptr;
for (unordered_map<string, Value>::iterator it = object->properties.begin(); it != object->properties.end(); ++it) {
mark(it->second.getPtr());
}
}
}
}
void vaiven::Heap::sweep() {
unordered_set<Gcable*>::iterator it = owned_ptrs.begin();
while (it != owned_ptrs.end()) {
Gcable* gcable = (Gcable*) *it;
if (!gcable->isMarked()) {
switch (gcable->getType()) {
case GCABLE_TYPE_LIST:
delete static_cast<GcableList*>(gcable); break;
case GCABLE_TYPE_STRING:
delete static_cast<GcableString*>(gcable); break;
case GCABLE_TYPE_OBJECT:
delete static_cast<GcableObject*>(gcable); break;
}
it = owned_ptrs.erase(it);
} else {
gcable->unmark();
++it;
}
}
}
void vaiven::Heap::free(Gcable* ptr) {
if (ptr->getType() == GCABLE_TYPE_LIST) {
delete (GcableList*) ptr;
} else if (ptr->getType() == GCABLE_TYPE_STRING) {
delete (GcableString*) ptr;
} else if (ptr->getType() == GCABLE_TYPE_OBJECT) {
delete (GcableObject*) ptr;
}
owned_ptrs.erase(ptr);
}
void vaiven::Heap::gc() {
Stack callStack;
StackFrame frame = callStack.top();
while (true) {
for (int i = 0; i < frame.size; ++i) {
mark((Gcable*) frame.locals[i]);
}
if (!frame.hasNext()) {
break;
}
frame = frame.next();
}
for (std::deque<Value>::iterator it = interpreterStack.c.begin();
it != interpreterStack.c.end();
++it) {
mark((Gcable*) it->getPtr());
}
std::map<string, Value> scopeMap;
globalScope.fill(scopeMap);
for (std::map<string, Value>::iterator it = scopeMap.begin();
it != scopeMap.end();
++it) {
mark((Gcable*) it->second.getPtr());
}
sweep();
size = max((int) owned_ptrs.size() * HEAP_FACTOR, MIN_HEAP_SIZE);
}
| 22.302703 | 124 | 0.60349 |
MichaelRFairhurst
|
657205b0280e4a607ca7f2356d4ee5a25a99d763
| 355 |
cpp
|
C++
|
tests/suites/partitioner_correctness.cpp
|
PMitura/pace2018
|
f81518ecd312c5fad7be26410b0ecbb5575e6d78
|
[
"MIT"
] | null | null | null |
tests/suites/partitioner_correctness.cpp
|
PMitura/pace2018
|
f81518ecd312c5fad7be26410b0ecbb5575e6d78
|
[
"MIT"
] | null | null | null |
tests/suites/partitioner_correctness.cpp
|
PMitura/pace2018
|
f81518ecd312c5fad7be26410b0ecbb5575e6d78
|
[
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include "utility/partitioner.h"
TEST(Partitioner, Basic) {
Partitioner part1(0, 0b111, 3);
part1.compute();
std::vector<uint64_t> vres1 = part1.getResult();
std::set<uint64_t> ref1 = {0x0000, 0x0100, 0x0010, 0x0110, 0x0210},
res1(vres1.begin(), vres1.end());
EXPECT_EQ(ref1, res1);
}
| 27.307692 | 71 | 0.625352 |
PMitura
|
65721c4f649cc6e333e45345687d2f6f913f4849
| 590 |
cpp
|
C++
|
perception_oru-port-kinetic/graph_map/src/ndt_dl/ndtdl_map_param.cpp
|
lllray/ndt-loam
|
331867941e0764b40e1a980dd85d2174f861e9c8
|
[
"BSD-3-Clause"
] | 1 |
2020-11-14T08:21:13.000Z
|
2020-11-14T08:21:13.000Z
|
perception_oru-port-kinetic/graph_map/src/ndt_dl/ndtdl_map_param.cpp
|
lllray/ndt-loam
|
331867941e0764b40e1a980dd85d2174f861e9c8
|
[
"BSD-3-Clause"
] | 1 |
2021-07-28T04:47:56.000Z
|
2021-07-28T04:47:56.000Z
|
perception_oru-port-kinetic/graph_map/src/ndt_dl/ndtdl_map_param.cpp
|
lllray/ndt-loam
|
331867941e0764b40e1a980dd85d2174f861e9c8
|
[
"BSD-3-Clause"
] | 2 |
2020-12-18T11:25:53.000Z
|
2022-02-19T12:59:59.000Z
|
#include "graph_map/ndt_dl/ndtdl_map_param.h"
#include <boost/serialization/export.hpp>
BOOST_CLASS_EXPORT(perception_oru::libgraphMap::NDTDLMapParam)
using namespace std;
namespace perception_oru{
namespace libgraphMap{
void NDTDLMapParam::GetParametersFromRos(){
MapParam::GetParametersFromRos();
ros::NodeHandle nh("~");
cout<<"reading parameters from ros inside NDTDLMapParam::GetRosParametersFromRos()"<<endl;
nh.param<std::string>("Super_important_map_parameter",SuperImportantMapParameter,"parhaps not so important...");
nh.param("resolution",resolution_,1.0);
}
}
}
| 26.818182 | 114 | 0.786441 |
lllray
|
6573ece9acf8698ec8d945159bec5a18d4713324
| 1,830 |
hpp
|
C++
|
include/owlcpp/detail/vector_set.hpp
|
GreyMerlin/owl_cpp
|
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
|
[
"BSL-1.0"
] | 10 |
2017-12-21T05:20:40.000Z
|
2021-09-18T05:14:01.000Z
|
include/owlcpp/detail/vector_set.hpp
|
GreyMerlin/owl_cpp
|
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
|
[
"BSL-1.0"
] | 2 |
2017-12-21T07:31:54.000Z
|
2021-06-23T08:52:35.000Z
|
include/owlcpp/detail/vector_set.hpp
|
GreyMerlin/owl_cpp
|
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
|
[
"BSL-1.0"
] | 7 |
2016-02-17T13:20:31.000Z
|
2021-11-08T09:30:43.000Z
|
/** @file "/owlcpp/include/owlcpp/detail/vector_set.hpp"
part of owlcpp project.
@n @n Distributed under the Boost Software License, Version 1.0; see doc/license.txt.
@n Copyright Mikhail K Levin 2013
*******************************************************************************/
#ifndef VECTOR_SET_HPP_
#define VECTOR_SET_HPP_
#include <vector>
namespace owlcpp{
/**@brief Collection of unique objects stored in a vector
*******************************************************************************/
template<class T, class Comp = std::less<T>, class Alloc = std::allocator<T> >
class Vector_set {
typedef std::vector<T, Alloc> stor_t;
public:
typedef T value_type;
typedef typename stor_t::iterator iterator;
typedef typename stor_t::const_iterator const_iterator;
Vector_set() : v_(), comp_() {}
Vector_set(Comp const& comp) : v_(), comp_(comp) {}
iterator begin() {return v_.begin();}
iterator end() {return v_.end();}
const_iterator begin() const {return v_.begin();}
const_iterator end() const {return v_.end();}
std::size_t size() const {return v_.size();}
std::pair<iterator, bool> insert(value_type const& t) {
iterator i = std::lower_bound(v_.begin(), v_.end(), t, comp_);
if( i == v_.end() || comp_(t, *i) ) {
return std::make_pair(v_.insert(i, t), true);
}
return std::make_pair(i, false);
}
const_iterator find(value_type const& t) const {
const_iterator i = std::lower_bound(v_.begin(), v_.end(), t, comp_);
if( i == v_.end() || comp_(t, *i) ) return v_.end();
return i;
}
value_type const& operator[](const std::size_t n) const {return v_[n];}
value_type const& at(const std::size_t n) const {return v_.at(n);}
private:
stor_t v_;
Comp comp_;
};
}//namespace owlcpp
#endif /* VECTOR_SET_HPP_ */
| 34.528302 | 85 | 0.604372 |
GreyMerlin
|
6576840e8ff3dd280cb0c3738aa2fc72123e5ae2
| 2,455 |
hpp
|
C++
|
falcon/functional/invoke_partial_recursive_param_loop.hpp
|
jonathanpoelen/falcon
|
5b60a39787eedf15b801d83384193a05efd41a89
|
[
"MIT"
] | 2 |
2018-02-02T14:19:59.000Z
|
2018-05-13T02:48:24.000Z
|
falcon/functional/invoke_partial_recursive_param_loop.hpp
|
jonathanpoelen/falcon
|
5b60a39787eedf15b801d83384193a05efd41a89
|
[
"MIT"
] | null | null | null |
falcon/functional/invoke_partial_recursive_param_loop.hpp
|
jonathanpoelen/falcon
|
5b60a39787eedf15b801d83384193a05efd41a89
|
[
"MIT"
] | null | null | null |
#ifndef FALCON_FUNCTIONAL_INVOKE_PARTIAL_RECURSIVE_PARAM_HPP
#define FALCON_FUNCTIONAL_INVOKE_PARTIAL_RECURSIVE_PARAM_HPP
#include <falcon/math/min.hpp>
#include <falcon/c++1x/syntax.hpp>
#include <falcon/functional/invoke.hpp>
#include <falcon/parameter/manip.hpp>
#include <falcon/preprocessor/not_ide_parser.hpp>
#include <utility>
namespace falcon {
template<std::size_t NumberArg>
class invoke_partial_recursive_param_loop_fn
{
static_assert(NumberArg > 1, "NumberArg < 2");
template<std::size_t N, class = void>
struct Impl {
template<
class F, class... Args
, std::size_t Start = (N - 1) * (NumberArg - 1) + NumberArg + 1>
static constexpr CPP1X_DELEGATE_FUNCTION(
impl_(F && func, Args&&... args)
, invoke(
typename parameter_index_cat<
parameter_index<0>,
build_range_parameter_index_t<
Start
, min(Start + (NumberArg - 1), sizeof...(Args) + 1)
>
>::type()
, std::forward<F>(func)
, Impl<N-1>::impl_(std::forward<F>(func), std::forward<Args>(args)...)
, std::forward<Args>(args)...
)
)
};
template<class T>
struct Impl<0, T> {
template<class F, class... Args>
static constexpr CPP1X_DELEGATE_FUNCTION(
impl_(F && func, Args&&... args)
, invoke(
build_parameter_index_t<min(NumberArg, sizeof...(Args))>()
, std::forward<F>(func)
, std::forward<Args>(args)...
)
)
};
public:
constexpr invoke_partial_recursive_param_loop_fn() noexcept {}
template<
class F, class... Args
, std::size_t N = (sizeof...(Args) - 2) / (NumberArg - 1)>
constexpr CPP1X_DELEGATE_FUNCTION(
operator()(F && func, Args&&... args) const
, Impl<N>::impl_(std::forward<F>(func), std::forward<Args>(args)...)
)
};
/**
* \brief Call \c func with \c NumberArg arguments. The return of \c func is the first argument of next call.
* \return Last operations.
*
* \code
* int n = invoke_partial_param_loop<2>(accu_t(), 1,2,3,4,5,6);
* \endcode
* equivalent to
* \code
* accu_t accu;
* int n = accu(accu(accu(accu(accu(1,2),3),4),5),6);
* \endcode
*
* \ingroup call-arguments
*/
template<std::size_t NumberArg, class F, class... Args>
constexpr CPP1X_DELEGATE_FUNCTION(
invoke_partial_recursive_param_loop(F func, Args&&... args)
, invoke_partial_recursive_param_loop_fn<NumberArg>()(
std::forward<F>(func), std::forward<Args>(args)...)
)
}
#endif
| 26.684783 | 109 | 0.648473 |
jonathanpoelen
|
6577079424087467dfb544b8d563874f3a5262b1
| 1,162 |
cc
|
C++
|
Projects/Grafeo/attic/grafeo_20091012_qt/app/mainwindow.cc
|
fredmorcos/attic
|
0da3b94aa525df59ddc977c32cb71c243ffd0dbd
|
[
"Unlicense"
] | 2 |
2021-01-24T09:00:51.000Z
|
2022-01-23T20:52:17.000Z
|
Projects/Grafeo/attic/grafeo_20091012_qt/app/mainwindow.cc
|
fredmorcos/attic
|
0da3b94aa525df59ddc977c32cb71c243ffd0dbd
|
[
"Unlicense"
] | 6 |
2020-02-29T01:59:03.000Z
|
2022-02-15T10:25:40.000Z
|
Projects/Grafeo/attic/grafeo_20091012_qt/app/mainwindow.cc
|
fredmorcos/attic
|
0da3b94aa525df59ddc977c32cb71c243ffd0dbd
|
[
"Unlicense"
] | 1 |
2019-03-22T14:41:21.000Z
|
2019-03-22T14:41:21.000Z
|
#include "mainwindow.h"
#include <QFileDialog>
MainWindow::MainWindow(QWidget *parent):
QMainWindow(parent)
{
setupUi(this);
tabWidget->removeTab(0);
}
void MainWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
retranslateUi(this);
break;
default:
break;
}
}
void MainWindow::closeEvent(QCloseEvent *event)
{
event->accept();
qApp->quit();
}
void MainWindow::on_actionOpen_triggered()
{
QFileDialog fd(this, tr("Select File to Open"));
fd.setFileMode(QFileDialog::ExistingFile);
fd.setOption(QFileDialog::ReadOnly);
fd.exec();
}
void MainWindow::on_actionSave_triggered()
{
Document *document = DocumentManager::instance()->documentFromIndex(
tabWidget->currentIndex());
if (document->fileName().isEmpty() == true)
{
QFileDialog fd(this, tr("Select Filename to Save"));
fd.setFileMode(QFileDialog::AnyFile);
connect(&fd, SIGNAL(fileSelected(QString)),
this, SLOT(saveFileSelected(QString)));
fd.exec();
}
else
DocumentManager::instance()->saveDocument(tabWidget->currentIndex(),
}
void MainWindow::saveFileSelected(const QString &filename)
{
}
| 19.366667 | 70 | 0.72031 |
fredmorcos
|
65773eb4d3d4009263fbd5df2240e268355ac09a
| 309 |
cpp
|
C++
|
Decorator Pattern/Decorator Pattern/HouseBlend.cpp
|
mrlegowatch/HeadFirstDesignPatternsCpp
|
436ee8f0344b6a2ccfef6dcfa216a16a6ca7b482
|
[
"MIT"
] | 43 |
2018-07-17T21:53:21.000Z
|
2022-03-23T13:15:06.000Z
|
Decorator Pattern/Decorator Pattern/HouseBlend.cpp
|
mrlegowatch/HeadFirstDesignPatternsCpp
|
436ee8f0344b6a2ccfef6dcfa216a16a6ca7b482
|
[
"MIT"
] | null | null | null |
Decorator Pattern/Decorator Pattern/HouseBlend.cpp
|
mrlegowatch/HeadFirstDesignPatternsCpp
|
436ee8f0344b6a2ccfef6dcfa216a16a6ca7b482
|
[
"MIT"
] | 14 |
2019-04-10T13:01:07.000Z
|
2022-03-08T13:19:14.000Z
|
//
// HouseBlend.cpp
// Decorator Pattern
//
// Created by Kevin Lee on 2/13/18.
// Copyright © 2018 Brian Arnold. All rights reserved.
//
#include "HouseBlend.hpp"
std::string HouseBlend::getDescription() const {
return "House Blend Coffee";
}
double HouseBlend::cost() const {
return 0.89;
}
| 17.166667 | 55 | 0.673139 |
mrlegowatch
|
657b0bd920f85fed566616a0e8c1eec48f75ca6c
| 9,204 |
cc
|
C++
|
tests/nonsmoke/functional/CompileTests/vxworks_tests/pond.cc
|
ouankou/rose
|
76f2a004bd6d8036bc24be2c566a14e33ba4f825
|
[
"BSD-3-Clause"
] | 488 |
2015-01-09T08:54:48.000Z
|
2022-03-30T07:15:46.000Z
|
tests/nonsmoke/functional/CompileTests/vxworks_tests/pond.cc
|
WildeGeist/rose
|
17db6454e8baba0014e30a8ec23df1a11ac55a0c
|
[
"BSD-3-Clause"
] | 174 |
2015-01-28T18:41:32.000Z
|
2022-03-31T16:51:05.000Z
|
tests/nonsmoke/functional/CompileTests/vxworks_tests/pond.cc
|
WildeGeist/rose
|
17db6454e8baba0014e30a8ec23df1a11ac55a0c
|
[
"BSD-3-Clause"
] | 146 |
2015-04-27T02:48:34.000Z
|
2022-03-04T07:32:53.000Z
|
// Example code from VX Works
#ifndef CPU
// DQ: changed defalt from Sparc to PPC
// #define CPU 10
#define CPU 91
#endif
#include "vxWorks.h"
#include "taskLib.h"
#include "vxwSemLib.h"
// Control the number of creatures in the pond
#define MAX_FLIES 5 // The initial number of flies
#define MAX_FROGS 2 // Same for frogs
#define FROG_STARVED 3 // How long ot takes a frog to starve
#define GRAB_CHANCE RAND_MAX / 2 // The probability of a frog catching a fly
#define FLY_BIRTH_RATE RAND_MAX / 4 // The probability of a fly reproducing
#define FROG_BIRTH_RATE RAND_MAX / 2 // Remeber here that frogs only give birth after they have eaten!!
int fly_lifecycle();
int frog_lifecycle();
/****************************************************************************************/
/* Linked list thingy */
class node
{
public:
class Fly *key;
node *next;
node()
{
key = NULL;
next = NULL;
}
~node()
{
key = NULL;
next = NULL;
}
};
class List
{
private:
node header;
node end;
public:
List()
{
header.key = NULL;
header.next = &end;
end.key = NULL;
end.next = &end;
}
void add(Fly *val)
{
node *tmp;
// printf("\nAdding %X ",val);
tmp = new node;
tmp->next = header.next;
tmp->key = val;
header.next = tmp;
//traverse();
}
void remove(Fly *val)
{
node *previous, *current;
//printf("\nRemoving %X ",val);
previous = &header;
current = previous->next;
while(current->key != val && current != &end)
{
previous = current;
current = current->next;
}
if(current->key == val)
{
previous->next = current->next;
delete current;
}
//traverse();
}
Fly *get()
{
Fly *tmp;
tmp = header.next->key;
//printf("\nGetting %X ",tmp);
//traverse();
return tmp;
}
int empty()
{
if(header.next == &end)
return 1;
else
return 0;
}
void traverse()
{
node *current;
//printf("\n");
current = header.next;
while(current != &end)
{
// printf("%X ",current->key);
current = current->next;
}
}
};
/*****************************************************************************************/
/* The pond class is basically a database or resource. Both flies and frogs will access */
/* the data and therefore proection is needed */
class Pond
{
private:
int number_of_flies, number_of_frogs;
List *flying_db;
public:
VXWBSem *fly_mutex;
//mutex_t fly_mutex;
Pond()
{
// mutex_init(&fly_mutex,NULL,NULL);
fly_mutex = new VXWBSem(SEM_Q_PRIORITY,SEM_FULL);
number_of_flies = 0;
number_of_frogs = 0;
flying_db = new List;
}
void lock()
// { mutex_lock(&fly_mutex) }
{ fly_mutex->take(WAIT_FOREVER); }
void unlock()
// { mutex_unlock(&fly_mutex);}
{ fly_mutex->give(); }
void fly_born()
{
number_of_flies++;
}
void fly_flying(Fly *id)
{
flying_db->add(id);
}
void fly_landed(Fly *id)
{
flying_db->remove(id);
}
/* void fly_died()
{
number_of_flies--;
}
*/
void fly_died(Fly *id)
{
number_of_flies--;
flying_db->remove(id);
}
Fly *flies_about()
{
if(!flying_db->empty())
return flying_db->get();
else
return NULL;
}
};
/*************************************************************************************/
/* */
class Fly
{
private:
enum { landed, flying, dead} status;
int age;
Pond *our_pond;
VXWMSem *mutex;
// mutex_t mutex;
public:
Fly(Pond *a_pond)
{
age = 3;
status = landed;
our_pond = a_pond;
our_pond->lock();
our_pond->fly_born();
our_pond->unlock();
mutex = new VXWMSem(SEM_Q_PRIORITY);
//mutex_init(&mutex,NULL,NULL);
}
void lock()
// { mutex_lock(&mutex); }
{ mutex->take(WAIT_FOREVER); }
void unlock()
//{ mutex_unlock(&mutex); }
{ mutex->give(); }
void fly_landed()
{
status = landed;
our_pond->lock();
our_pond->fly_landed(this);
our_pond->unlock();
}
void fly_flying()
{
status = flying;
our_pond->lock();
our_pond->fly_flying(this); // This will be change to a pointer to the fly shortly
our_pond->unlock();
}
void fly_dead()
{
status = dead;
our_pond->lock();
our_pond->fly_died(this);
our_pond->unlock();
}
// DQ: Added return type.
// fly_isdead()
int fly_isdead()
{
if(status == dead)
return 1;
else
return 0;
}
int get_age()
{ return age; }
void happy_birthday()
{ age--; }
int grab()
{
int result;
if(status==flying && (rand() > GRAB_CHANCE))
{
status = dead;
our_pond->lock();
our_pond->fly_died(this);
our_pond->unlock();
//fly_dead(); // Here I make use of implied 'this' and af the recursive mutual exclusion pointer
result = 1;
}
else
{
result = 0;
}
return result;
}
};
/****************************************************************************/
/* This is the frog class */
class Frog
{
private:
int last_meal;
Pond *our_pond;
public:
Frog(Pond *a_pond)
{
last_meal = 0;
our_pond = a_pond;
}
// DQ: Added return type.
// starved()
int starved()
{
if(last_meal>FROG_STARVED)
return 1;
else
return 0;
}
void not_hungry()
{
last_meal = 0;
}
Fly *flies_about()
{
Fly *dummy;
our_pond->lock();
dummy = our_pond->flies_about();
our_pond->unlock();
return dummy;
}
void no_dinner()
{
last_meal++;
}
void dead()
{
}
};
/****************************************************************************/
/* This is the controlling code - 'main' function */
Pond *the_pond;
// DQ: Added return type.
// ostmain()
int ostmain()
{
//thread_t tid[MAX_FROGS+MAX_FLIES];
//void *arg=NULL;
int i;
the_pond = new Pond;
for( i=0; i<MAX_FLIES; i++)
{
// taskSpawn( NULL, 100, 0, 2000, fly_lifecycle, 0,0,0,0,0,0,0,0,0,0);
taskSpawn( NULL, 100, 0, 2000, &fly_lifecycle, 0,0,0,0,0,0,0,0,0,0);
//thr_create(NULL, NULL, fly_lifecycle, arg, NULL, &tid[i]);
}
for(i=0; i<MAX_FROGS; i++)
{
taskSpawn( NULL, 100, 0, 2000, frog_lifecycle, 0,0,0,0,0,0,0,0,0,0);
//thr_create(NULL, NULL, frog_lifecycle, arg, NULL, &tid[MAX_FLIES+i]);
}
//while(thr_join(NULL,NULL,NULL)==0);
return 0;
}
/***********************************************************************************/
/* Task that models/controls the life of the fly */
/* */
/***********************************************************************************/
int fly_lifecycle()
{
Fly fly(the_pond);
int id;
//thread_t *tid;
//void *arg=NULL;
// This is the life cycle - each time round the fly gets older
while(fly.get_age())
{
// the fly may have been eaten before it lands
fly.lock();
if(!fly.fly_isdead())
{
fly.unlock();
fly.lock();
fly.fly_landed();
fly.unlock();
// sleep(1);
fly.lock();
fly.fly_flying();
fly.unlock();
if(rand() < FLY_BIRTH_RATE)
{
taskSpawn( NULL, 100, 0, 2000, fly_lifecycle, 0,0,0,0,0,0,0,0,0,0);
//tid = new thread_t;
//thr_create(NULL, NULL, fly_lifecycle, arg, NULL, tid);
}
//sleep(1);
fly.lock();
fly.happy_birthday();
fly.unlock();
}
else
{
fly.unlock();
return NULL;
}
}
fly.lock();
fly.fly_dead();
fly.unlock();
return NULL;
}
/***********************************************************************************/
/* Task that models/controls the life of the fro */
/* */
/***********************************************************************************/
int frog_lifecycle()
{
Frog frog(the_pond);
Fly *food;
//thread_t *tid;
//void *arg=NULL;
while(!frog.starved())
{
if((food = (Fly *)frog.flies_about()) != NULL)
{
food->lock();
if(food->grab()==1) // try to catch a fly and eat it. Then think about giving birth
{
frog.not_hungry();
if(rand() < FROG_BIRTH_RATE)
{
taskSpawn( NULL, 100, 0, 2000, frog_lifecycle, 0,0,0,0,0,0,0,0,0,0);
// tid = new thread_t;
//thr_create(NULL, NULL, frog_lifecycle, arg, NULL, tid);
}
}
else
frog.no_dinner();
food->unlock();
}
else
{
// The frog gets closer to starving
frog.no_dinner();
}
// sleep(2);
}
frog.dead();
return NULL;
}
| 18.631579 | 107 | 0.479791 |
ouankou
|
657b6e05c0b450096ec97900a9be50fd856371f9
| 10,078 |
cpp
|
C++
|
eX0/src/PolyBoolean/pbpolys.cpp
|
shurcooL/eX0
|
425cdd4bace184bef3b63efa0867add4e469e291
|
[
"MIT"
] | 54 |
2015-03-09T08:38:12.000Z
|
2021-06-20T15:54:57.000Z
|
eX0/src/PolyBoolean/pbpolys.cpp
|
shurcooL/eX0
|
425cdd4bace184bef3b63efa0867add4e469e291
|
[
"MIT"
] | 7 |
2015-03-02T21:03:54.000Z
|
2017-12-21T06:06:00.000Z
|
eX0/src/PolyBoolean/pbpolys.cpp
|
shurcooL/eX0
|
425cdd4bace184bef3b63efa0867add4e469e291
|
[
"MIT"
] | 10 |
2015-03-11T06:38:38.000Z
|
2021-05-10T04:35:33.000Z
|
// pbpolys.cpp - basic operations with vertices and polygons
//
// This file is a part of PolyBoolean software library
// (C) 1998-1999 Michael Leonov
// Consult your license regarding permissions and restrictions
//
// fix: 2006 Oct 2 Alexey Nikitin
// PLINE2::Prepare / left middle point from 3 points on the same line
#include "polybool.h"
#include "pbimpl.h"
#define SETBITS(n,mask,s) (((n)->Flags & ~(mask)) | ((s) & mask))
namespace POLYBOOLEAN
{
////////////////////// class VNODE2 /////////////////////////////
VNODE2 * VNODE2::New(const GRID2 & g)
{
VNODE2 * res = (VNODE2 *)calloc(1, sizeof(VNODE2));
if (res == NULL)
error(err_no_memory);
res->g = g;
res->prev = res->next = res;
return res;
} // VNODE2::New
//////////////////// class PLINE2 /////////////////////////
local
void AdjustBox(PLINE2 * pline, const GRID2 & g)
{
if (pline->gMin.x > g.x)
pline->gMin.x = g.x;
if (pline->gMin.y > g.y)
pline->gMin.y = g.y;
if (pline->gMax.x < g.x)
pline->gMax.x = g.x;
if (pline->gMax.y < g.y)
pline->gMax.y = g.y;
} // AdjustBox
local
bool GridInBox(const GRID2 & g, const PLINE2 * pline)
{
return (g.x > pline->gMin.x and g.y > pline->gMin.y and
g.x < pline->gMax.x and g.y < pline->gMax.y);
} // GridInBox
local
bool BoxInBox(const PLINE2 * c1, const PLINE2 * c2)
{
return (c1->gMin.x >= c2->gMin.x and
c1->gMin.y >= c2->gMin.y and
c1->gMax.x <= c2->gMax.x and
c1->gMax.y <= c2->gMax.y);
} // BoxInBox
void PLINE2::Del(PLINE2 ** pline)
{
if (*pline == NULL)
return;
VNODE2 *vn;
while ((vn = (*pline)->head->next) != (*pline)->head)
vn->Excl(), free(vn);
free(vn);
free(*pline), *pline = NULL;
} // PLINE2::Del
PLINE2 * PLINE2::New(const GRID2 &g)
{
PLINE2 *res = (PLINE2 *)calloc(1, sizeof(PLINE2));
if (res == NULL)
error(err_no_memory);
try
{
res->head = VNODE2::New(g);
}
catch (int)
{
free(res);
throw;
}
res->gMax = res->gMin = g;
res->Count = 1;
return res;
} // PLINE2::New
local
void InclPlineVnode(PLINE2 *c, VNODE2 *vn)
{
assert(vn != NULL and c != NULL);
vn->Incl(c->head->prev);
c->Count++;
AdjustBox(c, vn->g);
} // InclPlineVnode
void PLINE2::Incl(PLINE2 ** pline, const GRID2 & g)
{
if (*pline == NULL)
*pline = PLINE2::New(g);
else
InclPlineVnode(*pline, VNODE2::New(g));
} // PLINE2::Incl
PLINE2 * PLINE2::Copy(bool bMakeLinks) const
{
PLINE2 * dst = NULL;
VNODE2* vn = head;
try
{
do {
Incl(&dst, vn->g);
if (bMakeLinks)
(vn->vn = dst->head->prev)->vn = vn;
} while ((vn = vn->next) != head);
}
catch (int)
{
Del(&dst);
throw;
}
dst->Count = Count;
dst->Flags = Flags;
dst->gMin = gMin;
dst->gMax = gMax;
return dst;
} // PLINE2::Copy
// returns if b lies on (a,c)
local
bool PointOnLine(const GRID2 & a, const GRID2 & b, const GRID2 & c)
{
return (INT64)(b.x - a.x) * (c.y - b.y) ==
(INT64)(b.y - a.y) * (c.x - b.x);
} // PointOnLine
bool PLINE2::Prepare()
{
gMin.x = gMax.x = head->g.x;
gMin.y = gMax.y = head->g.y;
// remove coincident vertices and those lying on the same line
VNODE2 * p = head;
VNODE2 * c = p->next;
for (int test = 0, tests = Count; test < tests; ++test)
{
VNODE2 * n = c->next;
if (PointOnLine(p->g, c->g, n->g))
{
++tests;
if (n == head)
++tests;
--Count;
if (Count < 3)
return false;
if (c == head)
head = p;
c->Excl(), free(c);
p = (c = p)->prev;
}
else
{
p = c;
c = n;
}
}
c = head;
p = c->prev;
INT64 nArea = 0;
do {
nArea += (INT64)(p->g.x - c->g.x) * (p->g.y + c->g.y);
AdjustBox(this, c->g);
} while ((c = (p = c)->next) != head);
if (nArea == 0)
return false;
Flags = SETBITS(this, ORIENT, (nArea < 0) ? INV : DIR);
return true;
} // PLINE2::Prepare
void PLINE2::Invert()
{
VNODE2 *vn = head, *next;
do {
next = vn->next, vn->next = vn->prev, vn->prev = next;
} while ((vn = next) != head);
Flags ^= ORIENT;
} // PLINE2::Invert
/********************** PAREA stuff **********************************/
PAREA *PAREA::New()
{
PAREA *res = (PAREA *)calloc(1, sizeof(PAREA));
if (res == NULL)
error(err_no_memory);
return res->f = res->b = res;
} // PAREA::New
local
void ClearArea(PAREA *P)
{
PLINE2 *p;
assert(P != NULL);
while ((p = P->cntr) != NULL)
{
P->cntr = p->next;
PLINE2::Del(&p);
}
free(P->tria), P->tria = NULL;
P->tnum = 0;
} // ClearArea
void PAREA::Del(PAREA ** p)
{
if (*p == NULL)
return;
PAREA *cur;
while ((cur = (*p)->f) != *p)
{
(cur->b->f = cur->f)->b = cur->b;
ClearArea(cur);
free(cur);
}
ClearArea(cur);
free(cur), *p = NULL;
} // PAREA::Del
local
void InclPareaPline(PAREA * p, PLINE2 * c)
{
assert(c->next == NULL);
if (c->IsOuter())
{
assert(p->cntr == NULL);
p->cntr = c;
}
else
{
assert(p->cntr != NULL);
c->next = p->cntr->next, p->cntr->next = c;
}
} // InclPareaPline
void PAREA::InclParea(PAREA **list, PAREA *a)
{
if (a != NULL)
{
if (*list == NULL)
*list = a;
else
(((a->b = (*list)->b)->f = a)->f = *list)->b = a;
}
} // PAREA::InclParea
void PAREA::InclPline(PAREA ** area, PLINE2 * pline)
{
assert(pline != NULL and pline->next == NULL);
PAREA * t;
if (pline->IsOuter())
{
t = New();
InclParea(area, t);
}
else
{
assert(*area != NULL);
// find the smallest container for the hole
t = NULL;
PAREA * pa = *area;
do {
if (PlineInPline(pline, pa->cntr) and
(t == NULL or PlineInPline(pa->cntr, t->cntr)))
t = pa;
} while ((pa = pa->f) != *area);
if (t == NULL) // couldn't find a container for the hole
error(err_bad_parm);
}
InclPareaPline(t, pline);
} // PAREA::InclPline
void PLINE2::Put(PLINE2 * pline, PAREA ** area, PLINE2 ** holes)
{
assert(pline->next == NULL);
if (pline->IsOuter())
PAREA::InclPline(area, pline);
else
pline->next = *holes, *holes = pline;
} // PLINE2::Put
void PAREA::InsertHoles(PAREA ** area, PLINE2 ** holes)
{
if (*holes == NULL)
return;
if (*area == NULL)
error(err_bad_parm);
while (*holes != NULL)
{
PLINE2 * next = (*holes)->next;
(*holes)->next = NULL;
InclPline(area, *holes);
*holes = next;
}
} // PAREA::InsertHoles
local
PAREA * PareaCopy0(const PAREA * area)
{
PAREA * dst = NULL;
try
{
for (const PLINE2 * pline = area->cntr; pline != NULL; pline = pline->next)
PAREA::InclPline(&dst, pline->Copy(true));
if (area->tria == NULL)
return dst;
dst->tria = (PTRIA2 *)calloc(area->tnum, sizeof(PTRIA2));
if (dst->tria == NULL)
error(err_no_memory);
}
catch (int)
{
PAREA::Del(&dst);
throw;
}
dst->tnum = area->tnum;
for (UINT32 i = 0; i < area->tnum; i++)
{
PTRIA2 * td = dst->tria + i;
PTRIA2 * ts = area->tria + i;
td->v0 = ts->v0->vn;
td->v1 = ts->v1->vn;
td->v2 = ts->v2->vn;
}
return dst;
} // PareaCopy0
PAREA * PAREA::Copy() const
{
PAREA * dst = NULL;
const PAREA *src = this;
try
{
do {
PAREA *di = PareaCopy0(src);
InclParea(&dst, di);
} while ((src = src->f) != this);
}
catch (int)
{
Del(&dst);
throw;
}
return dst;
} // PAREA::Copy
bool GridInPline(const GRID2 * g, const PLINE2 * outer)
{
if (outer == NULL)
return false;
if (!GridInBox(*g, outer))
return false;
const VNODE2 *vn = outer->head;
bool bInside = false;
do {
const GRID2 & vc = vn->g;
const GRID2 & vp = vn->prev->g;
if (vc.y <= g->y and g->y < vp.y and
(INT64)(vp.y - vc.y) * (g->x - vc.x) <
(INT64)(g->y - vc.y) * (vp.x - vc.x))
{
bInside = not bInside;
}
else if (vp.y <= g->y and g->y < vc.y and
(INT64)(vp.y - vc.y) * (g->x - vc.x) >
(INT64)(g->y - vc.y) * (vp.x - vc.x))
{
bInside = not bInside;
}
} while ((vn = vn->next) != outer->head);
return bInside;
} // GridInPline
bool PlineInPline(const PLINE2 * p, const PLINE2 * outer)
{
assert(p != NULL);
return outer != NULL && BoxInBox(p, outer) and
GridInPline(&p->head->g, outer);
} // PlineInPline
typedef bool (*INSIDE_PROC)(const void *p, const PLINE2 *outer);
local
bool PolyInside(const void *p, const PAREA * outfst, INSIDE_PROC ins_actor)
{
const PAREA * pa = outfst;
if (pa == NULL)
return false;
assert(p != NULL && pa != NULL);
do {
const PLINE2 *curc = pa->cntr;
if (ins_actor(p, curc))
{
while ((curc = curc->next) != NULL)
if (ins_actor(p, curc))
goto Proceed;
return true;
}
Proceed: ;
} while ((pa = pa->f) != outfst);
return false;
} // PolyInside
bool GridInParea(const GRID2 * g, const PAREA * outer)
{
return PolyInside(g, outer, (INSIDE_PROC)GridInPline);
} // GridInParea
bool PlineInParea(const PLINE2* p, const PAREA * outer)
{
return PolyInside(p, outer, (INSIDE_PROC)PlineInPline);
} // PlineInParea
#ifndef NDEBUG
local
bool Chk(INT32 x)
{
return INT20_MIN > x or x > INT20_MAX;
}
bool PAREA::CheckDomain()
{
PAREA * pa = this;
do {
for (PLINE2 * pline = pa->cntr; pline != NULL; pline = pline->next)
{
if (Chk(pline->gMin.x) or
Chk(pline->gMin.y) or
Chk(pline->gMax.x) or
Chk(pline->gMax.y))
return false;
}
} while ((pa = pa->f) != this);
return true;
} // PAREA::CheckDomain
#endif // NDEBUG
} // namespace POLYBOOLEAN
| 21.261603 | 78 | 0.513991 |
shurcooL
|
6583b3d93fb5f4885db405c9f64563c26ccf25f8
| 5,709 |
hpp
|
C++
|
sources/SceneGraph/Animation/spAnimationJoint.hpp
|
rontrek/softpixel
|
73a13a67e044c93f5c3da9066eedbaf3805d6807
|
[
"Zlib"
] | 14 |
2015-08-16T21:05:20.000Z
|
2019-08-21T17:22:01.000Z
|
sources/SceneGraph/Animation/spAnimationJoint.hpp
|
rontrek/softpixel
|
73a13a67e044c93f5c3da9066eedbaf3805d6807
|
[
"Zlib"
] | null | null | null |
sources/SceneGraph/Animation/spAnimationJoint.hpp
|
rontrek/softpixel
|
73a13a67e044c93f5c3da9066eedbaf3805d6807
|
[
"Zlib"
] | 3 |
2020-02-15T09:17:41.000Z
|
2020-05-21T14:10:40.000Z
|
/*
* Animation bone header
*
* This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns)
* See "SoftPixelEngine.hpp" for license information.
*/
#ifndef __SP_ANIMATION_BONE_H__
#define __SP_ANIMATION_BONE_H__
#include "Base/spStandard.hpp"
#include "Base/spInputOutputString.hpp"
#include "Base/spDimension.hpp"
#include "Base/spMemoryManagement.hpp"
#include "SceneGraph/spSceneMesh.hpp"
#include "Base/spTransformation3D.hpp"
#include "SceneGraph/Animation/spAnimationBaseStructures.hpp"
#include <vector>
namespace sp
{
namespace scene
{
class AnimationSkeleton;
/**
Animation joints are the foundation of animation skeletons (used for skeletal animations).
\see AnimationSkeleton.
\ingroup group_animation
*/
class SP_EXPORT AnimationJoint : public BaseObject
{
public:
AnimationJoint(
const Transformation &OriginTransform, const io::stringc Name = ""
);
virtual ~AnimationJoint();
/* === Functions === */
//! Returns the global joint transformation.
virtual dim::matrix4f getGlobalTransformation() const;
//! Returns the final vertex transformation. Use this to transform the vertices by yourself.
virtual dim::matrix4f getVertexTransformation() const;
/* === Inline functions === */
/**
Enables or disables the bone. If disabled the bone won't be transformed automatically by the animation
but you can still transform it manual. By default enabled.
\todo RENAME this to "setAutoTransform"
*/
inline void setEnable(bool Enable) // !TODO! -> RENAME this to "setAutoTransform"
{
isEnable_ = Enable;
}
inline bool getEnable() const
{
return isEnable_;
}
//! Returns a pointer to the AnimationJoint parent object.
inline AnimationJoint* getParent() const
{
return Parent_;
}
//! Sets the vertex groups list.
inline void setVertexGroups(const std::vector<SVertexGroup> &VertexGroups)
{
VertexGroups_ = VertexGroups;
}
inline const std::vector<SVertexGroup>& getVertexGroups() const
{
return VertexGroups_;
}
inline std::vector<SVertexGroup>& getVertexGroups()
{
return VertexGroups_;
}
//! Sets the new (local) origin transformation. Internally the origin transformation is stored as inverse matrix.
inline void setOriginTransformation(const Transformation &Transform)
{
OriginTransform_ = Transform;
}
inline Transformation getOriginTransformation() const
{
return OriginTransform_;
}
//! Sets the new (local) current transformation.
inline void setTransformation(const Transformation &Transform)
{
Transform_ = Transform;
}
inline const Transformation& getTransformation() const
{
return Transform_;
}
inline Transformation& getTransformation()
{
return Transform_;
}
//! Returns the final origin matrix which will be computed when the "AnimationSkeleton::updateSkeleton" function is called.
inline dim::matrix4f getOriginMatrix() const
{
return OriginMatrix_;
}
//! Returns the joint children list.
inline const std::vector<AnimationJoint*>& getChildren() const
{
return Children_;
}
protected:
friend class AnimationSkeleton;
/* === Functions === */
/**
Transforms the vertices of the specified Mesh object. Which vertices will be transformed depends on
the bone's vertex groups.
\param[in] MeshObj Specifies the mesh object which vertices are to be transformed. This pointer must never be null!
\param[in] BaseMatrix: Specifies the base matrix transformation. If the bone has a parent this matrix should be
its parent's matrix transformation.
\param[in] useTangentSpace: Specifies whether tanget space is used or not.
\note The pointer is not checked for validity!
*/
void transformVertices(scene::Mesh* MeshObj, dim::matrix4f BaseMatrix, bool useTangentSpace) const;
bool checkParentIncest(AnimationJoint* Joint) const;
/* === Inline functions === */
inline void setParent(AnimationJoint* Parent)
{
Parent_ = Parent;
}
inline void addChild(AnimationJoint* Child)
{
Children_.push_back(Child);
}
inline void removeChild(AnimationJoint* Child)
{
MemoryManager::removeElement(Children_, Child);
}
private:
/* === Members === */
bool isEnable_;
AnimationJoint* Parent_;
std::vector<AnimationJoint*> Children_;
Transformation OriginTransform_; //!< Origin transformation.
Transformation Transform_; //!< Current transformation.
dim::matrix4f OriginMatrix_; //!< Final origin transformation matrix. Stored as inverse matrix for combining with the current transformation.
std::vector<SVertexGroup> VertexGroups_;
};
} // /namespace scene
} // /namespace sp
#endif
// ================================================================================
| 29.890052 | 156 | 0.602207 |
rontrek
|
65871db5c93f24650df9b1659e5d6c4b4852db33
| 5,497 |
cpp
|
C++
|
atcoder/marathon/rcl-contest-2020-qual/b.cpp
|
knuu/competitive-programming
|
16bc68fdaedd6f96ae24310d697585ca8836ab6e
|
[
"MIT"
] | 1 |
2018-11-12T15:18:55.000Z
|
2018-11-12T15:18:55.000Z
|
atcoder/marathon/rcl-contest-2020-qual/b.cpp
|
knuu/competitive-programming
|
16bc68fdaedd6f96ae24310d697585ca8836ab6e
|
[
"MIT"
] | null | null | null |
atcoder/marathon/rcl-contest-2020-qual/b.cpp
|
knuu/competitive-programming
|
16bc68fdaedd6f96ae24310d697585ca8836ab6e
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iostream>
#include <vector>
#include <chrono>
#include <random>
#include <tuple>
#include <utility>
#include <queue>
#include <cstdio>
#include <iomanip>
const int dr[4] = {-1, 1, 0, 0};
const int dc[4] = {0, 0, -1, 1};
int N, M;
std::vector<std::vector<int>> board, conn, tunnel;
std::vector<std::vector<bool>> used;
std::vector<int> conn_colors;
int n_conn;
const std::string DIR = "UDLR";
const int colors[4] = {0, 1, 2, 3};
int calc_score(std::vector<std::vector<int>> &ans) {
int ret = 0;
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
ret += ans[r][c] == board[r][c];
}
}
return ret;
}
void input() {
std::cin >> N >> M;
board.resize(N);
for (int i = 0; i < N; i++) {
board[i].resize(N);
for (int j = 0; j < N; j++) std::cin >> board[i][j];
}
}
void output(const std::vector<std::tuple<int, int, int>> &ans) {
for (std::tuple<int, int, int> t : ans) {
int r, c, d; std::tie(r, c, d) = t;
if (r == -1) {
std::cout << -1 << '\n';
} else {
std::cout << r << ' ' << c << ' ' << DIR[d] << '\n';
}
}
}
inline bool in_board(const int r, const int c) {
return 0 <= r and r < N and 0 <= c and c < N;
}
void dfs(int r, int c, int color) {
if (board[r][c] == color) {
conn[r][c] = n_conn;
}
used[r][c] = true;
for (int d = 0; d < 4; d++) {
int nr = r + dr[d], nc = c + dc[d];
if (not in_board(nr, nc) or (board[nr][nc] != color and (tunnel[nr][nc] >> color & 1) == 0)) continue;
if (used[nr][nc]) continue;
dfs(nr, nc, color);
}
}
void create_tunnel_sub() {
conn.assign(N, std::vector<int>(N, -1));
conn_colors.clear();
n_conn = 0;
/* 連結成分の色塗り */
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
if (conn[r][c] == -1) {
used.assign(N, std::vector<bool>(N, false));
dfs(r, c, board[r][c]);
n_conn++;
conn_colors.emplace_back(board[r][c]);
}
}
}
if (n_conn == 4) return;
/*
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
std::cerr << std::setw(2) << conn[r][c];
}
std::cerr << std::endl;
}
*/
/* 各連結成分に対して、同じ色の連結成分が出るまで探索し、
1 番近い連結成分までトンネルを掘る
*/
for (int i = 0; i < n_conn; i++) {
std::queue<std::tuple<int, int, int>> que;
std::vector<std::vector<int>> dists(N, std::vector<int>(N, N * N)),
prev(N, std::vector<int>(N, -1));
for (int r = 0; r < N; r++) for (int c = 0; c < N; c++) {
if (conn[r][c] == i) que.emplace(r, c, 0), dists[r][c] = 0;
}
while (not que.empty()) {
int r, c, dist; std::tie(r, c, dist) = que.front(); que.pop();
if (dists[r][c] < dist) continue;
if (conn[r][c] != i and board[r][c] == conn_colors[i]) {
int nr = prev[r][c] / N, nc = prev[r][c] % N;
r = nr, c = nc;
while (prev[r][c] != -1) {
tunnel[r][c] |= 1 << conn_colors[i];
nr = prev[r][c] / N, nc = prev[r][c] % N;
r = nr, c = nc;
}
break;
}
for (int i = 0; i < 4; i++) {
int nr = r + dr[i], nc = c + dc[i];
if (in_board(nr, nc) and dists[nr][nc] > dist + 1) {
dists[nr][nc] = dist + 1;
prev[nr][nc] = r * N + c;
que.emplace(nr, nc, dist + 1);
}
}
}
}
}
void create_tunnel() {
tunnel.assign(N, std::vector<int>(N, 0));
while (true) {
create_tunnel_sub();
if (n_conn == 4) break;
}
}
void solve() {
// create tunnnel
create_tunnel();
///*
for (int i = 0; i < 4; i++) {
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
std::cerr << ((tunnel[r][c] >> i & 1) | (board[r][c] == i));
//for (int i = 0; i < 4; i++) std::cerr << (tunnel[r][c] >> i & 1);
//std::cerr << ' ';
//std::cerr << conn[r][c] << ' ';
}
std::cerr << '\n';
}
std::cerr << '\n';
}
//*/
// coloring greedy
std::vector<std::vector<int>> colored(N, std::vector<int>(N, -1));
colored[0][0] = 0, colored[0][N-1] = 1, colored[N-1][0] = 2, colored[N-1][N-1] = 3;
std::vector<std::tuple<int, int, int>> ans(M);
for (int m = 0; m < M; m++) {
int color = colors[m % 4];
int cr = -1, cc = -1, cd = -1, up_score = -1;
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
if (colored[r][c] != color) continue;
for (int d = 0; d < 4; d++) {
int cand_score = 0;
for (int res_cnt = 5, nr = r, nc = c; res_cnt >= 0 and in_board(nr, nc);
res_cnt--, nr += dr[d], nc += dc[d]) {
if (board[nr][nc] == color and (m >= M - 41 or tunnel[nr][nc] == 0)) cand_score += 10;
if (colored[nr][nc] == board[nr][nc] and (m >= M - 41 or tunnel[nr][nc] == 0)) cand_score -= 10;
if (m < M - 41 and (tunnel[nr][nc] >> color & 1) and colored[nr][nc] != color) cand_score += 3;
if (colored[nr][nc] == -1) cand_score++;
}
if (cand_score > up_score) {
cr = r, cc = c, cd = d;
up_score = cand_score;
}
}
}
}
if (cr != -1) {
for (int res_cnt = 5, nr = cr, nc = cc; res_cnt >= 0 and in_board(nr, nc);
res_cnt--, nr += dr[cd], nc += dc[cd]) {
colored[nr][nc] = color;
}
}
ans[m] = std::make_tuple(cr, cc, cd);
}
std::cerr << calc_score(colored) << '\n';
output(ans);
}
int main() {
input();
n_conn = 0;
solve();
return 0;
}
| 26.814634 | 108 | 0.458978 |
knuu
|
658aabb1147a7a406e2f86a21215a02bc2ec3809
| 2,304 |
cpp
|
C++
|
ctable.cpp
|
Rescator7/Hearts
|
e72e46c5a1f90a0a553bf5527ee9a5aabf5154d7
|
[
"MIT"
] | 13 |
2018-11-19T00:11:52.000Z
|
2022-03-31T20:01:49.000Z
|
ctable.cpp
|
Rescator7/Hearts
|
e72e46c5a1f90a0a553bf5527ee9a5aabf5154d7
|
[
"MIT"
] | 3 |
2019-10-22T18:46:03.000Z
|
2022-03-31T18:16:48.000Z
|
ctable.cpp
|
Rescator7/Hearts
|
e72e46c5a1f90a0a553bf5527ee9a5aabf5154d7
|
[
"MIT"
] | 2 |
2020-10-12T11:34:11.000Z
|
2021-01-21T07:12:56.000Z
|
#ifdef ONLINE_PLAY
#include "ctable.h"
#include "define.h"
#include "ui_ctable.h"
CTable::CTable(QWidget *parent) :
QWidget(parent),
ui(new Ui::CTable)
{
ui->setupUi(this);
ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
setWindowTitle(tr("Tables list"));
setAttribute( Qt::WA_QuitOnClose, false );
}
CTable::~CTable()
{
delete ui;
}
void CTable::AddRow(QString id, QString flags)
{
int rowc = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(rowc);
QTableWidgetItem *item_id = new QTableWidgetItem(id);
ui->tableWidget->setItem(rowc, 0, item_id);
QString s;
int i = flags.toInt();
if (i & QUEEN_SPADE_f) s += "Q ";
if (i & PERFECT_100_f) s += "P ";
if (i & OMNIBUS_f) s += "O ";
if (i & NO_TRICK_BONUS_f) s += "T ";
if (i & NEW_MOON_f) s += "M ";
if (!(i & NO_DRAW_f)) s += "D";
QTableWidgetItem *item_flags = new QTableWidgetItem(s);
ui->tableWidget->setItem(rowc, 1, item_flags);
for (int i=0; i<4; i++) {
QTableWidgetItem *empty_item = new QTableWidgetItem("");
ui->tableWidget->setItem(rowc, i+2, empty_item);
}
}
void CTable::Empty()
{
ui->tableWidget->setRowCount(0);
}
void CTable::RemoveRow(QString id)
{
int rowc = ui->tableWidget->rowCount();
for (int i=0; i<rowc; i++) {
if (ui->tableWidget->item(i, 0)->text() == id) {
ui->tableWidget->removeRow(i); // by removing a row, the index changes, don't forget to break.
break;
}
}
}
void CTable::SetPlayer(QString id, QString name, QString chair)
{
int rowc = ui->tableWidget->rowCount();
int c = 0;
if (chair == "n") c = 2;
else
if (chair == "s") c = 3;
else
if (chair == "w") c = 4;
else
if (chair == "e") c = 5;
if (!c) return;
for (int i=0; i<rowc; i++) {
if (ui->tableWidget->item(i, 0)->text() == id) {
ui->tableWidget->item(i, c)->setText(name);
}
}
}
void CTable::on_tableWidget_cellDoubleClicked(int row, int column)
{
int id = ui->tableWidget->item(row, 0)->text().toInt();
char chair = ' ';
switch (column) {
case 2: chair = 'n'; break;
case 3: chair = 's'; break;
case 4: chair = 'w'; break;
case 5: chair = 'e'; break;
}
emit clicked(id, chair);
}
void CTable::Translate()
{
ui->retranslateUi(this);
}
#endif // ONLINE_PLAY
| 20.756757 | 100 | 0.608073 |
Rescator7
|
658b5f4b6f51da51cea226963cb6731dd35d2f88
| 13,245 |
cpp
|
C++
|
01_Develop/libXMCocos2D-v3/Source/3d/C3DScene.cpp
|
mcodegeeks/OpenKODE-Framework
|
d4382d781da7f488a0e7667362a89e8e389468dd
|
[
"MIT"
] | 2 |
2017-08-03T07:15:00.000Z
|
2018-06-18T10:32:53.000Z
|
01_Develop/libXMCocos2D-v3/Source/3d/C3DScene.cpp
|
mcodegeeks/OpenKODE-Framework
|
d4382d781da7f488a0e7667362a89e8e389468dd
|
[
"MIT"
] | null | null | null |
01_Develop/libXMCocos2D-v3/Source/3d/C3DScene.cpp
|
mcodegeeks/OpenKODE-Framework
|
d4382d781da7f488a0e7667362a89e8e389468dd
|
[
"MIT"
] | 2 |
2019-03-04T22:57:42.000Z
|
2020-03-06T01:32:26.000Z
|
#include "3d/Base.h"
#include "3d/C3DScene.h"
#include "3d/C3DVector3.h"
#include "3d/C3DRenderNode.h"
#include "3d/C3DCamera.h"
#include "3d/C3DLight.h"
#include "3d/C3DSprite.h"
#include "3d/C3DStaticObj.h"
#include "3d/C3DBatchModel.h"
#include "3d/C3DMaterial.h"
#include "3d/MaterialParameter.h"
#include "3d/C3DRenderChannel.h"
#include "3d/C3DVertexFormat.h"
#include "3d/C3DLayer.h"
#include "3d/C3DBatchMesh.h"
#include "3d/Vertex.h"
#include "3d/C3DStat.h"
#include "3d/C3DShadowMap.h"
#include "3d/C3DRenderSystem.h"
#include "3d/C3DViewport.h"
#include "3d/C3DPostProcess.h"
#include "3d/C3DGeoWireRender.h"
namespace cocos3d
{
C3DNode* C3DScene::findNode(const char* strId)
{
return C3DNode::findNode(strId, true);
}
void C3DScene::removeAllNode()
{
SAFE_RELEASE(_activeLight);
SAFE_RELEASE(_activeCamera);
SAFE_RELEASE(_activeShadowMap);
SAFE_RELEASE(_activePostProcess);
removeAllChildren();
size_t i;
for (i = 0; i < _lights.size(); i++) {
SAFE_RELEASE(_lights[i]);
}
_lights.clear();
for (i = 0; i < _cameras.size(); i++) {
SAFE_RELEASE(_cameras[i]);
}
_cameras.clear();
for (i = 0; i < _shadowMaps.size(); i++) {
SAFE_RELEASE(_shadowMaps[i]);
}
_shadowMaps.clear();
for (i = 0; i < _postProcesss.size(); i++) {
SAFE_RELEASE(_postProcesss[i]);
}
_postProcesss.clear();
}
C3DScene::C3DScene(const char* str) : C3DNode(str)
{
_ambientColor = new C3DVector3();
_showBoundingBox = false;
_showPosAxis = false;
_showScaleAxis = false;
_showLightPos = false;
_activeCamera = NULL;
_activeLight = NULL;
_defDepthZ = 0.5f;
_inShadowPass = false;
_activeShadowMap = NULL;
_activePostProcess = NULL;
_layer = NULL;
_geoWireRender = NULL;
setScene(this);
}
C3DScene::~C3DScene()
{
SAFE_RELEASE(_activeCamera);
SAFE_RELEASE(_activeLight);
SAFE_DELETE(_ambientColor);
removeAllNode();
SAFE_DELETE(_geoWireRender);
}
C3DScene* C3DScene::createScene(C3DLayer* layer)
{
C3DScene* scene = new C3DScene();
scene->_layer = layer;
return scene;
}
C3DCamera* C3DScene::getActiveCamera() const
{
return _activeCamera;
}
//set active camera by index
bool C3DScene::setActiveCamera(int index)
{
if (index < getCameraCount() )
{
if (_activeCamera != _cameras[index])
{
if (_activeCamera)
_activeCamera->release();
_activeCamera = _cameras[index];
_activeCamera->retain();
_activeCamera->setAspectRatio((float)C3DRenderSystem::getInstance()->getViewport()->width/(float)C3DRenderSystem::getInstance()->getViewport()->height);
}
return true;
}
return false;
}
//get number of cameras in the scene
int C3DScene::getCameraCount() const
{
return (int)_cameras.size();
}
C3DLight* C3DScene::getLight(int index)
{
if(index < (int)_lights.size())
return _lights[index];
else
return NULL;
}
void C3DScene::setViewAspectRatio(float aspectRatio)
{
if(getActiveCamera() != NULL)
{
getActiveCamera()->setAspectRatio(aspectRatio);
}
}
const C3DVector3* C3DScene::getAmbientColor() const
{
return _ambientColor;
}
void C3DScene::setAmbientColor(float red, float green, float blue)
{
_ambientColor->set(red, green, blue);
}
void C3DScene::showBoundingBox(bool show)
{
_showBoundingBox = show;
}
void C3DScene::showLight(bool show)
{
_showLightPos = show;
}
void C3DScene::drawLights()
{
for (std::vector<C3DLight*>::iterator iter = _lights.begin(); iter != _lights.end(); ++iter)
{
C3DLight* light = *iter;
C3DVector3 pos =light->getTranslationWorld();
C3DVector4 color;
if (light->getLightType() == C3DLight::DIRECTIONAL)
color = C3DVector4(1,0,0,1);
else if (light->getLightType() == C3DLight::POINT)
color = C3DVector4(0,1,0,1);
else if (light->getLightType() == C3DLight::SPOT)
color = C3DVector4(0,0,1,1);
C3DVector3 offsetX(0.2f, 0.0f, 0.0f);
C3DVector3 offsetY(0.0f, 0.2f, 0.0f);
C3DVector3 offsetZ(0.0f, 0.0f, 0.2f);
C3DGeoWireRender* render = getGeoWireRender();
render->add3DLine(pos + offsetX, pos - offsetX, color);
render->add3DLine(pos + offsetY, pos - offsetY, color);
render->add3DLine(pos + offsetZ, pos - offsetZ, color);
}
}
C3DGeoWireRender* C3DScene::getGeoWireRender()
{
if (_geoWireRender == NULL)
{
_geoWireRender = new C3DGeoWireRender();
C3DNode* node = C3DNode::create("geowirerender");
this->addChild(node);
_geoWireRender->init(node);
}
return _geoWireRender;
}
void C3DScene::drawDebug()
{
for (size_t i = 0; i < _children.size(); i++)
{
_children[i]->drawDebug();
}
// show lights
if (_showLightPos)
drawLights();
if (_geoWireRender)
_geoWireRender->flush();
}
void C3DScene::preDraw()
{
C3DStat::getInstance()->beginStat();
C3DRenderSystem::getInstance()->getRenderChannelManager()->clearChannelItems();
if (_activeShadowMap && _activeShadowMap->active())
{
_inShadowPass = true;
_activeShadowMap->beginDraw();
//draw scene
bool bStatEnable = C3DStat::getInstance()->isStatEnable();
for (size_t i = 0; i < _children.size(); ++i)
{
C3DNode* node = _children[i];
if(node->active())
{
node->draw();
if (bStatEnable)
C3DStat::getInstance()->incTriangleTotal(node->getTriangleCount());
}
}
_activeShadowMap->endDraw();
_inShadowPass = false;
}
//....posteffect start ....
if (_activePostProcess && _activePostProcess->active())
{
_activePostProcess->beginDraw();
}
//....posteffect end.......
}
void C3DScene::draw()
{
// C3DNode::draw();
bool bStatEnable = C3DStat::getInstance()->isStatEnable();
size_t i;
for (i = 0; i < _children.size(); ++i)
{
C3DNode* node = _children[i];
if(node->active())
{
node->draw();
if (bStatEnable)
C3DStat::getInstance()->incTriangleTotal(node->getTriangleCount());
}
}
}
void C3DScene::drawCameraAndLight()
{
// to do.. draw cameras and lights
}
void C3DScene::postDraw()
{
C3DRenderSystem::getInstance()->getRenderChannelManager()->draw();
C3DStat::getInstance()->endStat();
//....posteffect start ....
if (_activePostProcess && _activePostProcess->active())
{
_activePostProcess->endDraw();
_activePostProcess->draw();
}
//....posteffect end.......
}
// update routine
void C3DScene::update(long elapsedTime)
{
//update children then
// C3DNode::update(elapsedTime);
size_t i;
for (i = 0; i < _children.size(); ++i)
{
C3DNode* node = _children[i];
if(node->active())
node->update(elapsedTime);
}
if (_geoWireRender)
_geoWireRender->begin();
}
C3DNode::Type C3DScene::getType() const
{
return C3DNode::NodeType_Scene;
}
void C3DScene::addNodeToRenderList(C3DNode* node)
{
node->setScene(this);
C3DNode::Type type = node->getType();
switch (type)
{
case C3DNode::NodeType_Camera:
{
bool found = false;
for (std::vector<C3DCamera*>::iterator iter=_cameras.begin(); iter!=_cameras.end(); ++iter)
{
if (*iter == node)
{
found = true;
break;
}
}
if (found == false)
{
_cameras.push_back((C3DCamera*)node);
node->retain();
}
else
{
assert(false && "Duplicated camera node!");
}
}
break;
case C3DNode::NodeType_Light:
{
bool found = false;
for (std::vector<C3DLight*>::iterator iter=_lights.begin(); iter!=_lights.end(); ++iter)
{
if (*iter == node)
{
found = true;
break;
}
}
if (found == false)
{
_lights.push_back((C3DLight*)node);
node->retain();
}
else
{
assert(false && "Duplicated light node!");
}
}
break;
case C3DNode::NodeType_ShadowMap:
{
bool found = false;
for (std::vector<C3DShadowMap*>::iterator iter=_shadowMaps.begin(); iter!=_shadowMaps.end(); ++iter)
{
if (*iter == node)
{
found = true;
break;
}
}
if (found == false)
{
_shadowMaps.push_back((C3DShadowMap*)node);
node->retain();
}
else
{
assert(false && "Duplicated shadow map node!");
}
}
break;
case C3DNode::NodeType_PostProcess:
{
bool found = false;
for (std::vector<C3DPostProcess*>::iterator iter=_postProcesss.begin(); iter!=_postProcesss.end(); ++iter)
{
if (*iter == node)
{
found = true;
break;
}
}
if (found == false)
{
_postProcesss.push_back((C3DPostProcess*)node);
node->retain();
}
else
{
assert(false && "Duplicated posteffect node!");
}
}
break;
default:
break;
}
for (size_t i = 0; i < node->_children.size(); i++)
{
// addNodeToRenderList(node->_children[i]);
}
}
void C3DScene::removeNodeFromRenderList(C3DNode* node)
{
node->setScene(NULL);
for (size_t i = 0; i < node->_children.size(); i++)
{
// removeNodeFromRenderList(node->_children[i]);
}
C3DNode::Type type = node->getType();
switch (type)
{
case C3DNode::NodeType_Camera:
{
if ( _activeCamera == node)
{
assert(false && "removing active camera");
}
std::vector<C3DCamera*>::iterator it = find(_cameras.begin(), _cameras.end(), (C3DCamera*)node);
if (it != _cameras.end())
{
_cameras.erase(it);
node->release();
}
else
{
assert(false && "unrefereed node");
}
}
break;
case C3DNode::NodeType_Light:
{
std::vector<C3DLight*>::iterator it = find(_lights.begin(), _lights.end(), (C3DLight*)node);
if (it != _lights.end())
{
_lights.erase(it);
node->release();
}
else
{
assert(false && "unrefereed node");
}
break;
}
case C3DNode::NodeType_ShadowMap:
{
std::vector<C3DShadowMap*>::iterator it = find(_shadowMaps.begin(), _shadowMaps.end(), (C3DShadowMap*)node);
if (it != _shadowMaps.end())
{
_shadowMaps.erase(it);
node->release();
}
else
{
assert(false && "unrefereed node");
}
break;
}
case C3DNode::NodeType_PostProcess:
{
std::vector<C3DPostProcess*>::iterator it = find(_postProcesss.begin(), _postProcesss.end(), (C3DPostProcess*)node);
if (it != _postProcesss.end())
{
_postProcesss.erase(it);
node->release();
}
else
{
assert(false && "unrefereed node");
}
break;
}
default:
break;
}
}
void C3DScene::onChildChanged(ChangeEvent eventType, C3DNode* child)
{
switch (eventType)
{
case C3DNode::ADD:
addNodeToRenderList(child);
break;
case C3DNode::REMOVE:
removeNodeFromRenderList(child);
break;
}
}
const C3DMatrix& C3DScene::getViewProjectionMatrix() const
{
if (_inShadowPass)
{
CCAssert(_activeShadowMap, "active shadow map!");
return _activeShadowMap->getViewProjectionMatrix();
}
else
{
if (_activeCamera)
return _activeCamera->getViewProjectionMatrix();
else
return C3DMatrix::identity();
}
}
C3DShadowMap* C3DScene::getActiveShadowMap() const
{
return _activeShadowMap;
}
C3DShadowMap* C3DScene::setActiveShadowMap(int index)
{
C3DShadowMap* sm;
if (index >= 0 && index < (int)_shadowMaps.size())
sm = _shadowMaps[index];
else
sm = NULL;
if (sm != _activeShadowMap)
{
SAFE_RELEASE(_activeShadowMap);
_activeShadowMap = sm;
_activeShadowMap->retain();
}
return _activeShadowMap;
}
int C3DScene::GetShadowMapCount() const
{
return (int)_shadowMaps.size();
}
C3DPostProcess* C3DScene::getActivePostProcess() const
{
return _activePostProcess;
}
C3DPostProcess* C3DScene::setActivePostProcess(int index)
{
C3DPostProcess* pp;
if (index >= 0 && index < (int)_postProcesss.size())
pp = _postProcesss[index];
else
pp = NULL;
if(pp == NULL)
{
SAFE_RELEASE(_activePostProcess);
}
else if (pp != _activePostProcess)
{
SAFE_RELEASE(_activePostProcess);
_activePostProcess = pp;
_activePostProcess->retain();
}
return _activePostProcess;
}
C3DLayer* C3DScene::getLayer() const
{
return _layer;
}
void C3DScene::setLayer(C3DLayer* layer)
{
if (layer != _layer)
{
SAFE_RELEASE(_layer);
_layer = layer;
if (layer)
{
layer->retain();
}
}
}
}
| 20.598756 | 156 | 0.588373 |
mcodegeeks
|
6590b799fd04541ed819819c4b6bac8f524eba26
| 687 |
cpp
|
C++
|
src/script_interface/DropSourceAction.cpp
|
kbuffington/foo_jscript_panel
|
8e8375c109595b18e624e8709ee6d84effba66b4
|
[
"MIT"
] | 15 |
2020-02-20T19:39:54.000Z
|
2022-02-06T10:03:00.000Z
|
src/script_interface/DropSourceAction.cpp
|
kbuffington/foo_jscript_panel
|
8e8375c109595b18e624e8709ee6d84effba66b4
|
[
"MIT"
] | 1 |
2020-04-26T04:02:44.000Z
|
2020-04-26T04:02:44.000Z
|
src/script_interface/DropSourceAction.cpp
|
kbuffington/foo_jscript_panel
|
8e8375c109595b18e624e8709ee6d84effba66b4
|
[
"MIT"
] | 2 |
2020-04-24T11:09:45.000Z
|
2021-05-21T08:41:39.000Z
|
#include "stdafx.h"
#include "DropSourceAction.h"
DropSourceAction::DropSourceAction() {}
DropSourceAction::~DropSourceAction() {}
void DropSourceAction::FinalRelease() {}
STDMETHODIMP DropSourceAction::get_Effect(UINT* p)
{
if (!p) return E_POINTER;
*p = m_effect;
return S_OK;
}
STDMETHODIMP DropSourceAction::put_Base(UINT base)
{
m_base = base;
return S_OK;
}
STDMETHODIMP DropSourceAction::put_Effect(UINT effect)
{
m_effect = effect;
return S_OK;
}
STDMETHODIMP DropSourceAction::put_Playlist(UINT id)
{
m_playlist_idx = id;
return S_OK;
}
STDMETHODIMP DropSourceAction::put_ToSelect(VARIANT_BOOL select)
{
m_to_select = select != VARIANT_FALSE;
return S_OK;
}
| 16.756098 | 64 | 0.756914 |
kbuffington
|
6590d71a0949a66233120069104b8f4dc05e9e49
| 991 |
cpp
|
C++
|
UVa/11241.cpp
|
tico88612/Solution-Note
|
31a9d220fd633c6920760707a07c9a153c2f76cc
|
[
"MIT"
] | 1 |
2018-02-11T09:41:54.000Z
|
2018-02-11T09:41:54.000Z
|
UVa/11241.cpp
|
tico88612/Solution-Note
|
31a9d220fd633c6920760707a07c9a153c2f76cc
|
[
"MIT"
] | null | null | null |
UVa/11241.cpp
|
tico88612/Solution-Note
|
31a9d220fd633c6920760707a07c9a153c2f76cc
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
double T=-999999,D=-999999,H=-999999;
double dohum(double tt,double dd){
double ee=6.11*exp(5417.7530*((1/273.16)-(1/(dd+273.16))));
double hh=(0.5555)*(ee-10.0);
return tt+hh;
}
double dotemp(){
double ee=6.11*exp(5417.7530*((1/273.16)-(1/(D+273.16))));
double hh=(0.5555)*(ee-10.0);
return H-hh;
}
double dodew(){
double ans=0;
double delta=100;
for(delta=100;delta>0.00001;delta*=0.5){
if(dohum(T,ans)>H) ans-=delta;
else ans+=delta;
}
return ans;
}
int main(){
char e1,e2;
double t1,t2;
while(scanf(" %c",&e1)&&e1!='E'){
scanf("%lf %c %lf",&t1,&e2,&t2);
if(e1=='T')
T=t1;
else if(e1=='D')
D=t1;
else if(e1=='H')
H=t1;
if(e2=='T')
T=t2;
else if(e2=='D')
D=t2;
else if(e2=='H')
H=t2;
if(T==-999999)
T=dotemp();
else if(D==-999999)
D=dodew();
else if(H==-999999)
H=dohum(T,D);
printf("T %0.1lf D %0.1lf H %0.1lf\n",T,D,H);
T=-999999;
D=-999999;
H=-999999;
}
return 0;
}
| 19.057692 | 60 | 0.565086 |
tico88612
|
6594a2eb329a534b7fef1a53777d488e87f37a03
| 76,327 |
cpp
|
C++
|
source/ff.graphics/source/draw_device.cpp
|
spadapet/ff_game_library
|
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
|
[
"MIT"
] | null | null | null |
source/ff.graphics/source/draw_device.cpp
|
spadapet/ff_game_library
|
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
|
[
"MIT"
] | null | null | null |
source/ff.graphics/source/draw_device.cpp
|
spadapet/ff_game_library
|
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "depth.h"
#include "draw_device.h"
#include "graphics.h"
#include "matrix.h"
#include "matrix_stack.h"
#include "palette_data.h"
#include "shader.h"
#include "sprite_data.h"
#include "sprite_type.h"
#include "target_base.h"
#include "texture.h"
#include "texture_view_base.h"
#include "transform.h"
#include "vertex.h"
#if DXVER == 11
static const size_t MAX_TEXTURES = 32;
static const size_t MAX_TEXTURES_USING_PALETTE = 32;
static const size_t MAX_PALETTES = 128; // 256 color palettes only
static const size_t MAX_PALETTE_REMAPS = 128; // 256 entries only
static const size_t MAX_TRANSFORM_MATRIXES = 1024;
static const size_t MAX_RENDER_COUNT = 524288; // 0x00080000
static const float MAX_RENDER_DEPTH = 1.0f;
static const float RENDER_DEPTH_DELTA = ::MAX_RENDER_DEPTH / ::MAX_RENDER_COUNT;
static std::array<ID3D11ShaderResourceView*, ::MAX_TEXTURES + ::MAX_TEXTURES_USING_PALETTE + 2 /* palette + remap */> NULL_TEXTURES{};
static std::array<uint8_t, ff::constants::palette_size> DEFAULT_PALETTE_REMAP =
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
};
static size_t DEFAULT_PALETTE_REMAP_HASH = ff::stable_hash_bytes(::DEFAULT_PALETTE_REMAP.data(), ff::array_byte_size(::DEFAULT_PALETTE_REMAP));
namespace
{
enum class alpha_type
{
opaque,
transparent,
invisible,
};
enum class last_depth_type
{
none,
nudged,
line,
circle,
triangle,
sprite,
line_no_overlap,
circle_no_overlap,
triangle_no_overlap,
sprite_no_overlap,
start_no_overlap = line_no_overlap,
};
enum class geometry_bucket_type
{
lines,
circles,
triangles,
sprites,
palette_sprites,
lines_alpha,
circles_alpha,
triangles_alpha,
sprites_alpha,
count,
first_alpha = lines_alpha,
};
class geometry_bucket
{
private:
geometry_bucket(
::geometry_bucket_type bucket_type,
const std::type_info& item_type,
size_t item_size,
size_t item_align,
const D3D11_INPUT_ELEMENT_DESC* element_desc,
size_t element_count)
: bucket_type_(bucket_type)
, item_type_(&item_type)
, item_size_(item_size)
, item_align(item_align)
, render_start_(0)
, render_count_(0)
, data_start(nullptr)
, data_cur(nullptr)
, data_end(nullptr)
, element_desc(element_desc)
, element_count(element_count)
{}
public:
template<typename T, ::geometry_bucket_type BucketType>
static ::geometry_bucket create()
{
return ::geometry_bucket(BucketType, typeid(T), sizeof(T), alignof(T), T::layout().data(), T::layout().size());
}
geometry_bucket(::geometry_bucket&& rhs) noexcept
: vs_res(std::move(rhs.vs_res))
, gs_res(std::move(rhs.gs_res))
, ps_res(std::move(rhs.ps_res))
, ps_palette_out_res(std::move(rhs.ps_palette_out_res))
, layout(std::move(rhs.layout))
, vs(std::move(rhs.vs))
, gs(std::move(rhs.gs))
, ps(std::move(rhs.ps))
, ps_palette_out(std::move(rhs.ps_palette_out))
, element_desc(rhs.element_desc)
, element_count(rhs.element_count)
, bucket_type_(rhs.bucket_type_)
, item_type_(rhs.item_type_)
, item_size_(rhs.item_size_)
, item_align(rhs.item_align)
, render_start_(0)
, render_count_(0)
, data_start(rhs.data_start)
, data_cur(rhs.data_cur)
, data_end(rhs.data_end)
{
rhs.data_start = nullptr;
rhs.data_cur = nullptr;
rhs.data_end = nullptr;
}
~geometry_bucket()
{
::_aligned_free(this->data_start);
}
void reset(std::string_view vs_res, std::string_view gs_res, std::string_view ps_res, std::string_view ps_palette_out_res)
{
this->reset();
this->vs_res = ff::global_resources::get(vs_res);
this->gs_res = ff::global_resources::get(gs_res);
this->ps_res = ff::global_resources::get(ps_res);
this->ps_palette_out_res = ff::global_resources::get(ps_palette_out_res);
}
void reset()
{
this->layout.Reset();
this->vs.Reset();
this->gs.Reset();
this->ps.Reset();
this->ps_palette_out.Reset();
::_aligned_free(this->data_start);
this->data_start = nullptr;
this->data_cur = nullptr;
this->data_end = nullptr;
}
void apply(ID3D11Buffer* geometry_buffer, bool palette_out) const
{
const_cast<::geometry_bucket*>(this)->create_shaders(palette_out);
ff_dx::device_state& state = ff_dx::get_device_state();
state.set_vertex_ia(geometry_buffer, item_size(), 0);
state.set_layout_ia(this->layout.Get());
state.set_vs(this->vs.Get());
state.set_gs(this->gs.Get());
state.set_ps(palette_out ? this->ps_palette_out.Get() : this->ps.Get());
}
void* add(const void* data = nullptr)
{
if (this->data_cur == this->data_end)
{
size_t cur_size = this->data_end - this->data_start;
size_t new_size = std::max<size_t>(cur_size * 2, this->item_size_ * 64);
this->data_start = reinterpret_cast<uint8_t*>(_aligned_realloc(this->data_start, new_size, this->item_align));
this->data_cur = this->data_start + cur_size;
this->data_end = this->data_start + new_size;
}
if (this->data_cur && data)
{
std::memcpy(this->data_cur, data, this->item_size_);
}
void* result = this->data_cur;
this->data_cur += this->item_size_;
return result;
}
size_t item_size() const
{
return this->item_size_;
}
const std::type_info& item_type() const
{
return *this->item_type_;
}
::geometry_bucket_type bucket_type() const
{
return this->bucket_type_;
}
size_t count() const
{
return (this->data_cur - this->data_start) / this->item_size_;
}
void clear_items()
{
this->data_cur = this->data_start;
}
size_t byte_size() const
{
return this->data_cur - this->data_start;
}
const uint8_t* data() const
{
return this->data_start;
}
void render_start(size_t start)
{
this->render_start_ = start;
this->render_count_ = this->count();
}
size_t render_start() const
{
return this->render_start_;
}
size_t render_count() const
{
return this->render_count_;
}
private:
void create_shaders(bool palette_out)
{
if (!this->vs)
{
this->vs = ff_dx::get_object_cache().get_vertex_shader_and_input_layout(this->vs_res.resource()->name(), this->layout, this->element_desc, this->element_count);
}
if (!this->gs)
{
this->gs = ff_dx::get_object_cache().get_geometry_shader(this->gs_res.resource()->name());
}
Microsoft::WRL::ComPtr<ID3D11PixelShader>& ps = palette_out ? this->ps_palette_out : this->ps;
if (!ps)
{
ps = ff_dx::get_object_cache().get_pixel_shader(palette_out ? this->ps_palette_out_res.resource()->name() : this->ps_res.resource()->name());
}
}
ff::auto_resource<ff::shader> vs_res;
ff::auto_resource<ff::shader> gs_res;
ff::auto_resource<ff::shader> ps_res;
ff::auto_resource<ff::shader> ps_palette_out_res;
Microsoft::WRL::ComPtr<ID3D11InputLayout> layout;
Microsoft::WRL::ComPtr<ID3D11VertexShader> vs;
Microsoft::WRL::ComPtr<ID3D11GeometryShader> gs;
Microsoft::WRL::ComPtr<ID3D11PixelShader> ps;
Microsoft::WRL::ComPtr<ID3D11PixelShader> ps_palette_out;
const D3D11_INPUT_ELEMENT_DESC* element_desc;
size_t element_count;
::geometry_bucket_type bucket_type_;
const std::type_info* item_type_;
size_t item_size_;
size_t item_align;
size_t render_start_;
size_t render_count_;
uint8_t* data_start;
uint8_t* data_cur;
uint8_t* data_end;
};
struct alpha_geometry_entry
{
const ::geometry_bucket* bucket;
size_t index;
float depth;
};
struct geometry_shader_constants_0
{
DirectX::XMFLOAT4X4 projection;
ff::point_float view_size;
ff::point_float view_scale;
float z_offset;
float padding[3];
};
struct geometry_shader_constants_1
{
std::vector<DirectX::XMFLOAT4X4> model;
};
struct pixel_shader_constants_0
{
std::array<ff::rect_float, ::MAX_TEXTURES_USING_PALETTE> texture_palette_sizes;
};
}
namespace std
{
static bool operator==(const DirectX::XMFLOAT4X4& lhs, const DirectX::XMFLOAT4X4& rhs)
{
return ::operator==(lhs, rhs);
}
}
static ::alpha_type get_alpha_type(const DirectX::XMFLOAT4& color, bool force_opaque)
{
if (color.w == 0)
{
return alpha_type::invisible;
}
if (color.w == 1 || force_opaque)
{
return alpha_type::opaque;
}
return alpha_type::transparent;
}
static alpha_type get_alpha_type(const DirectX::XMFLOAT4* colors, size_t count, bool force_opaque)
{
alpha_type type = alpha_type::invisible;
for (size_t i = 0; i < count; i++)
{
switch (::get_alpha_type(colors[i], force_opaque))
{
case alpha_type::opaque:
type = alpha_type::opaque;
break;
case alpha_type::transparent:
return alpha_type::transparent;
}
}
return type;
}
static alpha_type get_alpha_type(const ff::sprite_data& data, const DirectX::XMFLOAT4& color, bool force_opaque)
{
switch (::get_alpha_type(color, force_opaque))
{
case alpha_type::transparent:
return ff::flags::has(data.type(), ff::sprite_type::palette) ? alpha_type::opaque : alpha_type::transparent;
case alpha_type::opaque:
return (ff::flags::has(data.type(), ff::sprite_type::transparent) && !force_opaque)
? alpha_type::transparent
: alpha_type::opaque;
default:
return alpha_type::invisible;
}
}
static alpha_type get_alpha_type(const ff::sprite_data** datas, const DirectX::XMFLOAT4* colors, size_t count, bool force_opaque)
{
alpha_type type = alpha_type::invisible;
for (size_t i = 0; i < count; i++)
{
switch (::get_alpha_type(*datas[i], colors[i], force_opaque))
{
case alpha_type::opaque:
type = alpha_type::opaque;
break;
case alpha_type::transparent:
return alpha_type::transparent;
}
}
return type;
}
static void get_alpha_blend(D3D11_RENDER_TARGET_BLEND_DESC& desc)
{
// newColor = (srcColor * SrcBlend) BlendOp (destColor * DestBlend)
// newAlpha = (srcAlpha * SrcBlendAlpha) BlendOpAlpha (destAlpha * DestBlendAlpha)
desc.BlendEnable = TRUE;
desc.SrcBlend = D3D11_BLEND_SRC_ALPHA;
desc.DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
desc.BlendOp = D3D11_BLEND_OP_ADD;
desc.SrcBlendAlpha = D3D11_BLEND_ONE;
desc.DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
desc.BlendOpAlpha = D3D11_BLEND_OP_ADD;
}
static void get_pre_multiplied_alpha_blend(D3D11_RENDER_TARGET_BLEND_DESC& desc)
{
// newColor = (srcColor * SrcBlend) BlendOp (destColor * DestBlend)
// newAlpha = (srcAlpha * SrcBlendAlpha) BlendOpAlpha (destAlpha * DestBlendAlpha)
desc.BlendEnable = TRUE;
desc.SrcBlend = D3D11_BLEND_ONE;
desc.DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
desc.BlendOp = D3D11_BLEND_OP_ADD;
desc.SrcBlendAlpha = D3D11_BLEND_ONE;
desc.DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
desc.BlendOpAlpha = D3D11_BLEND_OP_ADD;
}
static ID3D11SamplerState* get_texture_sampler_state(D3D11_FILTER filter)
{
CD3D11_SAMPLER_DESC sampler(D3D11_DEFAULT);
sampler.Filter = filter;
return ff_dx::get_object_cache().get_sampler_state(sampler);
}
static ID3D11BlendState* get_opaque_blend_state()
{
CD3D11_BLEND_DESC blend(D3D11_DEFAULT);
return ff_dx::get_object_cache().get_blend_state(blend);
}
static ID3D11BlendState* get_alpha_blend_state()
{
CD3D11_BLEND_DESC blend(D3D11_DEFAULT);
::get_alpha_blend(blend.RenderTarget[0]);
return ff_dx::get_object_cache().get_blend_state(blend);
}
static ID3D11BlendState* get_pre_multiplied_alpha_blend_state()
{
CD3D11_BLEND_DESC blend(D3D11_DEFAULT);
::get_pre_multiplied_alpha_blend(blend.RenderTarget[0]);
return ff_dx::get_object_cache().get_blend_state(blend);
}
static ID3D11DepthStencilState* get_enabled_depth_state()
{
CD3D11_DEPTH_STENCIL_DESC depth(D3D11_DEFAULT);
depth.DepthFunc = D3D11_COMPARISON_GREATER;
return ff_dx::get_object_cache().get_depth_stencil_state(depth);
}
static ID3D11DepthStencilState* get_disabled_depth_state()
{
CD3D11_DEPTH_STENCIL_DESC depth(D3D11_DEFAULT);
depth.DepthEnable = FALSE;
depth.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
return ff_dx::get_object_cache().get_depth_stencil_state(depth);
}
static ID3D11RasterizerState* get_no_cull_raster_state()
{
CD3D11_RASTERIZER_DESC raster(D3D11_DEFAULT);
raster.CullMode = D3D11_CULL_NONE;
return ff_dx::get_object_cache().get_rasterize_state(raster);
}
static ff_dx::fixed_state create_opaque_draw_state()
{
ff_dx::fixed_state state;
state.blend = ::get_opaque_blend_state();
state.depth = ::get_enabled_depth_state();
state.disabled_depth = ::get_disabled_depth_state();
state.raster = ::get_no_cull_raster_state();
return state;
}
static ff_dx::fixed_state create_alpha_draw_state()
{
ff_dx::fixed_state state;
state.blend = ::get_alpha_blend_state();
state.depth = ::get_enabled_depth_state();
state.disabled_depth = ::get_disabled_depth_state();
state.raster = ::get_no_cull_raster_state();
return state;
}
static ff_dx::fixed_state create_pre_multiplied_alpha_draw_state()
{
ff_dx::fixed_state state;
state.blend = ::get_pre_multiplied_alpha_blend_state();
state.depth = ::get_enabled_depth_state();
state.disabled_depth = ::get_disabled_depth_state();
state.raster = ::get_no_cull_raster_state();
return state;
}
static ff::rect_float get_rotated_view_rect(ff::target_base& target, const ff::rect_float& view_rect)
{
ff::window_size size = target.size();
ff::rect_float rotated_view_rect;
switch (size.current_rotation)
{
default:
rotated_view_rect = view_rect;
break;
case DMDO_90:
{
float height = size.rotated_pixel_size().cast<float>().y;
rotated_view_rect.left = height - view_rect.bottom;
rotated_view_rect.top = view_rect.left;
rotated_view_rect.right = height - view_rect.top;
rotated_view_rect.bottom = view_rect.right;
} break;
case DMDO_180:
{
ff::point_float target_size = size.rotated_pixel_size().cast<float>();
rotated_view_rect.left = target_size.x - view_rect.right;
rotated_view_rect.top = target_size.y - view_rect.bottom;
rotated_view_rect.right = target_size.x - view_rect.left;
rotated_view_rect.bottom = target_size.y - view_rect.top;
} break;
case DMDO_270:
{
float width = size.rotated_pixel_size().cast<float>().x;
rotated_view_rect.left = view_rect.top;
rotated_view_rect.top = width - view_rect.right;
rotated_view_rect.right = view_rect.bottom;
rotated_view_rect.bottom = width - view_rect.left;
} break;
}
return rotated_view_rect;
}
static DirectX::XMMATRIX get_view_matrix(const ff::rect_float& world_rect)
{
return DirectX::XMMatrixOrthographicOffCenterLH(
world_rect.left,
world_rect.right,
world_rect.bottom,
world_rect.top,
0, ::MAX_RENDER_DEPTH);
}
static DirectX::XMMATRIX get_orientation_matrix(ff::target_base& target, const ff::rect_float& view_rect, ff::point_float world_center)
{
DirectX::XMMATRIX orientation_matrix;
int degrees = target.size().current_rotation;
switch (degrees)
{
default:
orientation_matrix = DirectX::XMMatrixIdentity();
break;
case DMDO_90:
case DMDO_270:
{
float view_height_per_width = view_rect.height() / view_rect.width();
float view_width_per_height = view_rect.width() / view_rect.height();
orientation_matrix =
DirectX::XMMatrixTransformation2D(
DirectX::XMVectorSet(world_center.x, world_center.y, 0, 0), 0, // scale center
DirectX::XMVectorSet(view_height_per_width, view_width_per_height, 1, 1), // scale
DirectX::XMVectorSet(world_center.x, world_center.y, 0, 0), // rotation center
ff::math::pi<float>() * degrees / 2.0f, // rotation
DirectX::XMVectorZero()); // translation
} break;
case DMDO_180:
orientation_matrix =
DirectX::XMMatrixAffineTransformation2D(
DirectX::XMVectorSet(1, 1, 1, 1), // scale
DirectX::XMVectorSet(world_center.x, world_center.y, 0, 0), // rotation center
ff::math::pi<float>(), // rotation
DirectX::XMVectorZero()); // translation
break;
}
return orientation_matrix;
}
static D3D11_VIEWPORT get_viewport(const ff::rect_float& view_rect)
{
D3D11_VIEWPORT viewport;
viewport.TopLeftX = view_rect.left;
viewport.TopLeftY = view_rect.top;
viewport.Width = view_rect.width();
viewport.Height = view_rect.height();
viewport.MinDepth = 0;
viewport.MaxDepth = 1;
return viewport;
}
static bool setup_view_matrix(ff::target_base& target, const ff::rect_float& view_rect, const ff::rect_float& world_rect, DirectX::XMFLOAT4X4& view_matrix)
{
if (world_rect.width() != 0 && world_rect.height() != 0 && view_rect.width() > 0 && view_rect.height() > 0)
{
DirectX::XMMATRIX unoriented_view_matrix = ::get_view_matrix(world_rect);
DirectX::XMMATRIX orientation_matrix = ::get_orientation_matrix(target, view_rect, world_rect.center());
DirectX::XMStoreFloat4x4(&view_matrix, DirectX::XMMatrixTranspose(orientation_matrix * unoriented_view_matrix));
return true;
}
return false;
}
static bool setup_render_target(ff::target_base& target, ff::depth* depth, const ff::rect_float& view_rect)
{
ID3D11RenderTargetView* target_view = target.view();
if (target_view)
{
ID3D11DepthStencilView* depth_view = nullptr;
if (depth)
{
if (depth->size(target.size().pixel_size))
{
depth->clear(0, 0);
depth_view = depth->view();
}
if (!depth_view)
{
assert(false);
return false;
}
}
ff::rect_float rotated_view_rect = ::get_rotated_view_rect(target, view_rect);
D3D11_VIEWPORT viewport = ::get_viewport(rotated_view_rect);
ff_dx::get_device_state().set_targets(&target_view, 1, depth_view);
ff_dx::get_device_state().set_viewports(&viewport, 1);
return true;
}
assert(false);
return false;
}
namespace
{
class draw_device_internal
: public ff::draw_device
, public ff::draw_base
, private ff::dxgi::device_child_base
{
public:
draw_device_internal()
: state(::draw_device_internal::state_t::invalid)
, world_matrix_stack_changing_connection(this->world_matrix_stack_.matrix_changing().connect(std::bind(&draw_device_internal::matrix_changing, this, std::placeholders::_1)))
, geometry_buffer(ff::dxgi::buffer_type::vertex)
, geometry_constants_buffer_0(ff::dxgi::buffer_type::constant)
, geometry_constants_buffer_1(ff::dxgi::buffer_type::constant)
, pixel_constants_buffer_0(ff::dxgi::buffer_type::constant)
, geometry_buckets
{
::geometry_bucket::create<ff::vertex::line_geometry, ::geometry_bucket_type::lines>(),
::geometry_bucket::create<ff::vertex::circle_geometry, ::geometry_bucket_type::circles>(),
::geometry_bucket::create<ff::vertex::triangle_geometry, ::geometry_bucket_type::triangles>(),
::geometry_bucket::create<ff::vertex::sprite_geometry, ::geometry_bucket_type::sprites>(),
::geometry_bucket::create<ff::vertex::sprite_geometry, ::geometry_bucket_type::palette_sprites>(),
::geometry_bucket::create<ff::vertex::line_geometry, ::geometry_bucket_type::lines_alpha>(),
::geometry_bucket::create<ff::vertex::circle_geometry, ::geometry_bucket_type::circles_alpha>(),
::geometry_bucket::create<ff::vertex::triangle_geometry, ::geometry_bucket_type::triangles_alpha>(),
::geometry_bucket::create<ff::vertex::sprite_geometry, ::geometry_bucket_type::sprites_alpha>(),
}
{
this->reset();
ff_dx::add_device_child(this, ff_dx::device_reset_priority::normal);
}
virtual ~draw_device_internal() override
{
assert(this->state != ::draw_device_internal::state_t::drawing);
ff_dx::remove_device_child(this);
}
draw_device_internal(draw_device_internal&& other) noexcept = delete;
draw_device_internal(const draw_device_internal& other) = delete;
draw_device_internal& operator=(draw_device_internal&& other) noexcept = delete;
draw_device_internal& operator=(const draw_device_internal& other) = delete;
virtual bool valid() const override
{
return this->state != ::draw_device_internal::state_t::invalid;
}
virtual ff::draw_ptr begin_draw(ff::target_base& target, ff::depth* depth, const ff::rect_float& view_rect, const ff::rect_float& world_rect, ff::draw_options options) override
{
this->end_draw();
if (::setup_view_matrix(target, view_rect, world_rect, this->view_matrix) &&
::setup_render_target(target, depth, view_rect))
{
this->init_geometry_constant_buffers_0(target, view_rect, world_rect);
this->target_requires_palette = ff::dxgi::palette_format(target.format());
this->force_pre_multiplied_alpha = ff::flags::has(options, ff::draw_options::pre_multiplied_alpha) && ff::dxgi::supports_pre_multiplied_alpha(target.format()) ? 1 : 0;
this->state = ::draw_device_internal::state_t::drawing;
return this;
}
return nullptr;
}
virtual void end_draw() override
{
if (this->state == state_t::drawing)
{
this->flush();
ff_dx::get_device_state().set_resources_ps(::NULL_TEXTURES.data(), 0, ::NULL_TEXTURES.size());
this->state = ::draw_device_internal::state_t::valid;
this->palette_stack.resize(1);
this->palette_remap_stack.resize(1);
this->sampler_stack.resize(1);
this->custom_context_stack.clear();
this->world_matrix_stack_.reset();
this->draw_depth = 0;
this->force_no_overlap = 0;
this->force_opaque = 0;
this->force_pre_multiplied_alpha = 0;
}
}
virtual void draw_sprite(const ff::sprite_data& sprite, const ff::transform& transform) override
{
::alpha_type alpha_type = ::get_alpha_type(sprite, transform.color, this->force_opaque || this->target_requires_palette);
if (alpha_type != ::alpha_type::invisible && sprite.view())
{
bool use_palette = ff::flags::has(sprite.type(), ff::sprite_type::palette);
::geometry_bucket_type bucket_type = (alpha_type == ::alpha_type::transparent && !this->target_requires_palette)
? (use_palette ? ::geometry_bucket_type::palette_sprites : ::geometry_bucket_type::sprites_alpha)
: (use_palette ? ::geometry_bucket_type::palette_sprites : ::geometry_bucket_type::sprites);
float depth = this->nudge_depth(this->force_no_overlap ? ::last_depth_type::sprite_no_overlap : ::last_depth_type::sprite);
ff::vertex::sprite_geometry& input = *reinterpret_cast<ff::vertex::sprite_geometry*>(this->add_geometry(nullptr, bucket_type, depth));
this->get_world_matrix_and_texture_index(*sprite.view(), use_palette, input.matrix_index, input.texture_index);
input.position.x = transform.position.x;
input.position.y = transform.position.y;
input.position.z = depth;
input.scale = *reinterpret_cast<const DirectX::XMFLOAT2*>(&transform.scale);
input.rotate = transform.rotation_radians();
input.color = transform.color;
input.uv_rect = *reinterpret_cast<const DirectX::XMFLOAT4*>(&sprite.texture_uv());
input.rect = *reinterpret_cast<const DirectX::XMFLOAT4*>(&sprite.world());
}
}
virtual void draw_line_strip(const ff::point_float* points, const DirectX::XMFLOAT4* colors, size_t count, float thickness, bool pixel_thickness) override
{
this->draw_line_strip(points, count, colors, count, thickness, pixel_thickness);
}
virtual void draw_line_strip(const ff::point_float* points, size_t count, const DirectX::XMFLOAT4& color, float thickness, bool pixel_thickness) override
{
this->draw_line_strip(points, count, &color, 1, thickness, pixel_thickness);
}
virtual void draw_line(const ff::point_float& start, const ff::point_float& end, const DirectX::XMFLOAT4& color, float thickness, bool pixel_thickness) override
{
const ff::point_float points[2] = { start, end };
this->draw_line_strip(points, 2, color, thickness, pixel_thickness);
}
virtual void draw_filled_rectangle(const ff::rect_float& rect, const DirectX::XMFLOAT4* colors) override
{
const float tri_points[12] =
{
rect.left, rect.top,
rect.right, rect.top,
rect.right, rect.bottom,
rect.right, rect.bottom,
rect.left, rect.bottom,
rect.left, rect.top,
};
const DirectX::XMFLOAT4 tri_colors[6] =
{
colors[0],
colors[1],
colors[2],
colors[2],
colors[3],
colors[0],
};
this->draw_filled_triangles(reinterpret_cast<const ff::point_float*>(tri_points), tri_colors, 2);
}
virtual void draw_filled_rectangle(const ff::rect_float& rect, const DirectX::XMFLOAT4& color) override
{
const float tri_points[12] =
{
rect.left, rect.top,
rect.right, rect.top,
rect.right, rect.bottom,
rect.right, rect.bottom,
rect.left, rect.bottom,
rect.left, rect.top,
};
const DirectX::XMFLOAT4 tri_colors[6] =
{
color,
color,
color,
color,
color,
color,
};
this->draw_filled_triangles(reinterpret_cast<const ff::point_float*>(tri_points), tri_colors, 2);
}
virtual void draw_filled_triangles(const ff::point_float* points, const DirectX::XMFLOAT4* colors, size_t count) override
{
ff::vertex::triangle_geometry input;
input.matrix_index = (this->world_matrix_index == ff::constants::invalid_dword) ? this->get_world_matrix_index() : this->world_matrix_index;
input.depth = this->nudge_depth(this->force_no_overlap ? ::last_depth_type::triangle_no_overlap : ::last_depth_type::triangle);
for (size_t i = 0; i < count; i++, points += 3, colors += 3)
{
std::memcpy(input.position, points, sizeof(input.position));
std::memcpy(input.color, colors, sizeof(input.color));
::alpha_type alpha_type = ::get_alpha_type(colors, 3, this->force_opaque || this->target_requires_palette);
if (alpha_type != ::alpha_type::invisible)
{
::geometry_bucket_type bucket_type = (alpha_type == ::alpha_type::transparent) ? ::geometry_bucket_type::triangles_alpha : ::geometry_bucket_type::triangles;
this->add_geometry(&input, bucket_type, input.depth);
}
}
}
virtual void draw_filled_circle(const ff::point_float& center, float radius, const DirectX::XMFLOAT4& color) override
{
this->draw_outline_circle(center, radius, color, color, std::abs(radius), false);
}
virtual void draw_filled_circle(const ff::point_float& center, float radius, const DirectX::XMFLOAT4& inside_color, const DirectX::XMFLOAT4& outside_color) override
{
this->draw_outline_circle(center, radius, inside_color, outside_color, std::abs(radius), false);
}
virtual void draw_outline_rectangle(const ff::rect_float& rect, const DirectX::XMFLOAT4& color, float thickness, bool pixel_thickness) override
{
ff::rect_float rect2 = rect.normalize();
if (thickness < 0)
{
ff::point_float deflate = this->geometry_constants_0.view_scale * thickness;
rect2 = rect2.deflate(deflate);
this->draw_outline_rectangle(rect2, color, -thickness, pixel_thickness);
}
else if (!pixel_thickness && (thickness * 2 >= rect2.width() || thickness * 2 >= rect2.height()))
{
this->draw_filled_rectangle(rect2, color);
}
else
{
ff::point_float half_thickness(thickness / 2, thickness / 2);
if (pixel_thickness)
{
half_thickness *= this->geometry_constants_0.view_scale;
}
rect2 = rect2.deflate(half_thickness);
const ff::point_float points[5] =
{
rect2.top_left(),
rect2.top_right(),
rect2.bottom_right(),
rect2.bottom_left(),
rect2.top_left(),
};
this->draw_line_strip(points, 5, color, thickness, pixel_thickness);
}
}
virtual void draw_outline_circle(const ff::point_float& center, float radius, const DirectX::XMFLOAT4& color, float thickness, bool pixel_thickness) override
{
this->draw_outline_circle(center, radius, color, color, thickness, pixel_thickness);
}
virtual void draw_outline_circle(const ff::point_float& center, float radius, const DirectX::XMFLOAT4& inside_color, const DirectX::XMFLOAT4& outside_color, float thickness, bool pixel_thickness) override
{
ff::vertex::circle_geometry input;
input.matrix_index = (this->world_matrix_index == ff::constants::invalid_dword) ? this->get_world_matrix_index() : this->world_matrix_index;
input.position.x = center.x;
input.position.y = center.y;
input.position.z = this->nudge_depth(this->force_no_overlap ? ::last_depth_type::circle_no_overlap : ::last_depth_type::circle);
input.radius = std::abs(radius);
input.thickness = pixel_thickness ? -std::abs(thickness) : std::min(std::abs(thickness), input.radius);
input.inside_color = inside_color;
input.outside_color = outside_color;
::alpha_type alpha_type = ::get_alpha_type(&input.inside_color, 2, this->force_opaque || this->target_requires_palette);
if (alpha_type != ::alpha_type::invisible)
{
::geometry_bucket_type bucket_type = (alpha_type == ::alpha_type::transparent) ? ::geometry_bucket_type::circles_alpha : ::geometry_bucket_type::circles;
this->add_geometry(&input, bucket_type, input.position.z);
}
}
virtual void draw_palette_line_strip(const ff::point_float* points, const int* colors, size_t count, float thickness, bool pixel_thickness) override
{
ff::stack_vector<DirectX::XMFLOAT4, 64> colors2;
colors2.resize(count);
for (size_t i = 0; i != colors2.size(); i++)
{
ff::palette_index_to_color(this->remap_palette_index(colors[i]), colors2[i]);
}
this->draw_line_strip(points, count, colors2.data(), count, thickness, pixel_thickness);
}
virtual void draw_palette_line_strip(const ff::point_float* points, size_t count, int color, float thickness, bool pixel_thickness) override
{
DirectX::XMFLOAT4 color2;
ff::palette_index_to_color(this->remap_palette_index(color), color2);
this->draw_line_strip(points, count, &color2, 1, thickness, pixel_thickness);
}
virtual void draw_palette_line(const ff::point_float& start, const ff::point_float& end, int color, float thickness, bool pixel_thickness) override
{
DirectX::XMFLOAT4 color2;
ff::palette_index_to_color(this->remap_palette_index(color), color2);
this->draw_line(start, end, color2, thickness, pixel_thickness);
}
virtual void draw_palette_filled_rectangle(const ff::rect_float& rect, const int* colors) override
{
std::array<DirectX::XMFLOAT4, 4> colors2;
for (size_t i = 0; i != colors2.size(); i++)
{
ff::palette_index_to_color(this->remap_palette_index(colors[i]), colors2[i]);
}
this->draw_filled_rectangle(rect, colors2.data());
}
virtual void draw_palette_filled_rectangle(const ff::rect_float& rect, int color) override
{
DirectX::XMFLOAT4 color2;
ff::palette_index_to_color(this->remap_palette_index(color), color2);
this->draw_filled_rectangle(rect, color2);
}
virtual void draw_palette_filled_triangles(const ff::point_float* points, const int* colors, size_t count) override
{
ff::stack_vector<DirectX::XMFLOAT4, 64 * 3> colors2;
colors2.resize(count * 3);
for (size_t i = 0; i != colors2.size(); i++)
{
ff::palette_index_to_color(this->remap_palette_index(colors[i]), colors2[i]);
}
this->draw_filled_triangles(points, colors2.data(), count);
}
virtual void draw_palette_filled_circle(const ff::point_float& center, float radius, int color) override
{
DirectX::XMFLOAT4 color2;
ff::palette_index_to_color(this->remap_palette_index(color), color2);
this->draw_filled_circle(center, radius, color2);
}
virtual void draw_palette_filled_circle(const ff::point_float& center, float radius, int inside_color, int outside_color) override
{
DirectX::XMFLOAT4 inside_color2, outside_color2;
ff::palette_index_to_color(this->remap_palette_index(inside_color), inside_color2);
ff::palette_index_to_color(this->remap_palette_index(outside_color), outside_color2);
this->draw_filled_circle(center, radius, inside_color2, outside_color2);
}
virtual void draw_palette_outline_rectangle(const ff::rect_float& rect, int color, float thickness, bool pixel_thickness) override
{
DirectX::XMFLOAT4 color2;
ff::palette_index_to_color(this->remap_palette_index(color), color2);
this->draw_outline_rectangle(rect, color2, thickness, pixel_thickness);
}
virtual void draw_palette_outline_circle(const ff::point_float& center, float radius, int color, float thickness, bool pixel_thickness) override
{
DirectX::XMFLOAT4 color2;
ff::palette_index_to_color(this->remap_palette_index(color), color2);
this->draw_outline_circle(center, radius, color2, thickness, pixel_thickness);
}
virtual void draw_palette_outline_circle(const ff::point_float& center, float radius, int inside_color, int outside_color, float thickness, bool pixel_thickness) override
{
DirectX::XMFLOAT4 inside_color2, outside_color2;
ff::palette_index_to_color(this->remap_palette_index(inside_color), inside_color2);
ff::palette_index_to_color(this->remap_palette_index(outside_color), outside_color2);
this->draw_outline_circle(center, radius, inside_color2, outside_color2, thickness, pixel_thickness);
}
virtual ff::matrix_stack& world_matrix_stack() override
{
return this->world_matrix_stack_;
}
virtual void nudge_depth() override
{
this->last_depth_type = ::last_depth_type::nudged;
}
virtual void push_palette(ff::palette_base* palette) override
{
assert(!this->target_requires_palette && palette);
this->palette_stack.push_back(palette);
this->palette_index = ff::constants::invalid_dword;
this->push_palette_remap(palette->index_remap(), palette->index_remap_hash());
}
virtual void pop_palette() override
{
assert(this->palette_stack.size() > 1);
this->palette_stack.pop_back();
this->palette_index = ff::constants::invalid_dword;
this->pop_palette_remap();
}
virtual void push_palette_remap(const uint8_t* remap, size_t hash) override
{
this->palette_remap_stack.push_back(std::make_pair(
remap ? remap : ::DEFAULT_PALETTE_REMAP.data(),
remap ? (hash ? hash : ff::stable_hash_bytes(remap, ff::constants::palette_size)) : ::DEFAULT_PALETTE_REMAP_HASH));
this->palette_remap_index = ff::constants::invalid_dword;
}
virtual void pop_palette_remap() override
{
assert(this->palette_remap_stack.size() > 1);
this->palette_remap_stack.pop_back();
this->palette_remap_index = ff::constants::invalid_dword;
}
virtual void push_no_overlap() override
{
this->force_no_overlap++;
}
virtual void pop_no_overlap() override
{
assert(this->force_no_overlap > 0);
if (!--this->force_no_overlap)
{
this->nudge_depth();
}
}
virtual void push_opaque() override
{
this->force_opaque++;
}
virtual void pop_opaque() override
{
assert(this->force_opaque > 0);
this->force_opaque--;
}
virtual void push_pre_multiplied_alpha() override
{
if (!this->force_pre_multiplied_alpha)
{
this->flush();
}
this->force_pre_multiplied_alpha++;
}
virtual void pop_pre_multiplied_alpha() override
{
assert(this->force_pre_multiplied_alpha > 0);
if (this->force_pre_multiplied_alpha == 1)
{
this->flush();
}
this->force_pre_multiplied_alpha--;
}
virtual void push_custom_context(ff::draw_base::custom_context_func&& func) override
{
this->flush();
this->custom_context_stack.push_back(std::move(func));
}
virtual void pop_custom_context() override
{
assert(this->custom_context_stack.size());
this->flush();
this->custom_context_stack.pop_back();
}
virtual void push_sampler_linear_filter(bool linear_filter) override
{
this->flush();
this->sampler_stack.push_back(::get_texture_sampler_state(linear_filter
? D3D11_FILTER_MIN_MAG_MIP_LINEAR
: D3D11_FILTER_MIN_MAG_MIP_POINT));
}
virtual void pop_sampler_linear_filter() override
{
assert(this->sampler_stack.size() > 1);
this->flush();
this->sampler_stack.pop_back();
}
private:
// device_child_base
virtual bool reset()
{
this->destroy();
// Geometry buckets
this->get_geometry_bucket(::geometry_bucket_type::lines).reset("ff.shader.line_vs", "ff.shader.line_gs", "ff.shader.color_ps", "ff.shader.palette_out_color_ps");
this->get_geometry_bucket(::geometry_bucket_type::circles).reset("ff.shader.circle_vs", "ff.shader.circle_gs", "ff.shader.color_ps", "ff.shader.palette_out_color_ps");
this->get_geometry_bucket(::geometry_bucket_type::triangles).reset("ff.shader.triangle_vs", "ff.shader.triangle_gs", "ff.shader.color_ps", "ff.shader.palette_out_color_ps");
this->get_geometry_bucket(::geometry_bucket_type::sprites).reset("ff.shader.sprite_vs", "ff.shader.sprite_gs", "ff.shader.sprite_ps", "ff.shader.palette_out_sprite_ps");
this->get_geometry_bucket(::geometry_bucket_type::palette_sprites).reset("ff.shader.sprite_vs", "ff.shader.sprite_gs", "ff.shader.sprite_palette_ps", "ff.shader.palette_out_sprite_palette_ps");
this->get_geometry_bucket(::geometry_bucket_type::lines_alpha).reset("ff.shader.line_vs", "ff.shader.line_gs", "ff.shader.color_ps", "ff.shader.palette_out_color_ps");
this->get_geometry_bucket(::geometry_bucket_type::circles_alpha).reset("ff.shader.circle_vs", "ff.shader.circle_gs", "ff.shader.color_ps", "ff.shader.palette_out_color_ps");
this->get_geometry_bucket(::geometry_bucket_type::triangles_alpha).reset("ff.shader.triangle_vs", "ff.shader.triangle_gs", "ff.shader.color_ps", "ff.shader.palette_out_color_ps");
this->get_geometry_bucket(::geometry_bucket_type::sprites_alpha).reset("ff.shader.sprite_vs", "ff.shader.sprite_gs", "ff.shader.sprite_ps", "ff.shader.palette_out_sprite_ps");
// Palette
this->palette_stack.push_back(nullptr);
this->palette_texture = std::make_shared<ff::texture>(
ff::point_size(ff::constants::palette_size, ::MAX_PALETTES).cast<int>(), ff::dxgi::PALETTE_FORMAT);
this->palette_remap_stack.push_back(std::make_pair(::DEFAULT_PALETTE_REMAP.data(), ::DEFAULT_PALETTE_REMAP_HASH));
this->palette_remap_texture = std::make_shared<ff::texture>(
ff::point_size(ff::constants::palette_size, ::MAX_PALETTE_REMAPS).cast<int>(), ff::dxgi::PALETTE_INDEX_FORMAT);
// States
this->sampler_stack.push_back(::get_texture_sampler_state(D3D11_FILTER_MIN_MAG_MIP_POINT));
this->opaque_state = ::create_opaque_draw_state();
this->alpha_state = ::create_alpha_draw_state();
this->pre_multiplied_alpha_state = ::create_pre_multiplied_alpha_draw_state();
this->state = ::draw_device_internal::state_t::valid;
return true;
}
void destroy()
{
this->state = ::draw_device_internal::state_t::invalid;
this->geometry_constants_0 = ::geometry_shader_constants_0{};
this->geometry_constants_1 = ::geometry_shader_constants_1{};
this->pixel_constants_0 = ::pixel_shader_constants_0{};
this->geometry_constants_hash_0 = 0;
this->geometry_constants_hash_1 = 0;
this->pixel_constants_hash_0 = 0;
this->sampler_stack.clear();
this->opaque_state = ff_dx::fixed_state();
this->alpha_state = ff_dx::fixed_state();
this->pre_multiplied_alpha_state = ff_dx::fixed_state();
this->custom_context_stack.clear();
this->view_matrix = ff::matrix::identity_4x4();
this->world_matrix_stack_.reset();
this->world_matrix_to_index.clear();
this->world_matrix_index = ff::constants::invalid_dword;
std::memset(this->textures.data(), 0, ff::array_byte_size(this->textures));
std::memset(this->textures_using_palette.data(), 0, ff::array_byte_size(this->textures_using_palette));
this->texture_count = 0;
this->textures_using_palette_count = 0;
std::memset(this->palette_texture_hashes.data(), 0, ff::array_byte_size(this->palette_texture_hashes));
this->palette_stack.clear();
this->palette_to_index.clear();
this->palette_texture = nullptr;
this->palette_index = ff::constants::invalid_dword;
std::memset(this->palette_remap_texture_hashes.data(), 0, ff::array_byte_size(this->palette_remap_texture_hashes));
this->palette_remap_stack.clear();
this->palette_remap_to_index.clear();
this->palette_remap_texture = nullptr;
this->palette_remap_index = ff::constants::invalid_dword;
this->alpha_geometry.clear();
this->last_depth_type = ::last_depth_type::none;
this->draw_depth = 0;
this->force_no_overlap = 0;
this->force_opaque = 0;
this->force_pre_multiplied_alpha = 0;
for (auto& bucket : this->geometry_buckets)
{
bucket.reset();
}
}
void matrix_changing(const ff::matrix_stack& matrix_stack)
{
this->world_matrix_index = ff::constants::invalid_dword;
}
void draw_line_strip(const ff::point_float* points, size_t point_count, const DirectX::XMFLOAT4* colors, size_t color_count, float thickness, bool pixel_thickness)
{
assert(color_count == 1 || color_count == point_count);
thickness = pixel_thickness ? -std::abs(thickness) : std::abs(thickness);
ff::vertex::line_geometry input;
input.matrix_index = (this->world_matrix_index == ff::constants::invalid_dword) ? this->get_world_matrix_index() : this->world_matrix_index;
input.depth = this->nudge_depth(this->force_no_overlap ? ::last_depth_type::line_no_overlap : ::last_depth_type::line);
input.color[0] = colors[0];
input.color[1] = colors[0];
input.thickness[0] = thickness;
input.thickness[1] = thickness;
const DirectX::XMFLOAT2* dxpoints = reinterpret_cast<const DirectX::XMFLOAT2*>(points);
bool closed = point_count > 2 && points[0] == points[point_count - 1];
::alpha_type alpha_type = ::get_alpha_type(colors[0], this->force_opaque || this->target_requires_palette);
for (size_t i = 0; i < point_count - 1; i++)
{
input.position[1] = dxpoints[i];
input.position[2] = dxpoints[i + 1];
input.position[0] = (i == 0)
? (closed ? dxpoints[point_count - 2] : dxpoints[i])
: dxpoints[i - 1];
input.position[3] = (i == point_count - 2)
? (closed ? dxpoints[1] : dxpoints[i + 1])
: dxpoints[i + 2];
if (color_count != 1)
{
input.color[0] = colors[i];
input.color[1] = colors[i + 1];
alpha_type = ::get_alpha_type(colors + i, 2, this->force_opaque || this->target_requires_palette);
}
if (alpha_type != ::alpha_type::invisible)
{
::geometry_bucket_type bucket_type = (alpha_type == ::alpha_type::transparent) ? ::geometry_bucket_type::lines_alpha : ::geometry_bucket_type::lines;
this->add_geometry(&input, bucket_type, input.depth);
}
}
}
void init_geometry_constant_buffers_0(ff::target_base& target, const ff::rect_float& view_rect, const ff::rect_float& world_rect)
{
this->geometry_constants_0.view_size = view_rect.size() / static_cast<float>(target.size().dpi_scale);
this->geometry_constants_0.view_scale = world_rect.size() / this->geometry_constants_0.view_size;
}
void update_geometry_constant_buffers_0()
{
this->geometry_constants_0.projection = this->view_matrix;
size_t hash0 = ff::stable_hash_func(this->geometry_constants_0);
if (!this->geometry_constants_hash_0 || this->geometry_constants_hash_0 != hash0)
{
this->geometry_constants_buffer_0.update(ff_dx::get_device_state(), &this->geometry_constants_0, sizeof(::geometry_shader_constants_0));
this->geometry_constants_hash_0 = hash0;
}
}
void update_geometry_constant_buffers_1()
{
// Build up model matrix array
size_t world_matrix_count = this->world_matrix_to_index.size();
this->geometry_constants_1.model.resize(world_matrix_count);
for (const auto& iter : this->world_matrix_to_index)
{
this->geometry_constants_1.model[iter.second] = iter.first;
}
size_t hash1 = world_matrix_count
? ff::stable_hash_bytes(this->geometry_constants_1.model.data(), ff::vector_byte_size(this->geometry_constants_1.model))
: 0;
if (!this->geometry_constants_hash_1 || this->geometry_constants_hash_1 != hash1)
{
this->geometry_constants_hash_1 = hash1;
#if _DEBUG
size_t buffer_size = sizeof(DirectX::XMFLOAT4X4) * ::MAX_TRANSFORM_MATRIXES;
#else
size_t buffer_size = sizeof(DirectX::XMFLOAT4X4) * world_matrix_count;
#endif
this->geometry_constants_buffer_1.update(ff_dx::get_device_state(), this->geometry_constants_1.model.data(), ff::vector_byte_size(this->geometry_constants_1.model), buffer_size);
}
}
void update_pixel_constant_buffers_0()
{
if (this->textures_using_palette_count)
{
for (size_t i = 0; i < this->textures_using_palette_count; i++)
{
ff::rect_float& rect = this->pixel_constants_0.texture_palette_sizes[i];
ff::point_float size = this->textures_using_palette[i]->view_texture()->size().cast<float>();
rect.left = size.x;
rect.top = size.y;
}
size_t hash0 = ff::stable_hash_func(this->pixel_constants_0);
if (!this->pixel_constants_hash_0 || this->pixel_constants_hash_0 != hash0)
{
this->pixel_constants_buffer_0.update(ff_dx::get_device_state(), &this->pixel_constants_0, sizeof(::pixel_shader_constants_0));
this->pixel_constants_hash_0 = hash0;
}
}
}
void update_palette_texture()
{
if (this->textures_using_palette_count && !this->palette_to_index.empty())
{
ID3D11Resource* dest_resource = this->palette_texture->dx_texture();
CD3D11_BOX box(0, 0, 0, static_cast<int>(ff::constants::palette_size), 1, 1);
for (const auto& iter : this->palette_to_index)
{
ff::palette_base* palette = iter.second.first;
if (palette)
{
unsigned int index = iter.second.second;
size_t palette_row = palette->current_row();
const ff::palette_data* palette_data = palette->data();
size_t row_hash = palette_data->row_hash(palette_row);
if (this->palette_texture_hashes[index] != row_hash)
{
this->palette_texture_hashes[index] = row_hash;
ID3D11Resource* src_resource = palette_data->texture()->dx_texture();
box.top = static_cast<UINT>(palette_row);
box.bottom = box.top + 1;
ff_dx::get_device_state().copy_subresource_region(dest_resource, 0, 0, index, 0, src_resource, 0, &box);
}
}
}
}
if ((this->textures_using_palette_count || this->target_requires_palette) && !this->palette_remap_to_index.empty())
{
ID3D11Resource* dest_remap_resource = this->palette_remap_texture->dx_texture();
CD3D11_BOX box(0, 0, 0, static_cast<int>(ff::constants::palette_size), 1, 1);
for (const auto& iter : this->palette_remap_to_index)
{
const uint8_t* remap = iter.second.first;
unsigned int row = iter.second.second;
size_t row_hash = iter.first;
if (this->palette_remap_texture_hashes[row] != row_hash)
{
this->palette_remap_texture_hashes[row] = row_hash;
box.top = row;
box.bottom = row + 1;
ff_dx::get_device_state().update_subresource(dest_remap_resource, 0, &box, remap, static_cast<UINT>(ff::constants::palette_size), 0);
}
}
}
}
void set_shader_input()
{
std::array<ID3D11Buffer*, 2> buffers_gs = { this->geometry_constants_buffer_0.dx_buffer(), this->geometry_constants_buffer_1.dx_buffer() };
ff_dx::get_device_state().set_constants_gs(buffers_gs.data(), 0, buffers_gs.size());
std::array<ID3D11Buffer*, 1> buffers_ps = { this->pixel_constants_buffer_0.dx_buffer() };
ff_dx::get_device_state().set_constants_ps(buffers_ps.data(), 0, buffers_ps.size());
std::array<ID3D11SamplerState*, 1> sample_states = { this->sampler_stack.back().Get() };
ff_dx::get_device_state().set_samplers_ps(sample_states.data(), 0, sample_states.size());
if (this->texture_count)
{
std::array<ID3D11ShaderResourceView*, ::MAX_TEXTURES> textures;
for (size_t i = 0; i < this->texture_count; i++)
{
textures[i] = this->textures[i]->view();
}
ff_dx::get_device_state().set_resources_ps(textures.data(), 0, this->texture_count);
}
if (this->textures_using_palette_count)
{
std::array<ID3D11ShaderResourceView*, ::MAX_TEXTURES_USING_PALETTE> textures_using_palette;
for (size_t i = 0; i < this->textures_using_palette_count; i++)
{
textures_using_palette[i] = this->textures_using_palette[i]->view();
}
ff_dx::get_device_state().set_resources_ps(textures_using_palette.data(), ::MAX_TEXTURES, this->textures_using_palette_count);
}
if (this->textures_using_palette_count || this->target_requires_palette)
{
std::array<ID3D11ShaderResourceView*, 2> palettes =
{
(this->textures_using_palette_count ? this->palette_texture->view() : nullptr),
this->palette_remap_texture->view(),
};
ff_dx::get_device_state().set_resources_ps(palettes.data(), ::MAX_TEXTURES + ::MAX_TEXTURES_USING_PALETTE, palettes.size());
}
}
void flush()
{
if (this->last_depth_type != ::last_depth_type::none && this->create_geometry_buffer())
{
this->update_geometry_constant_buffers_0();
this->update_geometry_constant_buffers_1();
this->update_pixel_constant_buffers_0();
this->update_palette_texture();
this->set_shader_input();
this->draw_opaque_geometry();
this->draw_alpha_geometry();
// Reset draw data
this->world_matrix_to_index.clear();
this->world_matrix_index = ff::constants::invalid_dword;
this->palette_to_index.clear();
this->palette_index = ff::constants::invalid_dword;
this->palette_remap_to_index.clear();
this->palette_remap_index = ff::constants::invalid_dword;
this->texture_count = 0;
this->textures_using_palette_count = 0;
this->alpha_geometry.clear();
this->last_depth_type = ::last_depth_type::none;
}
}
bool create_geometry_buffer()
{
size_t byte_size = 0;
for (::geometry_bucket& bucket : this->geometry_buckets)
{
byte_size = ff::math::round_up(byte_size, bucket.item_size());
bucket.render_start(byte_size / bucket.item_size());
byte_size += bucket.byte_size();
}
void* buffer_data = this->geometry_buffer.map(ff_dx::get_device_state(), byte_size);
if (buffer_data)
{
for (::geometry_bucket& bucket : this->geometry_buckets)
{
if (bucket.render_count())
{
::memcpy(reinterpret_cast<uint8_t*>(buffer_data) + bucket.render_start() * bucket.item_size(), bucket.data(), bucket.byte_size());
bucket.clear_items();
}
}
this->geometry_buffer.unmap();
return true;
}
assert(false);
return false;
}
void draw_opaque_geometry()
{
const ff::draw_base::custom_context_func* custom_func = this->custom_context_stack.size() ? &this->custom_context_stack.back() : nullptr;
ff_dx::get_device_state().set_topology_ia(D3D_PRIMITIVE_TOPOLOGY_POINTLIST);
this->opaque_state.apply();
for (::geometry_bucket& bucket : this->geometry_buckets)
{
if (bucket.bucket_type() >= ::geometry_bucket_type::first_alpha)
{
break;
}
if (bucket.render_count())
{
bucket.apply(this->geometry_buffer.dx_buffer(), this->target_requires_palette);
if (!custom_func || (*custom_func)(bucket.item_type(), true))
{
ff_dx::get_device_state().draw(bucket.render_count(), bucket.render_start());
}
}
}
}
void draw_alpha_geometry()
{
const size_t alpha_geometry_size = this->alpha_geometry.size();
if (alpha_geometry_size)
{
const ff::draw_base::custom_context_func* custom_func = this->custom_context_stack.size() ? &this->custom_context_stack.back() : nullptr;
ff_dx::get_device_state().set_topology_ia(D3D_PRIMITIVE_TOPOLOGY_POINTLIST);
ff_dx::fixed_state& alpha_state = this->force_pre_multiplied_alpha ? this->pre_multiplied_alpha_state : this->alpha_state;
alpha_state.apply();
for (size_t i = 0; i < alpha_geometry_size; )
{
const ::alpha_geometry_entry& entry = this->alpha_geometry[i];
size_t geometry_count = 1;
for (i++; i < alpha_geometry_size; i++, geometry_count++)
{
const ::alpha_geometry_entry& entry2 = this->alpha_geometry[i];
if (entry2.bucket != entry.bucket ||
entry2.depth != entry.depth ||
entry2.index != entry.index + geometry_count)
{
break;
}
}
entry.bucket->apply(this->geometry_buffer.dx_buffer(), this->target_requires_palette);
if (!custom_func || (*custom_func)(entry.bucket->item_type(), false))
{
ff_dx::get_device_state().draw(geometry_count, entry.bucket->render_start() + entry.index);
}
}
}
}
float nudge_depth(::last_depth_type depth_type)
{
if (depth_type < ::last_depth_type::start_no_overlap || this->last_depth_type != depth_type)
{
this->draw_depth += ::RENDER_DEPTH_DELTA;
}
this->last_depth_type = depth_type;
return this->draw_depth;
}
unsigned int get_world_matrix_index()
{
unsigned int index = this->get_world_matrix_index_no_flush();
if (index == ff::constants::invalid_dword)
{
this->flush();
index = this->get_world_matrix_index_no_flush();
}
return index;
}
unsigned int get_world_matrix_index_no_flush()
{
if (this->world_matrix_index == ff::constants::invalid_dword)
{
DirectX::XMFLOAT4X4 wm;
DirectX::XMStoreFloat4x4(&wm, DirectX::XMMatrixTranspose(DirectX::XMLoadFloat4x4(&this->world_matrix_stack_.matrix())));
auto iter = this->world_matrix_to_index.find(wm);
if (iter == this->world_matrix_to_index.cend() && this->world_matrix_to_index.size() != ::MAX_TRANSFORM_MATRIXES)
{
iter = this->world_matrix_to_index.try_emplace(wm, static_cast<unsigned int>(this->world_matrix_to_index.size())).first;
}
if (iter != this->world_matrix_to_index.cend())
{
this->world_matrix_index = iter->second;
}
}
return this->world_matrix_index;
}
unsigned int get_texture_index_no_flush(const ff::texture_view_base& texture_view, bool use_palette)
{
if (use_palette)
{
unsigned int palette_index = (this->palette_index == ff::constants::invalid_dword) ? this->get_palette_index_no_flush() : this->palette_index;
if (palette_index == ff::constants::invalid_dword)
{
return ff::constants::invalid_dword;
}
unsigned int palette_remap_index = (this->palette_remap_index == ff::constants::invalid_dword) ? this->get_palette_remap_index_no_flush() : this->palette_remap_index;
if (palette_remap_index == ff::constants::invalid_dword)
{
return ff::constants::invalid_dword;
}
unsigned int texture_index = ff::constants::invalid_dword;
for (size_t i = this->textures_using_palette_count; i != 0; i--)
{
if (this->textures_using_palette[i - 1] == &texture_view)
{
texture_index = static_cast<unsigned int>(i - 1);
break;
}
}
if (texture_index == ff::constants::invalid_dword)
{
if (this->textures_using_palette_count == ::MAX_TEXTURES_USING_PALETTE)
{
return ff::constants::invalid_dword;
}
this->textures_using_palette[this->textures_using_palette_count] = &texture_view;
texture_index = static_cast<unsigned int>(this->textures_using_palette_count++);
}
return texture_index | (palette_index << 8) | (palette_remap_index << 16);
}
else
{
unsigned int palette_remap_index = 0;
if (this->target_requires_palette)
{
palette_remap_index = (this->palette_remap_index == ff::constants::invalid_dword) ? this->get_palette_remap_index_no_flush() : this->palette_remap_index;
if (palette_remap_index == ff::constants::invalid_dword)
{
return ff::constants::invalid_dword;
}
}
unsigned int texture_index = ff::constants::invalid_dword;
for (size_t i = this->texture_count; i != 0; i--)
{
if (this->textures[i - 1] == &texture_view)
{
texture_index = static_cast<unsigned int>(i - 1);
break;
}
}
if (texture_index == ff::constants::invalid_dword)
{
if (this->texture_count == ::MAX_TEXTURES)
{
return ff::constants::invalid_dword;
}
this->textures[this->texture_count] = &texture_view;
texture_index = static_cast<unsigned int>(this->texture_count++);
}
return texture_index | (palette_remap_index << 16);
}
}
unsigned int get_palette_index_no_flush()
{
if (this->palette_index == ff::constants::invalid_dword)
{
if (this->target_requires_palette)
{
// Not converting palette to RGBA, so don't use a palette
this->palette_index = 0;
}
else
{
ff::palette_base* palette = this->palette_stack.back();
size_t palette_hash = palette ? palette->data()->row_hash(palette->current_row()) : 0;
auto iter = this->palette_to_index.find(palette_hash);
if (iter == this->palette_to_index.cend() && this->palette_to_index.size() != ::MAX_PALETTES)
{
iter = this->palette_to_index.try_emplace(palette_hash, std::make_pair(palette, static_cast<unsigned int>(this->palette_to_index.size()))).first;
}
if (iter != this->palette_to_index.cend())
{
this->palette_index = iter->second.second;
}
}
}
return this->palette_index;
}
unsigned int get_palette_remap_index_no_flush()
{
if (this->palette_remap_index == ff::constants::invalid_dword)
{
auto& remap_pair = this->palette_remap_stack.back();
auto iter = this->palette_remap_to_index.find(remap_pair.second);
if (iter == this->palette_remap_to_index.cend() && this->palette_remap_to_index.size() != ::MAX_PALETTE_REMAPS)
{
iter = this->palette_remap_to_index.try_emplace(remap_pair.second, std::make_pair(remap_pair.first, static_cast<unsigned int>(this->palette_remap_to_index.size()))).first;
}
if (iter != this->palette_remap_to_index.cend())
{
this->palette_remap_index = iter->second.second;
}
}
return this->palette_remap_index;
}
int remap_palette_index(int color) const
{
return this->palette_remap_stack.back().first[color];
}
void get_world_matrix_and_texture_index(const ff::texture_view_base& texture_view, bool use_palette, unsigned int& model_index, unsigned int& texture_index)
{
model_index = (this->world_matrix_index == ff::constants::invalid_dword) ? this->get_world_matrix_index_no_flush() : this->world_matrix_index;
texture_index = this->get_texture_index_no_flush(texture_view, use_palette);
if (model_index == ff::constants::invalid_dword || texture_index == ff::constants::invalid_dword)
{
this->flush();
this->get_world_matrix_and_texture_index(texture_view, use_palette, model_index, texture_index);
}
}
void get_world_matrix_and_texture_indexes(ff::texture_view_base* const* texture_views, bool use_palette, unsigned int* texture_indexes, size_t count, unsigned int& model_index)
{
model_index = (this->world_matrix_index == ff::constants::invalid_dword) ? this->get_world_matrix_index_no_flush() : this->world_matrix_index;
bool flush = (model_index == ff::constants::invalid_dword);
for (size_t i = 0; !flush && i < count; i++)
{
texture_indexes[i] = this->get_texture_index_no_flush(*texture_views[i], use_palette);
flush |= (texture_indexes[i] == ff::constants::invalid_dword);
}
if (flush)
{
this->flush();
this->get_world_matrix_and_texture_indexes(texture_views, use_palette, texture_indexes, count, model_index);
}
}
void* add_geometry(const void* data, ::geometry_bucket_type bucket_type, float depth)
{
::geometry_bucket& bucket = this->get_geometry_bucket(bucket_type);
if (bucket_type >= ::geometry_bucket_type::first_alpha)
{
assert(!this->force_opaque);
this->alpha_geometry.push_back(::alpha_geometry_entry
{
&bucket,
bucket.count(),
depth
});
}
return bucket.add(data);
}
::geometry_bucket& get_geometry_bucket(::geometry_bucket_type type)
{
return this->geometry_buckets[static_cast<size_t>(type)];
}
enum class state_t
{
invalid,
valid,
drawing,
} state;
// Constant data for shaders
ff_dx::buffer geometry_buffer;
ff_dx::buffer geometry_constants_buffer_0;
ff_dx::buffer geometry_constants_buffer_1;
ff_dx::buffer pixel_constants_buffer_0;
::geometry_shader_constants_0 geometry_constants_0;
::geometry_shader_constants_1 geometry_constants_1;
::pixel_shader_constants_0 pixel_constants_0;
size_t geometry_constants_hash_0;
size_t geometry_constants_hash_1;
size_t pixel_constants_hash_0;
// Render state
std::vector<Microsoft::WRL::ComPtr<ID3D11SamplerState>> sampler_stack;
ff_dx::fixed_state opaque_state;
ff_dx::fixed_state alpha_state;
ff_dx::fixed_state pre_multiplied_alpha_state;
std::vector<ff::draw_base::custom_context_func> custom_context_stack;
// Matrixes
DirectX::XMFLOAT4X4 view_matrix;
ff::matrix_stack world_matrix_stack_;
ff::signal_connection world_matrix_stack_changing_connection;
std::unordered_map<DirectX::XMFLOAT4X4, unsigned int, ff::stable_hash<DirectX::XMFLOAT4X4>> world_matrix_to_index;
unsigned int world_matrix_index;
// Textures
std::array<const ff::texture_view_base*, ::MAX_TEXTURES> textures;
std::array<const ff::texture_view_base*, ::MAX_TEXTURES_USING_PALETTE> textures_using_palette;
size_t texture_count;
size_t textures_using_palette_count;
// Palettes
bool target_requires_palette;
std::vector<ff::palette_base*> palette_stack;
std::shared_ptr<ff::texture> palette_texture;
std::array<size_t, ::MAX_PALETTES> palette_texture_hashes;
std::unordered_map<size_t, std::pair<ff::palette_base*, unsigned int>, ff::no_hash<size_t>> palette_to_index;
unsigned int palette_index;
std::vector<std::pair<const uint8_t*, size_t>> palette_remap_stack;
std::shared_ptr<ff::texture> palette_remap_texture;
std::array<size_t, ::MAX_PALETTE_REMAPS> palette_remap_texture_hashes;
std::unordered_map<size_t, std::pair<const uint8_t*, unsigned int>, ff::no_hash<size_t>> palette_remap_to_index;
unsigned int palette_remap_index;
// Render data
std::vector<::alpha_geometry_entry> alpha_geometry;
std::array<::geometry_bucket, static_cast<size_t>(::geometry_bucket_type::count)> geometry_buckets;
::last_depth_type last_depth_type;
float draw_depth;
int force_no_overlap;
int force_opaque;
int force_pre_multiplied_alpha;
};
}
std::unique_ptr<ff::draw_device> ff::draw_device::create()
{
return std::make_unique<::draw_device_internal>();
}
ff::draw_ptr ff::draw_device::begin_draw(ff::target_base& target, ff::depth* depth, const ff::rect_fixed& view_rect, const ff::rect_fixed& world_rect, ff::draw_options options)
{
return this->begin_draw(target, depth, std::floor(view_rect).cast<float>(), std::floor(world_rect).cast<float>(), options);
}
#endif
| 40.024646 | 212 | 0.595844 |
spadapet
|
65997a849b40b9899b50f9d4c9f7a8950fea29fe
| 2,425 |
cpp
|
C++
|
piLibs/src/libLog/piXmlLogger.cpp
|
fossabot/arctic
|
f3f6e1051b7209020cdaec69ad1f1edbd1acb522
|
[
"MIT"
] | 6 |
2021-03-27T01:54:55.000Z
|
2021-12-15T22:50:28.000Z
|
piLibs/src/libLog/piXmlLogger.cpp
|
fossabot/arctic
|
f3f6e1051b7209020cdaec69ad1f1edbd1acb522
|
[
"MIT"
] | null | null | null |
piLibs/src/libLog/piXmlLogger.cpp
|
fossabot/arctic
|
f3f6e1051b7209020cdaec69ad1f1edbd1acb522
|
[
"MIT"
] | 3 |
2020-07-15T13:27:02.000Z
|
2021-04-19T01:12:02.000Z
|
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "piXmlLogger.h"
namespace piLibs {
piXmlLogger::piXmlLogger() :piLogger()
{
}
piXmlLogger::~piXmlLogger()
{
}
static void printHeader(FILE *fp, const piLogStartInfo *info)
{
fwprintf(fp, L"<?xml version=\"1.0\"?>\n");
fwprintf(fp, L"<?xml-stylesheet type=\"text/xsl\" href=\"ComplexXSLT.xsl\" ?>\n");
fwprintf(fp, L"\n");
fwprintf(fp, L"\n");
fwprintf(fp, L"<DebugSesion>\n");
fwprintf(fp, L"\n");
fwprintf(fp, L"<Info>\n");
fwprintf(fp, L" <Date>%s</Date>\n", info->date);
fwprintf(fp, L" <Memory>%d / %d Megabytes</Memory>", info->free_memory_MB, info->total_memory_MB);
fwprintf(fp, L" <CPU>\n");
fwprintf(fp, L" <Processor>%s</Processor>\n", info->processor);
fwprintf(fp, L" <Units>%d</Units>\n", info->number_cpus);
fwprintf(fp, L" <Speed>%d Mhz</Speed>\n", info->mhz);
fwprintf(fp, L" <CPU/>\n");
fwprintf(fp, L" <OS>%s</OS>\n", info->os);
fwprintf(fp, L" <GPU>\n");
fwprintf(fp, L" <Vendor>%s</Vendor>\n", info->gpuVendor);
fwprintf(fp, L" <Model>%s</Model>\n", info->gpuModel);
fwprintf(fp, L" </GPU>\n");
fwprintf(fp, L" <VRam>%d Megabytes</GPU>\n", info->total_videomemory_MB);
fwprintf(fp, L" <Screen>%d x %d</Screen>\n", info->mScreenResolution[0], info->mScreenResolution[1]);
fwprintf(fp, L" <Multitouch>%d</Multitouch>\n", info->mIntegratedMultitouch);
fwprintf(fp, L"</Info>\n");
fwprintf(fp, L"\n");
fwprintf(fp, L"<Events>\n");
fflush(fp);
}
bool piXmlLogger::Init(const wchar_t *path, const piLogStartInfo *info)
{
//path
mFp = _wfopen(path, L"wt");
if (!mFp)
return false;
printHeader(mFp, info);
return true;
}
void piXmlLogger::End(void)
{
fprintf(mFp, "</DebugSesion>\n");
fclose(mFp);
}
static const wchar_t *stype[5] = { L"Error", L"Warning", L"Assume", L"Message", L"Debug" };
void piXmlLogger::Printf(int messageId, int threadId, const wchar_t *file, const wchar_t *func, int line, int type, const wchar_t *str)
{
if (!mFp) return;
fwprintf(mFp, L" <Event id=\"%d\">\n", messageId);
fwprintf(mFp, L" <Type>%s</Type>\n", stype[type - 1]);
fwprintf(mFp, L" <Th>%d</Th>\n", threadId);
fwprintf(mFp, L" <File>%s</File>\n", file);
fwprintf(mFp, L" <Func>%s</Func>\n", func);
fwprintf(mFp, L" <Line>%d</Line>\n", line);
fwprintf(mFp, L" <Text>%s</Text>\n", str);
fwprintf(mFp, L" </Event>\n");
fflush(mFp);
}
}
| 28.869048 | 135 | 0.621031 |
fossabot
|
659bfcb3b3d2eda72683ba09bc7e8f7416d3b963
| 481 |
cpp
|
C++
|
Online Judges/URI/2482/main.cpp
|
AnneLivia/URI-Online
|
02ff972be172a62b8abe25030c3676f6c04efd1b
|
[
"MIT"
] | 64 |
2019-03-17T08:56:28.000Z
|
2022-01-14T02:31:21.000Z
|
Online Judges/URI/2482/main.cpp
|
AnneLivia/URI-Online
|
02ff972be172a62b8abe25030c3676f6c04efd1b
|
[
"MIT"
] | 1 |
2020-12-24T07:16:30.000Z
|
2021-03-23T20:51:05.000Z
|
Online Judges/URI/2482/main.cpp
|
AnneLivia/URI-Online
|
02ff972be172a62b8abe25030c3676f6c04efd1b
|
[
"MIT"
] | 19 |
2019-05-25T10:48:16.000Z
|
2022-01-07T10:07:46.000Z
|
#include <iostream>
#include <map>
using namespace std;
int main()
{
int qtdI, qtdP;
string s, idioma;
map<string,string>m;
cin >> qtdI;
cin.ignore();
while(qtdI--) {
getline(cin,idioma);
getline(cin,s);
m.insert(make_pair(idioma,s));
}
cin >> qtdP;
cin.ignore();
while(qtdP--) {
getline(cin,s);
getline(cin,idioma);
cout << s << "\n" << m.at(idioma) << endl << endl;
}
return 0;
}
| 17.178571 | 58 | 0.511435 |
AnneLivia
|