hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
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
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
33871cfbe4bcd8b277d8532ccf73b0c547953390
65,531
cpp
C++
modules/gles3/functional/es3fNegativeBufferApiTests.cpp
quanganh2627/bytm-x64-L-w05-2015_external_deqp
78b1425294582bbe001a33393de7f7b5c49822bb
[ "Apache-2.0" ]
2
2016-12-27T00:57:00.000Z
2020-07-13T13:02:45.000Z
modules/gles3/functional/es3fNegativeBufferApiTests.cpp
quanganh2627/bytm-x64-L-w05-2015_external_deqp
78b1425294582bbe001a33393de7f7b5c49822bb
[ "Apache-2.0" ]
null
null
null
modules/gles3/functional/es3fNegativeBufferApiTests.cpp
quanganh2627/bytm-x64-L-w05-2015_external_deqp
78b1425294582bbe001a33393de7f7b5c49822bb
[ "Apache-2.0" ]
4
2016-04-27T21:12:29.000Z
2020-07-13T13:02:48.000Z
/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL ES 3.0 Module * ------------------------------------------------- * * Copyright 2014 The Android Open Source Project * * 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 * \brief Negative Buffer API tests. *//*--------------------------------------------------------------------*/ #include "es3fNegativeBufferApiTests.hpp" #include "es3fApiCase.hpp" #include "gluContextInfo.hpp" #include "glwDefs.hpp" #include "glwEnums.hpp" using namespace glw; // GL types namespace deqp { namespace gles3 { namespace Functional { using tcu::TestLog; NegativeBufferApiTests::NegativeBufferApiTests (Context& context) : TestCaseGroup(context, "buffer", "Negative Buffer API Cases") { } NegativeBufferApiTests::~NegativeBufferApiTests (void) { } void NegativeBufferApiTests::init (void) { // Buffers ES3F_ADD_API_CASE(bind_buffer, "Invalid glBindBuffer() usage", { m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not one of the allowable values."); glBindBuffer(-1, 0); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; }); ES3F_ADD_API_CASE(delete_buffers, "Invalid glDeleteBuffers() usage", { m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if n is negative."); glDeleteBuffers(-1, 0); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; }); ES3F_ADD_API_CASE(gen_buffers, "Invalid glGenBuffers() usage", { m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if n is negative."); glGenBuffers(-1, 0); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; }); ES3F_ADD_API_CASE(buffer_data, "Invalid glBufferData() usage", { GLuint buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not GL_ARRAY_BUFFER or GL_ELEMENT_ARRAY_BUFFER."); glBufferData(-1, 0, NULL, GL_STREAM_DRAW); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if usage is not GL_STREAM_DRAW, GL_STATIC_DRAW, or GL_DYNAMIC_DRAW."); glBufferData(GL_ARRAY_BUFFER, 0, NULL, -1); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if size is negative."); glBufferData(GL_ARRAY_BUFFER, -1, NULL, GL_STREAM_DRAW); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the reserved buffer object name 0 is bound to target."); glBindBuffer(GL_ARRAY_BUFFER, 0); glBufferData(GL_ARRAY_BUFFER, 0, NULL, GL_STREAM_DRAW); expectError(GL_INVALID_OPERATION); m_log << TestLog::EndSection; glDeleteBuffers(1, &buffer); }); ES3F_ADD_API_CASE(buffer_sub_data, "Invalid glBufferSubData() usage", { GLuint buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, 10, 0, GL_STREAM_DRAW); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not GL_ARRAY_BUFFER or GL_ELEMENT_ARRAY_BUFFER."); glBufferSubData(-1, 1, 1, 0); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the reserved buffer object name 0 is bound to target."); glBindBuffer(GL_ARRAY_BUFFER, 0); glBufferSubData(GL_ARRAY_BUFFER, 1, 1, 0); expectError(GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the buffer object being updated is mapped."); glBindBuffer(GL_ARRAY_BUFFER, buffer); glMapBufferRange(GL_ARRAY_BUFFER, 0, 5, GL_MAP_READ_BIT); expectError(GL_NO_ERROR); glBufferSubData(GL_ARRAY_BUFFER, 1, 1, 0); expectError(GL_INVALID_OPERATION); m_log << TestLog::EndSection; glDeleteBuffers(1, &buffer); }); ES3F_ADD_API_CASE(buffer_sub_data_size_offset, "Invalid glBufferSubData() usage", { GLuint buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, 10, 0, GL_STREAM_DRAW); m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if offset or size is negative, or if together they define a region of memory that extends beyond the buffer object's allocated data store."); glBufferSubData(GL_ARRAY_BUFFER, -1, 1, 0); expectError(GL_INVALID_VALUE); glBufferSubData(GL_ARRAY_BUFFER, -1, -1, 0); expectError(GL_INVALID_VALUE); glBufferSubData(GL_ARRAY_BUFFER, 1, -1, 0); expectError(GL_INVALID_VALUE); glBufferSubData(GL_ARRAY_BUFFER, 15, 1, 0); expectError(GL_INVALID_VALUE); glBufferSubData(GL_ARRAY_BUFFER, 1, 15, 0); expectError(GL_INVALID_VALUE); glBufferSubData(GL_ARRAY_BUFFER, 8, 8, 0); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; glDeleteBuffers(1, &buffer); }); ES3F_ADD_API_CASE(clear, "Invalid glClear() usage", { m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if any bit other than the three defined bits is set in mask."); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); expectError(GL_NO_ERROR); glClear(0x00000200); expectError(GL_INVALID_VALUE); glClear(0x00001000); expectError(GL_INVALID_VALUE); glClear(0x00000010); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; }); ES3F_ADD_API_CASE(read_pixels, "Invalid glReadPixels() usage", { std::vector<GLubyte> ubyteData(4); m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the combination of format and type is unsupported."); glReadPixels(0, 0, 1, 1, GL_LUMINANCE_ALPHA, GL_UNSIGNED_SHORT_4_4_4_4, &ubyteData[0]); expectError(GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if either width or height is negative."); glReadPixels(0, 0, -1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &ubyteData[0]); expectError(GL_INVALID_VALUE); glReadPixels(0, 0, 1, -1, GL_RGBA, GL_UNSIGNED_BYTE, &ubyteData[0]); expectError(GL_INVALID_VALUE); glReadPixels(0, 0, -1, -1, GL_RGBA, GL_UNSIGNED_BYTE, &ubyteData[0]); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_FRAMEBUFFER_OPERATION is generated if the currently bound framebuffer is not framebuffer complete."); GLuint fbo; glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); glCheckFramebufferStatus(GL_FRAMEBUFFER); glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &ubyteData[0]); expectError(GL_INVALID_FRAMEBUFFER_OPERATION); m_log << TestLog::EndSection; glDeleteFramebuffers(1, &fbo); }); ES3F_ADD_API_CASE(read_pixels_format_mismatch, "Invalid glReadPixels() usage", { std::vector<GLubyte> ubyteData(4); std::vector<GLushort> ushortData(4); m_log << TestLog::Section("", "Unsupported combinations of format and type will generate an INVALID_OPERATION error."); glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_SHORT_5_6_5, &ushortData[0]); expectError(GL_INVALID_OPERATION); glReadPixels(0, 0, 1, 1, GL_ALPHA, GL_UNSIGNED_SHORT_5_6_5, &ushortData[0]); expectError(GL_INVALID_OPERATION); glReadPixels(0, 0, 1, 1, GL_RGB, GL_UNSIGNED_SHORT_4_4_4_4, &ushortData[0]); expectError(GL_INVALID_OPERATION); glReadPixels(0, 0, 1, 1, GL_ALPHA, GL_UNSIGNED_SHORT_4_4_4_4, &ushortData[0]); expectError(GL_INVALID_OPERATION); glReadPixels(0, 0, 1, 1, GL_RGB, GL_UNSIGNED_SHORT_5_5_5_1, &ushortData[0]); expectError(GL_INVALID_OPERATION); glReadPixels(0, 0, 1, 1, GL_ALPHA, GL_UNSIGNED_SHORT_5_5_5_1, &ushortData[0]); expectError(GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_RGBA/GL_UNSIGNED_BYTE is always accepted and the other acceptable pair can be discovered by querying GL_IMPLEMENTATION_COLOR_READ_FORMAT and GL_IMPLEMENTATION_COLOR_READ_TYPE."); glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &ubyteData[0]); expectError(GL_NO_ERROR); GLint readFormat; GLint readType; glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &readFormat); glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &readType); glReadPixels(0, 0, 1, 1, readFormat, readType, &ubyteData[0]); expectError(GL_NO_ERROR); m_log << TestLog::EndSection; }); ES3F_ADD_API_CASE(read_pixels_fbo_format_mismatch, "Invalid glReadPixels() usage", { std::vector<GLubyte> ubyteData(4); std::vector<float> floatData(4); deUint32 fbo; deUint32 texture; glGenTextures (1, &texture); glBindTexture (GL_TEXTURE_2D, texture); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glGenFramebuffers (1, &fbo); glBindFramebuffer (GL_FRAMEBUFFER, fbo); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if currently bound framebuffer format is incompatible with format and type."); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); glCheckFramebufferStatus(GL_FRAMEBUFFER); expectError (GL_NO_ERROR); glReadPixels (0, 0, 1, 1, GL_RGBA, GL_FLOAT, &floatData[0]); expectError (GL_INVALID_OPERATION); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA32I, 32, 32, 0, GL_RGBA_INTEGER, GL_INT, NULL); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); glCheckFramebufferStatus(GL_FRAMEBUFFER); expectError (GL_NO_ERROR); glReadPixels (0, 0, 1, 1, GL_RGBA, GL_FLOAT, &floatData[0]); expectError (GL_INVALID_OPERATION); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA32UI, 32, 32, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, NULL); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); glCheckFramebufferStatus(GL_FRAMEBUFFER); expectError (GL_NO_ERROR); glReadPixels (0, 0, 1, 1, GL_RGBA, GL_FLOAT, &floatData[0]); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if GL_READ_FRAMEBUFFER_BINDING is non-zero, the read framebuffer is complete, and the value of GL_SAMPLE_BUFFERS for the read framebuffer is greater than zero."); int binding = -1; int sampleBuffers; deUint32 rbo; glGenRenderbuffers(1, &rbo); glBindRenderbuffer(GL_RENDERBUFFER, rbo); glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_RGBA8, 32, 32); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo); glGetIntegerv (GL_READ_FRAMEBUFFER_BINDING, &binding); m_log << TestLog::Message << "// GL_READ_FRAMEBUFFER_BINDING: " << binding << TestLog::EndMessage; glCheckFramebufferStatus(GL_FRAMEBUFFER); glGetIntegerv (GL_SAMPLE_BUFFERS, &sampleBuffers); m_log << TestLog::Message << "// GL_SAMPLE_BUFFERS: " << sampleBuffers << TestLog::EndMessage; expectError (GL_NO_ERROR); if (binding == 0 || sampleBuffers <= 0) { m_log << TestLog::Message << "// ERROR: expected GL_READ_FRAMEBUFFER_BINDING to be non-zero and GL_SAMPLE_BUFFERS to be greater than zero" << TestLog::EndMessage; if (m_testCtx.getTestResult() == QP_TEST_RESULT_PASS) m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Got invalid value"); } else { glReadPixels (0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &ubyteData[0]); expectError (GL_INVALID_OPERATION); } m_log << TestLog::EndSection; glBindRenderbuffer (GL_RENDERBUFFER, 0); glBindTexture (GL_TEXTURE_2D, 0); glBindFramebuffer (GL_FRAMEBUFFER, 0); glDeleteFramebuffers (1, &fbo); glDeleteTextures (1, &texture); glDeleteRenderbuffers (1, &rbo); }); ES3F_ADD_API_CASE(bind_buffer_range, "Invalid glBindBufferRange() usage", { deUint32 bufU; glGenBuffers(1, &bufU); glBindBuffer(GL_UNIFORM_BUFFER, bufU); glBufferData(GL_UNIFORM_BUFFER, 16, NULL, GL_STREAM_DRAW); deUint32 bufTF; glGenBuffers(1, &bufTF); glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, bufTF); glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, 16, NULL, GL_STREAM_DRAW); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not GL_TRANSFORM_FEEDBACK_BUFFER or GL_UNIFORM_BUFFER."); glBindBufferRange(GL_ARRAY_BUFFER, 0, bufU, 0, 4); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if target is GL_TRANSFORM_FEEDBACK_BUFFER and index is greater than or equal to GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS."); int maxTFSize; glGetIntegerv(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS, &maxTFSize); glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, maxTFSize, bufTF, 0, 4); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if target is GL_UNIFORM_BUFFER and index is greater than or equal to GL_MAX_UNIFORM_BUFFER_BINDINGS."); int maxUSize; glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &maxUSize); glBindBufferRange(GL_UNIFORM_BUFFER, maxUSize, bufU, 0, 4); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if size is less than or equal to zero."); glBindBufferRange(GL_UNIFORM_BUFFER, 0, bufU, 0, -1); expectError(GL_INVALID_VALUE); glBindBufferRange(GL_UNIFORM_BUFFER, 0, bufU, 0, 0); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if target is GL_TRANSFORM_FEEDBACK_BUFFER and size or offset are not multiples of 4."); glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, 0, bufTF, 4, 5); expectError(GL_INVALID_VALUE); glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, 0, bufTF, 5, 4); expectError(GL_INVALID_VALUE); glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, 0, bufTF, 5, 7); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if target is GL_UNIFORM_BUFFER and offset is not a multiple of GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT."); int alignment; glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &alignment); glBindBufferRange(GL_UNIFORM_BUFFER, 0, bufU, alignment+1, 4); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; glDeleteBuffers(1, &bufU); glDeleteBuffers(1, &bufTF); }); ES3F_ADD_API_CASE(bind_buffer_base, "Invalid glBindBufferBase() usage", { deUint32 bufU; glGenBuffers(1, &bufU); glBindBuffer(GL_UNIFORM_BUFFER, bufU); glBufferData(GL_UNIFORM_BUFFER, 16, NULL, GL_STREAM_DRAW); deUint32 bufTF; glGenBuffers(1, &bufTF); glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, bufTF); glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, 16, NULL, GL_STREAM_DRAW); expectError(GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not GL_TRANSFORM_FEEDBACK_BUFFER or GL_UNIFORM_BUFFER."); glBindBufferBase(-1, 0, bufU); expectError(GL_INVALID_ENUM); glBindBufferBase(GL_ARRAY_BUFFER, 0, bufU); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if target is GL_UNIFORM_BUFFER and index is greater than or equal to GL_MAX_UNIFORM_BUFFER_BINDINGS."); int maxUSize; glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &maxUSize); glBindBufferBase(GL_UNIFORM_BUFFER, maxUSize, bufU); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if target is GL_TRANSFORM_FEEDBACK_BUFFER andindex is greater than or equal to GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS."); int maxTFSize; glGetIntegerv(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS, &maxTFSize); glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, maxTFSize, bufTF); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; glDeleteBuffers(1, &bufU); glDeleteBuffers(1, &bufTF); }); ES3F_ADD_API_CASE(clear_bufferiv, "Invalid glClearBufferiv() usage", { std::vector<int> data(32*32); deUint32 fbo; deUint32 texture; glGenTextures (1, &texture); glBindTexture (GL_TEXTURE_2D, texture); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA32I, 32, 32, 0, GL_RGBA_INTEGER, GL_INT, NULL); glGenFramebuffers (1, &fbo); glBindFramebuffer (GL_FRAMEBUFFER, fbo); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); glCheckFramebufferStatus(GL_FRAMEBUFFER); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if buffer is not an accepted value."); glClearBufferiv(-1, 0, &data[0]); expectError(GL_INVALID_ENUM); glClearBufferiv(GL_FRAMEBUFFER, 0, &data[0]); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if buffer is GL_COLOR, GL_FRONT, GL_BACK, GL_LEFT, GL_RIGHT, or GL_FRONT_AND_BACK and drawBuffer is greater than or equal to GL_MAX_DRAW_BUFFERS."); int maxDrawBuffers; glGetIntegerv(GL_MAX_DRAW_BUFFERS, &maxDrawBuffers); glClearBufferiv(GL_COLOR, maxDrawBuffers, &data[0]); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if buffer is GL_DEPTH or GL_DEPTH_STENCIL."); glClearBufferiv(GL_DEPTH, 1, &data[0]); expectError(GL_INVALID_ENUM); glClearBufferiv(GL_DEPTH_STENCIL, 1, &data[0]); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if buffer is GL_STENCIL and drawBuffer is not zero."); glClearBufferiv(GL_STENCIL, 1, &data[0]); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; glDeleteFramebuffers(1, &fbo); glDeleteTextures(1, &texture); }); ES3F_ADD_API_CASE(clear_bufferuiv, "Invalid glClearBufferuiv() usage", { std::vector<deUint32> data(32*32); deUint32 fbo; deUint32 texture; glGenTextures (1, &texture); glBindTexture (GL_TEXTURE_2D, texture); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA32UI, 32, 32, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, NULL); glGenFramebuffers (1, &fbo); glBindFramebuffer (GL_FRAMEBUFFER, fbo); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); glCheckFramebufferStatus(GL_FRAMEBUFFER); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if buffer is not an accepted value."); glClearBufferuiv(-1, 0, &data[0]); expectError(GL_INVALID_ENUM); glClearBufferuiv(GL_FRAMEBUFFER, 0, &data[0]); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if buffer is GL_COLOR, GL_FRONT, GL_BACK, GL_LEFT, GL_RIGHT, or GL_FRONT_AND_BACK and drawBuffer is greater than or equal to GL_MAX_DRAW_BUFFERS."); int maxDrawBuffers; glGetIntegerv(GL_MAX_DRAW_BUFFERS, &maxDrawBuffers); glClearBufferuiv(GL_COLOR, maxDrawBuffers, &data[0]); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if buffer is GL_DEPTH, GL_STENCIL or GL_DEPTH_STENCIL."); glClearBufferuiv(GL_DEPTH, 1, &data[0]); expectError(GL_INVALID_ENUM); glClearBufferuiv(GL_STENCIL, 1, &data[0]); expectError(GL_INVALID_ENUM); glClearBufferuiv(GL_DEPTH_STENCIL, 1, &data[0]); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; glDeleteFramebuffers(1, &fbo); glDeleteTextures(1, &texture); }); ES3F_ADD_API_CASE(clear_bufferfv, "Invalid glClearBufferfv() usage", { std::vector<float> data(32*32); deUint32 fbo; deUint32 texture; glGenTextures (1, &texture); glBindTexture (GL_TEXTURE_2D, texture); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA32F, 32, 32, 0, GL_RGBA, GL_FLOAT, NULL); glGenFramebuffers (1, &fbo); glBindFramebuffer (GL_FRAMEBUFFER, fbo); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); glCheckFramebufferStatus(GL_FRAMEBUFFER); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if buffer is not an accepted value."); glClearBufferfv(-1, 0, &data[0]); expectError(GL_INVALID_ENUM); glClearBufferfv(GL_FRAMEBUFFER, 0, &data[0]); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if buffer is GL_COLOR, GL_FRONT, GL_BACK, GL_LEFT, GL_RIGHT, or GL_FRONT_AND_BACK and drawBuffer is greater than or equal to GL_MAX_DRAW_BUFFERS."); int maxDrawBuffers; glGetIntegerv(GL_MAX_DRAW_BUFFERS, &maxDrawBuffers); glClearBufferfv(GL_COLOR, maxDrawBuffers, &data[0]); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if buffer is GL_STENCIL or GL_DEPTH_STENCIL."); glClearBufferfv(GL_STENCIL, 1, &data[0]); expectError(GL_INVALID_ENUM); glClearBufferfv(GL_DEPTH_STENCIL, 1, &data[0]); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if buffer is GL_DEPTH and drawBuffer is not zero."); glClearBufferfv(GL_DEPTH, 1, &data[0]); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; glDeleteFramebuffers(1, &fbo); glDeleteTextures(1, &texture); }); ES3F_ADD_API_CASE(clear_bufferfi, "Invalid glClearBufferfi() usage", { m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if buffer is not an accepted value."); glClearBufferfi(-1, 0, 1.0f, 1); expectError(GL_INVALID_ENUM); glClearBufferfi(GL_FRAMEBUFFER, 0, 1.0f, 1); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if buffer is not GL_DEPTH_STENCIL."); glClearBufferfi(GL_DEPTH, 0, 1.0f, 1); expectError(GL_INVALID_ENUM); glClearBufferfi(GL_STENCIL, 0, 1.0f, 1); expectError(GL_INVALID_ENUM); glClearBufferfi(GL_COLOR, 0, 1.0f, 1); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if buffer is GL_DEPTH_STENCIL and drawBuffer is not zero."); glClearBufferfi(GL_DEPTH_STENCIL, 1, 1.0f, 1); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; }); ES3F_ADD_API_CASE(copy_buffer_sub_data, "Invalid glCopyBufferSubData() usage", { deUint32 buf[2]; std::vector<float> data(32*32); glGenBuffers (2, buf); glBindBuffer (GL_COPY_READ_BUFFER, buf[0]); glBufferData (GL_COPY_READ_BUFFER, 32, &data[0], GL_DYNAMIC_COPY); glBindBuffer (GL_COPY_WRITE_BUFFER, buf[1]); glBufferData (GL_COPY_WRITE_BUFFER, 32, &data[0], GL_DYNAMIC_COPY); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if any of readoffset, writeoffset or size is negative."); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 0, -4); expectError (GL_INVALID_VALUE); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, -1, 0, 4); expectError (GL_INVALID_VALUE); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, -1, 4); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if readoffset + size exceeds the size of the buffer object bound to readtarget."); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 0, 36); expectError (GL_INVALID_VALUE); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 24, 0, 16); expectError (GL_INVALID_VALUE); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 36, 0, 4); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if writeoffset + size exceeds the size of the buffer object bound to writetarget."); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 0, 36); expectError (GL_INVALID_VALUE); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 24, 16); expectError (GL_INVALID_VALUE); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 36, 4); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if the same buffer object is bound to both readtarget and writetarget and the ranges [readoffset, readoffset + size) and [writeoffset, writeoffset + size) overlap."); glBindBuffer (GL_COPY_WRITE_BUFFER, buf[0]); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 16, 4); expectError (GL_NO_ERROR); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 0, 4); expectError (GL_INVALID_VALUE); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 16, 18); expectError (GL_INVALID_VALUE); glBindBuffer (GL_COPY_WRITE_BUFFER, buf[1]); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if zero is bound to readtarget or writetarget."); glBindBuffer (GL_COPY_READ_BUFFER, 0); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 0, 16); expectError (GL_INVALID_OPERATION); glBindBuffer (GL_COPY_READ_BUFFER, buf[0]); glBindBuffer (GL_COPY_WRITE_BUFFER, 0); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 0, 16); expectError (GL_INVALID_OPERATION); glBindBuffer (GL_COPY_WRITE_BUFFER, buf[1]); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the buffer object bound to either readtarget or writetarget is mapped."); glMapBufferRange (GL_COPY_READ_BUFFER, 0, 4, GL_MAP_READ_BIT); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 0, 16); expectError (GL_INVALID_OPERATION); glUnmapBuffer (GL_COPY_READ_BUFFER); glMapBufferRange (GL_COPY_WRITE_BUFFER, 0, 4, GL_MAP_READ_BIT); glCopyBufferSubData (GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 0, 16); expectError (GL_INVALID_OPERATION); glUnmapBuffer (GL_COPY_WRITE_BUFFER); m_log << TestLog::EndSection; glDeleteBuffers(2, buf); }); ES3F_ADD_API_CASE(draw_buffers, "Invalid glDrawBuffers() usage", { deUint32 fbo; deUint32 texture; int maxDrawBuffers; glGetIntegerv (GL_MAX_DRAW_BUFFERS, &maxDrawBuffers); std::vector<deUint32> values(maxDrawBuffers+1); values[0] = GL_NONE; values[1] = GL_BACK; values[2] = GL_COLOR_ATTACHMENT0; values[3] = GL_DEPTH_ATTACHMENT; std::vector<GLfloat> data(32*32); glGenTextures (1, &texture); glBindTexture (GL_TEXTURE_2D, texture); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glGenFramebuffers (1, &fbo); glBindFramebuffer (GL_FRAMEBUFFER, fbo); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); glCheckFramebufferStatus(GL_FRAMEBUFFER); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if one of the values in bufs is not an accepted value."); glDrawBuffers (2, &values[2]); expectError (GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the GL is bound to the default framebuffer and n is not 1."); glBindFramebuffer (GL_FRAMEBUFFER, 0); glDrawBuffers (2, &values[0]); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the GL is bound to the default framebuffer and the value in bufs is one of the GL_COLOR_ATTACHMENTn tokens."); glBindFramebuffer (GL_FRAMEBUFFER, 0); glDrawBuffers (1, &values[2]); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the GL is bound to a framebuffer object and the ith buffer listed in bufs is anything other than GL_NONE or GL_COLOR_ATTACHMENTSi."); glBindFramebuffer (GL_FRAMEBUFFER, fbo); glDrawBuffers (1, &values[1]); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if n is less than 0 or greater than GL_MAX_DRAW_BUFFERS."); glDrawBuffers (-1, &values[1]); expectError (GL_INVALID_VALUE); glDrawBuffers (maxDrawBuffers+1, &values[0]); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; glDeleteTextures(1, &texture); glDeleteFramebuffers(1, &fbo); }); ES3F_ADD_API_CASE(flush_mapped_buffer_range, "Invalid glFlushMappedBufferRange() usage", { deUint32 buf; std::vector<GLfloat> data(32); glGenBuffers (1, &buf); glBindBuffer (GL_ARRAY_BUFFER, buf); glBufferData (GL_ARRAY_BUFFER, 32, &data[0], GL_STATIC_READ); glMapBufferRange (GL_ARRAY_BUFFER, 0, 16, GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if offset or length is negative, or if offset + length exceeds the size of the mapping."); glFlushMappedBufferRange(GL_ARRAY_BUFFER, -1, 1); expectError (GL_INVALID_VALUE); glFlushMappedBufferRange(GL_ARRAY_BUFFER, 0, -1); expectError (GL_INVALID_VALUE); glFlushMappedBufferRange(GL_ARRAY_BUFFER, 12, 8); expectError (GL_INVALID_VALUE); glFlushMappedBufferRange(GL_ARRAY_BUFFER, 24, 4); expectError (GL_INVALID_VALUE); glFlushMappedBufferRange(GL_ARRAY_BUFFER, 0, 24); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if zero is bound to target."); glBindBuffer (GL_ARRAY_BUFFER, 0); glFlushMappedBufferRange(GL_ARRAY_BUFFER, 0, 8); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the buffer bound to target is not mapped, or is mapped without the GL_MAP_FLUSH_EXPLICIT flag."); glBindBuffer (GL_ARRAY_BUFFER, buf); glUnmapBuffer (GL_ARRAY_BUFFER); glFlushMappedBufferRange(GL_ARRAY_BUFFER, 0, 8); expectError (GL_INVALID_OPERATION); glMapBufferRange (GL_ARRAY_BUFFER, 0, 16, GL_MAP_WRITE_BIT); glFlushMappedBufferRange(GL_ARRAY_BUFFER, 0, 8); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; glUnmapBuffer (GL_ARRAY_BUFFER); glDeleteBuffers (1, &buf); }); ES3F_ADD_API_CASE(map_buffer_range, "Invalid glMapBufferRange() usage", { deUint32 buf; std::vector<GLfloat> data(32); glGenBuffers (1, &buf); glBindBuffer (GL_ARRAY_BUFFER, buf); glBufferData (GL_ARRAY_BUFFER, 32, &data[0], GL_DYNAMIC_COPY); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if either of offset or length is negative."); glMapBufferRange (GL_ARRAY_BUFFER, -1, 1, GL_MAP_READ_BIT); expectError (GL_INVALID_VALUE); glMapBufferRange (GL_ARRAY_BUFFER, 1, -1, GL_MAP_READ_BIT); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if offset + length is greater than the value of GL_BUFFER_SIZE."); glMapBufferRange (GL_ARRAY_BUFFER, 0, 33, GL_MAP_READ_BIT); expectError (GL_INVALID_VALUE); glMapBufferRange (GL_ARRAY_BUFFER, 32, 1, GL_MAP_READ_BIT); expectError (GL_INVALID_VALUE); glMapBufferRange (GL_ARRAY_BUFFER, 16, 17, GL_MAP_READ_BIT); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if access has any bits set other than those accepted."); glMapBufferRange (GL_ARRAY_BUFFER, 0, 16, GL_MAP_READ_BIT | 0x1000); expectError (GL_INVALID_VALUE); glMapBufferRange (GL_ARRAY_BUFFER, 0, 16, GL_MAP_WRITE_BIT | 0x1000); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the buffer is already in a mapped state."); glMapBufferRange (GL_ARRAY_BUFFER, 0, 16, GL_MAP_WRITE_BIT); expectError (GL_NO_ERROR); glMapBufferRange (GL_ARRAY_BUFFER, 16, 8, GL_MAP_READ_BIT); expectError (GL_INVALID_OPERATION); glUnmapBuffer (GL_ARRAY_BUFFER); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if neither GL_MAP_READ_BIT or GL_MAP_WRITE_BIT is set."); glMapBufferRange (GL_ARRAY_BUFFER, 0, 16, GL_MAP_INVALIDATE_RANGE_BIT); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if "); glMapBufferRange (GL_ARRAY_BUFFER, 0, 16, GL_MAP_INVALIDATE_RANGE_BIT); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if GL_MAP_READ_BIT is set and any of GL_MAP_INVALIDATE_RANGE_BIT, GL_MAP_INVALIDATE_BUFFER_BIT, or GL_MAP_UNSYNCHRONIZED_BIT is set."); glMapBufferRange (GL_ARRAY_BUFFER, 0, 16, GL_MAP_READ_BIT | GL_MAP_INVALIDATE_RANGE_BIT); expectError (GL_INVALID_OPERATION); glMapBufferRange (GL_ARRAY_BUFFER, 0, 16, GL_MAP_READ_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); expectError (GL_INVALID_OPERATION); glMapBufferRange (GL_ARRAY_BUFFER, 0, 16, GL_MAP_READ_BIT | GL_MAP_UNSYNCHRONIZED_BIT); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if GL_MAP_FLUSH_EXPLICIT_BIT is set and GL_MAP_WRITE_BIT is not set."); glMapBufferRange (GL_ARRAY_BUFFER, 0, 16, GL_MAP_READ_BIT | GL_MAP_FLUSH_EXPLICIT_BIT); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; glDeleteBuffers (1, &buf); }); ES3F_ADD_API_CASE(read_buffer, "Invalid glReadBuffer() usage", { deUint32 fbo; deUint32 texture; int maxColorAttachments; glGetIntegerv (GL_MAX_COLOR_ATTACHMENTS, &maxColorAttachments); glGenTextures (1, &texture); glBindTexture (GL_TEXTURE_2D, texture); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glGenFramebuffers (1, &fbo); glBindFramebuffer (GL_FRAMEBUFFER, fbo); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); glCheckFramebufferStatus(GL_FRAMEBUFFER); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if mode is not GL_BACK, GL_NONE, or GL_COLOR_ATTACHMENTi."); glReadBuffer (GL_NONE); expectError (GL_NO_ERROR); glReadBuffer (1); expectError (GL_INVALID_ENUM); glReadBuffer (GL_FRAMEBUFFER); expectError (GL_INVALID_ENUM); glReadBuffer (GL_COLOR_ATTACHMENT0 - 1); expectError (GL_INVALID_ENUM); glReadBuffer (GL_FRONT); expectError (GL_INVALID_ENUM); // \ note Spec isn't actually clear here, but it is safe to assume that // GL_DEPTH_ATTACHMENT can't be interpreted as GL_COLOR_ATTACHMENTm // where m = (GL_DEPTH_ATTACHMENT - GL_COLOR_ATTACHMENT0). glReadBuffer (GL_DEPTH_ATTACHMENT); expectError (GL_INVALID_ENUM); glReadBuffer (GL_STENCIL_ATTACHMENT); expectError (GL_INVALID_ENUM); glReadBuffer (GL_STENCIL_ATTACHMENT+1); expectError (GL_INVALID_ENUM); glReadBuffer (0xffffffffu); expectError (GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION error is generated if src is GL_BACK or if src is GL_COLOR_ATTACHMENTm where m is greater than or equal to the value of GL_MAX_COLOR_ATTACHMENTS."); glReadBuffer (GL_BACK); expectError (GL_INVALID_OPERATION); glReadBuffer (GL_COLOR_ATTACHMENT0 + maxColorAttachments); expectError (GL_INVALID_OPERATION); if (GL_COLOR_ATTACHMENT0+maxColorAttachments < GL_DEPTH_ATTACHMENT-1) { glReadBuffer (GL_DEPTH_ATTACHMENT - 1); expectError (GL_INVALID_OPERATION); } m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the current framebuffer is the default framebuffer and mode is not GL_NONE or GL_BACK."); glBindFramebuffer (GL_FRAMEBUFFER, 0); glReadBuffer (GL_COLOR_ATTACHMENT0); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the current framebuffer is a named framebuffer and mode is not GL_NONE or GL_COLOR_ATTACHMENTi."); glBindFramebuffer (GL_FRAMEBUFFER, fbo); glReadBuffer (GL_BACK); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; glDeleteTextures(1, &texture); glDeleteFramebuffers(1, &fbo); }); ES3F_ADD_API_CASE(unmap_buffer, "Invalid glUnmapBuffer() usage", { deUint32 buf; std::vector<GLfloat> data(32); glGenBuffers (1, &buf); glBindBuffer (GL_ARRAY_BUFFER, buf); glBufferData (GL_ARRAY_BUFFER, 32, &data[0], GL_DYNAMIC_COPY); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the buffer data store is already in an unmapped state."); glUnmapBuffer (GL_ARRAY_BUFFER); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; glDeleteBuffers (1, &buf); }); // Framebuffer Objects ES3F_ADD_API_CASE(bind_framebuffer, "Invalid glBindFramebuffer() usage", { m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not GL_FRAMEBUFFER."); glBindFramebuffer(-1, 0); expectError(GL_INVALID_ENUM); glBindFramebuffer(GL_RENDERBUFFER, 0); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; }); ES3F_ADD_API_CASE(bind_renderbuffer, "Invalid glBindRenderbuffer() usage", { m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not GL_RENDERBUFFER."); glBindRenderbuffer(-1, 0); expectError(GL_INVALID_ENUM); glBindRenderbuffer(GL_FRAMEBUFFER, 0); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; }); ES3F_ADD_API_CASE(check_framebuffer_status, "Invalid glCheckFramebufferStatus() usage", { m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not GL_FRAMEBUFFER."); glCheckFramebufferStatus(-1); expectError(GL_INVALID_ENUM); glCheckFramebufferStatus(GL_RENDERBUFFER); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; }); ES3F_ADD_API_CASE(gen_framebuffers, "Invalid glGenFramebuffers() usage", { m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if n is negative."); glGenFramebuffers(-1, 0); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; }); ES3F_ADD_API_CASE(gen_renderbuffers, "Invalid glGenRenderbuffers() usage", { m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if n is negative."); glGenRenderbuffers(-1, 0); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; }); ES3F_ADD_API_CASE(delete_framebuffers, "Invalid glDeleteFramebuffers() usage", { m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if n is negative."); glDeleteFramebuffers(-1, 0); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; }); ES3F_ADD_API_CASE(delete_renderbuffers, "Invalid glDeleteRenderbuffers() usage", {; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if n is negative."); glDeleteRenderbuffers(-1, 0); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; }); ES3F_ADD_API_CASE(framebuffer_renderbuffer, "Invalid glFramebufferRenderbuffer() usage", { GLuint fbo; GLuint rbo; glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); glGenRenderbuffers(1, &rbo); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not one of the accepted tokens."); glFramebufferRenderbuffer(-1, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, 0); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if renderbuffertarget is not GL_RENDERBUFFER."); glBindRenderbuffer(GL_RENDERBUFFER, rbo); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, -1, rbo); expectError(GL_INVALID_ENUM); glBindRenderbuffer(GL_RENDERBUFFER, 0); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if renderbuffer is neither 0 nor the name of an existing renderbuffer object."); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, -1); expectError(GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if zero is bound to target."); glBindFramebuffer(GL_FRAMEBUFFER, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, 0); expectError(GL_INVALID_OPERATION); m_log << TestLog::EndSection; glDeleteRenderbuffers(1, &rbo); glDeleteFramebuffers(1, &fbo); }); ES3F_ADD_API_CASE(framebuffer_texture2d, "Invalid glFramebufferTexture2D() usage", { GLuint fbo; GLuint tex2D; GLuint texCube; glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); glGenTextures(1, &tex2D); glBindTexture(GL_TEXTURE_2D, tex2D); glGenTextures(1, &texCube); glBindTexture(GL_TEXTURE_CUBE_MAP, texCube); expectError(GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not one of the accepted tokens."); glFramebufferTexture2D(-1, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if textarget is not an accepted texture target."); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, -1, tex2D, 0); expectError(GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if level is less than 0 or larger than log_2 of maximum texture size."); int maxSize; glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex2D, -1); expectError(GL_INVALID_VALUE); maxSize = deLog2Floor32(m_context.getContextInfo().getInt(GL_MAX_TEXTURE_SIZE)) + 1; glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex2D, maxSize); expectError(GL_INVALID_VALUE); maxSize = deLog2Floor32(m_context.getContextInfo().getInt(GL_MAX_CUBE_MAP_TEXTURE_SIZE)) + 1; glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X, texCube, maxSize); expectError(GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if texture is neither 0 nor the name of an existing texture object."); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, -1, 0); expectError(GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if textarget and texture are not compatible."); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X, tex2D, 0); expectError(GL_INVALID_OPERATION); glDeleteTextures(1, &tex2D); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texCube, 0); expectError(GL_INVALID_OPERATION); glDeleteTextures(1, &texCube); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if zero is bound to target."); glBindFramebuffer(GL_FRAMEBUFFER, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); expectError(GL_INVALID_OPERATION); m_log << TestLog::EndSection; glDeleteFramebuffers(1, &fbo); }); ES3F_ADD_API_CASE(renderbuffer_storage, "Invalid glRenderbufferStorage() usage", { deUint32 rbo; glGenRenderbuffers (1, &rbo); glBindRenderbuffer (GL_RENDERBUFFER, rbo); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not GL_RENDERBUFFER."); glRenderbufferStorage (-1, GL_RGBA4, 1, 1); expectError (GL_INVALID_ENUM); glRenderbufferStorage (GL_FRAMEBUFFER, GL_RGBA4, 1, 1); expectError (GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if internalformat is not a color-renderable, depth-renderable, or stencil-renderable format."); glRenderbufferStorage (GL_RENDERBUFFER, -1, 1, 1); expectError (GL_INVALID_ENUM); if (!m_context.getContextInfo().isExtensionSupported("GL_EXT_color_buffer_half_float")) // GL_EXT_color_buffer_half_float disables error { glRenderbufferStorage (GL_RENDERBUFFER, GL_RGB16F, 1, 1); expectError (GL_INVALID_ENUM); } glRenderbufferStorage (GL_RENDERBUFFER, GL_RGBA8_SNORM, 1, 1); expectError (GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if width or height is less than zero."); glRenderbufferStorage (GL_RENDERBUFFER, GL_RGBA4, -1, 1); expectError (GL_INVALID_VALUE); glRenderbufferStorage (GL_RENDERBUFFER, GL_RGBA4, 1, -1); expectError (GL_INVALID_VALUE); glRenderbufferStorage (GL_RENDERBUFFER, GL_RGBA4, -1, -1); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if width or height is greater than GL_MAX_RENDERBUFFER_SIZE."); GLint maxSize; glGetIntegerv (GL_MAX_RENDERBUFFER_SIZE, &maxSize); glRenderbufferStorage (GL_RENDERBUFFER, GL_RGBA4, 1, maxSize+1); expectError (GL_INVALID_VALUE); glRenderbufferStorage (GL_RENDERBUFFER, GL_RGBA4, maxSize+1, 1); expectError (GL_INVALID_VALUE); glRenderbufferStorage (GL_RENDERBUFFER, GL_RGBA4, maxSize+1, maxSize+1); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; glDeleteRenderbuffers(1, &rbo); }); ES3F_ADD_API_CASE(blit_framebuffer, "Invalid glBlitFramebuffer() usage", { deUint32 fbo[2]; deUint32 rbo[2]; deUint32 texture[2]; glGenFramebuffers (2, fbo); glGenTextures (2, texture); glGenRenderbuffers (2, rbo); glBindTexture (GL_TEXTURE_2D, texture[0]); glBindRenderbuffer (GL_RENDERBUFFER, rbo[0]); glBindFramebuffer (GL_READ_FRAMEBUFFER, fbo[0]); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glRenderbufferStorage (GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 32, 32); glFramebufferTexture2D (GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture[0], 0); glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo[0]); glCheckFramebufferStatus(GL_READ_FRAMEBUFFER); glBindTexture (GL_TEXTURE_2D, texture[1]); glBindRenderbuffer (GL_RENDERBUFFER, rbo[1]); glBindFramebuffer (GL_DRAW_FRAMEBUFFER, fbo[1]); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glRenderbufferStorage (GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 32, 32); glFramebufferTexture2D (GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture[1], 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo[1]); glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if mask contains any of the GL_DEPTH_BUFFER_BIT or GL_STENCIL_BUFFER_BIT and filter is not GL_NEAREST."); glBlitFramebuffer (0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_LINEAR); expectError (GL_INVALID_OPERATION); glBlitFramebuffer (0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_LINEAR); expectError (GL_INVALID_OPERATION); glBlitFramebuffer (0, 0, 16, 16, 0, 0, 16, 16, GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_LINEAR); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if mask contains GL_COLOR_BUFFER_BIT and read buffer format is incompatible with draw buffer format."); glBindTexture (GL_TEXTURE_2D, texture[0]); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA32UI, 32, 32, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, NULL); glFramebufferTexture2D (GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture[0], 0); m_log << TestLog::Message << "// Read buffer: GL_RGBA32UI, draw buffer: GL_RGBA" << TestLog::EndMessage; glBlitFramebuffer (0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT, GL_NEAREST); expectError (GL_INVALID_OPERATION); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA32I, 32, 32, 0, GL_RGBA_INTEGER, GL_INT, NULL); glFramebufferTexture2D (GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture[0], 0); m_log << TestLog::Message << "// Read buffer: GL_RGBA32I, draw buffer: GL_RGBA" << TestLog::EndMessage; glBlitFramebuffer (0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT, GL_NEAREST); expectError (GL_INVALID_OPERATION); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glFramebufferTexture2D (GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture[0], 0); glBindTexture (GL_TEXTURE_2D, texture[1]); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA32I, 32, 32, 0, GL_RGBA_INTEGER, GL_INT, NULL); glFramebufferTexture2D (GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture[1], 0); m_log << TestLog::Message << "// Read buffer: GL_RGBA8, draw buffer: GL_RGBA32I" << TestLog::EndMessage; glBlitFramebuffer (0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT, GL_NEAREST); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if filter is GL_LINEAR and the read buffer contains integer data."); glBindTexture (GL_TEXTURE_2D, texture[0]); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA32UI, 32, 32, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, NULL); glFramebufferTexture2D (GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture[0], 0); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glFramebufferTexture2D (GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture[1], 0); m_log << TestLog::Message << "// Read buffer: GL_RGBA32I, draw buffer: GL_RGBA8" << TestLog::EndMessage; glBlitFramebuffer (0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT, GL_LINEAR); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if mask contains GL_DEPTH_BUFFER_BIT or GL_STENCIL_BUFFER_BIT and the source and destination depth and stencil formats do not match."); glBindRenderbuffer (GL_RENDERBUFFER, rbo[0]); glRenderbufferStorage (GL_RENDERBUFFER, GL_DEPTH32F_STENCIL8, 32, 32); glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo[0]); glBlitFramebuffer (0, 0, 16, 16, 0, 0, 16, 16, GL_DEPTH_BUFFER_BIT, GL_NEAREST); expectError (GL_INVALID_OPERATION); glBlitFramebuffer (0, 0, 16, 16, 0, 0, 16, 16, GL_STENCIL_BUFFER_BIT, GL_NEAREST); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; glBindFramebuffer (GL_FRAMEBUFFER, 0); glDeleteFramebuffers (2, fbo); glDeleteTextures (2, texture); glDeleteRenderbuffers (2, rbo); }); ES3F_ADD_API_CASE(blit_framebuffer_multisample, "Invalid glBlitFramebuffer() usage", { deUint32 fbo[2]; deUint32 rbo[2]; glGenFramebuffers (2, fbo); glGenRenderbuffers (2, rbo); glBindRenderbuffer (GL_RENDERBUFFER, rbo[0]); glBindFramebuffer (GL_READ_FRAMEBUFFER, fbo[0]); glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_RGBA8, 32, 32); glFramebufferRenderbuffer (GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo[0]); glCheckFramebufferStatus (GL_READ_FRAMEBUFFER); glBindRenderbuffer (GL_RENDERBUFFER, rbo[1]); glBindFramebuffer (GL_DRAW_FRAMEBUFFER, fbo[1]); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if the value of GL_SAMPLE_BUFFERS for the draw buffer is greater than zero."); glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_RGBA8, 32, 32); glFramebufferRenderbuffer (GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo[1]); glBlitFramebuffer (0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT, GL_NEAREST); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if GL_SAMPLE_BUFFERS for the read buffer is greater than zero and the formats of draw and read buffers are not identical."); glRenderbufferStorage (GL_RENDERBUFFER, GL_RGBA4, 32, 32); glFramebufferRenderbuffer (GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo[1]); glBlitFramebuffer (0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT, GL_NEAREST); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if GL_SAMPLE_BUFFERS for the read buffer is greater than zero and the source and destination rectangles are not defined with the same (X0, Y0) and (X1, Y1) bounds."); glRenderbufferStorage (GL_RENDERBUFFER, GL_RGBA8, 32, 32); glFramebufferRenderbuffer (GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo[1]); glBlitFramebuffer (0, 0, 16, 16, 2, 2, 18, 18, GL_COLOR_BUFFER_BIT, GL_NEAREST); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; glBindFramebuffer (GL_FRAMEBUFFER, 0); glDeleteRenderbuffers (2, rbo); glDeleteFramebuffers (2, fbo); }); ES3F_ADD_API_CASE(framebuffer_texture_layer, "Invalid glFramebufferTextureLayer() usage", { deUint32 fbo; deUint32 tex3D; deUint32 tex2DArray; deUint32 tex2D; glGenFramebuffers (1, &fbo); glGenTextures (1, &tex3D); glGenTextures (1, &tex2DArray); glGenTextures (1, &tex2D); glBindFramebuffer (GL_FRAMEBUFFER, fbo); glBindTexture (GL_TEXTURE_3D, tex3D); glTexImage3D (GL_TEXTURE_3D, 0, GL_RGBA, 4, 4, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindTexture (GL_TEXTURE_2D_ARRAY, tex2DArray); glTexImage3D (GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, 4, 4, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindTexture (GL_TEXTURE_2D, tex2D); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, 4, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not one of the accepted tokens."); glFramebufferTextureLayer (-1, GL_COLOR_ATTACHMENT0, tex3D, 0, 1); expectError (GL_INVALID_ENUM); glFramebufferTextureLayer (GL_RENDERBUFFER, GL_COLOR_ATTACHMENT0, tex3D, 0, 1); expectError (GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if attachment is not one of the accepted tokens."); glFramebufferTextureLayer (GL_FRAMEBUFFER, -1, tex3D, 0, 1); expectError (GL_INVALID_ENUM); glFramebufferTextureLayer (GL_FRAMEBUFFER, GL_BACK, tex3D, 0, 1); expectError (GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if texture is non-zero and not the name of a 3D texture or 2D array texture."); glFramebufferTextureLayer (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, -1, 0, 0); expectError (GL_INVALID_OPERATION); glFramebufferTextureLayer (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex2D, 0, 0); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if texture is not zero and layer is negative."); glFramebufferTextureLayer (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex3D, 0, -1); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if texture is not zero and layer is greater than GL_MAX_3D_TEXTURE_SIZE-1 for a 3D texture."); int max3DTexSize; glGetIntegerv (GL_MAX_3D_TEXTURE_SIZE, &max3DTexSize); glFramebufferTextureLayer (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex3D, 0, max3DTexSize); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if texture is not zero and layer is greater than GL_MAX_ARRAY_TEXTURE_LAYERS-1 for a 2D array texture."); int maxArrayTexLayers; glGetIntegerv (GL_MAX_ARRAY_TEXTURE_LAYERS, &maxArrayTexLayers); glFramebufferTextureLayer (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex2DArray, 0, maxArrayTexLayers); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if zero is bound to target."); glBindFramebuffer (GL_FRAMEBUFFER, 0); glFramebufferTextureLayer (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex3D, 0, 1); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; glDeleteTextures (1, &tex3D); glDeleteTextures (1, &tex2DArray); glDeleteTextures (1, &tex2D); glDeleteFramebuffers (1, &fbo); }); ES3F_ADD_API_CASE(invalidate_framebuffer, "Invalid glInvalidateFramebuffer() usage", { deUint32 fbo; deUint32 texture; deUint32 attachments[2]; int maxColorAttachments; glGetIntegerv (GL_MAX_COLOR_ATTACHMENTS, &maxColorAttachments); attachments[0] = GL_COLOR_ATTACHMENT0; attachments[1] = GL_COLOR_ATTACHMENT0 + maxColorAttachments; glGenFramebuffers (1, &fbo); glGenTextures (1, &texture); glBindFramebuffer (GL_FRAMEBUFFER, fbo); glBindTexture (GL_TEXTURE_2D, texture); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); glCheckFramebufferStatus (GL_FRAMEBUFFER); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not GL_FRAMEBUFFER, GL_READ_FRAMEBUFFER or GL_DRAW_FRAMEBUFFER."); glInvalidateFramebuffer (-1, 1, &attachments[0]); expectError (GL_INVALID_ENUM); glInvalidateFramebuffer (GL_BACK, 1, &attachments[0]); expectError (GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if attachments contains GL_COLOR_ATTACHMENTm and m is greater than or equal to the value of GL_MAX_COLOR_ATTACHMENTS."); glInvalidateFramebuffer (GL_FRAMEBUFFER, 1, &attachments[1]); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; glDeleteTextures (1, &texture); glDeleteFramebuffers (1, &fbo); }); ES3F_ADD_API_CASE(invalidate_sub_framebuffer, "Invalid glInvalidateSubFramebuffer() usage", { deUint32 fbo; deUint32 texture; deUint32 attachments[2]; int maxColorAttachments; glGetIntegerv (GL_MAX_COLOR_ATTACHMENTS, &maxColorAttachments); attachments[0] = GL_COLOR_ATTACHMENT0; attachments[1] = GL_COLOR_ATTACHMENT0 + maxColorAttachments; glGenFramebuffers (1, &fbo); glGenTextures (1, &texture); glBindFramebuffer (GL_FRAMEBUFFER, fbo); glBindTexture (GL_TEXTURE_2D, texture); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); glCheckFramebufferStatus (GL_FRAMEBUFFER); expectError (GL_NO_ERROR); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not GL_FRAMEBUFFER, GL_READ_FRAMEBUFFER or GL_DRAW_FRAMEBUFFER."); glInvalidateSubFramebuffer (-1, 1, &attachments[0], 0, 0, 16, 16); expectError (GL_INVALID_ENUM); glInvalidateSubFramebuffer (GL_BACK, 1, &attachments[0], 0, 0, 16, 16); expectError (GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if attachments contains GL_COLOR_ATTACHMENTm and m is greater than or equal to the value of GL_MAX_COLOR_ATTACHMENTS."); glInvalidateSubFramebuffer (GL_FRAMEBUFFER, 1, &attachments[1], 0, 0, 16, 16); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; glDeleteTextures (1, &texture); glDeleteFramebuffers (1, &fbo); }); ES3F_ADD_API_CASE(renderbuffer_storage_multisample, "Invalid glRenderbufferStorageMultisample() usage", { deUint32 rbo; int maxSamplesSupportedRGBA4 = -1; glGetInternalformativ (GL_RENDERBUFFER, GL_RGBA4, GL_SAMPLES, 1, &maxSamplesSupportedRGBA4); glGenRenderbuffers (1, &rbo); glBindRenderbuffer (GL_RENDERBUFFER, rbo); m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if target is not GL_RENDERBUFFER."); glRenderbufferStorageMultisample (-1, 2, GL_RGBA4, 1, 1); expectError (GL_INVALID_ENUM); glRenderbufferStorageMultisample (GL_FRAMEBUFFER, 2, GL_RGBA4, 1, 1); expectError (GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if samples is greater than the maximum number of samples supported for internalformat."); glRenderbufferStorageMultisample (GL_RENDERBUFFER, maxSamplesSupportedRGBA4+1, GL_RGBA4, 1, 1); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_ENUM is generated if internalformat is not a color-renderable, depth-renderable, or stencil-renderable format."); glRenderbufferStorageMultisample (GL_RENDERBUFFER, 2, -1, 1, 1); expectError (GL_INVALID_ENUM); if (!m_context.getContextInfo().isExtensionSupported("GL_EXT_color_buffer_half_float")) // GL_EXT_color_buffer_half_float disables error { glRenderbufferStorageMultisample (GL_RENDERBUFFER, 2, GL_RGB16F, 1, 1); expectError (GL_INVALID_ENUM); } glRenderbufferStorageMultisample (GL_RENDERBUFFER, 2, GL_RGBA8_SNORM, 1, 1); expectError (GL_INVALID_ENUM); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_OPERATION is generated if internalformat is a signed or unsigned integer format and samples is greater than 0."); glRenderbufferStorageMultisample (GL_RENDERBUFFER, 1, GL_RGBA8UI, 1, 1); expectError (GL_INVALID_OPERATION); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if width or height is less than zero."); glRenderbufferStorageMultisample (GL_RENDERBUFFER, 2, GL_RGBA4, -1, 1); expectError (GL_INVALID_VALUE); glRenderbufferStorageMultisample (GL_RENDERBUFFER, 2, GL_RGBA4, 1, -1); expectError (GL_INVALID_VALUE); glRenderbufferStorageMultisample (GL_RENDERBUFFER, 2, GL_RGBA4, -1, -1); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; m_log << TestLog::Section("", "GL_INVALID_VALUE is generated if width or height is greater than GL_MAX_RENDERBUFFER_SIZE."); GLint maxSize; glGetIntegerv (GL_MAX_RENDERBUFFER_SIZE, &maxSize); glRenderbufferStorageMultisample (GL_RENDERBUFFER, 4, GL_RGBA4, 1, maxSize+1); expectError (GL_INVALID_VALUE); glRenderbufferStorageMultisample (GL_RENDERBUFFER, 4, GL_RGBA4, maxSize+1, 1); expectError (GL_INVALID_VALUE); glRenderbufferStorageMultisample (GL_RENDERBUFFER, 4, GL_RGBA4, maxSize+1, maxSize+1); expectError (GL_INVALID_VALUE); m_log << TestLog::EndSection; glDeleteRenderbuffers(1, &rbo); }); } } // Functional } // gles3 } // deqp
45.79385
234
0.736171
[ "object", "vector", "3d" ]
3389a0ca038fe8f4ce6fcd5252e520f6840138ad
653
cpp
C++
src/telegram/types/invoice.cpp
AlexTeos/CustomsForgeBot
7ac473ea88ded526c9edbc9486967a8a839b6fe2
[ "MIT" ]
null
null
null
src/telegram/types/invoice.cpp
AlexTeos/CustomsForgeBot
7ac473ea88ded526c9edbc9486967a8a839b6fe2
[ "MIT" ]
null
null
null
src/telegram/types/invoice.cpp
AlexTeos/CustomsForgeBot
7ac473ea88ded526c9edbc9486967a8a839b6fe2
[ "MIT" ]
null
null
null
#include "invoice.h" namespace Telegram { void readJsonObject(Invoice::Ptr& value, const QJsonObject& json, const QString& valueName) { if (json.contains(valueName) && json[valueName].isObject()) { value = Invoice::Ptr::create(); QJsonObject object = json[valueName].toObject(); readJsonObject(value->m_title, object, "title"); readJsonObject(value->m_description, object, "description"); readJsonObject(value->m_start_parameter, object, "start_parameter"); readJsonObject(value->m_currency, object, "currency"); readJsonObject(value->m_total_amount, object, "total_amount"); } } }
31.095238
91
0.683002
[ "object" ]
338c43e9d57b1dd09033c5911a0a4695b529e3eb
4,569
cc
C++
hbase-native-client/src/hbase/client/meta-utils.cc
bijugs/hbase-1.1.2.2.6.3.22-1
56954ebd740994c90ce872c732c1637a65e4865e
[ "Apache-2.0" ]
null
null
null
hbase-native-client/src/hbase/client/meta-utils.cc
bijugs/hbase-1.1.2.2.6.3.22-1
56954ebd740994c90ce872c732c1637a65e4865e
[ "Apache-2.0" ]
null
null
null
hbase-native-client/src/hbase/client/meta-utils.cc
bijugs/hbase-1.1.2.2.6.3.22-1
56954ebd740994c90ce872c732c1637a65e4865e
[ "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 "hbase/client/meta-utils.h" #include <folly/Conv.h> #include <memory> #include <utility> #include <vector> #include "hbase/connection/request.h" #include "hbase/connection/response.h" #include "hbase/client/response-converter.h" #include "hbase/exceptions/exception.h" #include "hbase/if/Client.pb.h" #include "hbase/serde/region-info.h" #include "hbase/serde/server-name.h" #include "hbase/serde/table-name.h" using hbase::pb::TableName; using hbase::pb::RegionInfo; using hbase::pb::RegionSpecifier_RegionSpecifierType; using hbase::pb::ScanRequest; using hbase::pb::ServerName; namespace hbase { MetaUtil::MetaUtil() { meta_region_info_.set_start_key(""); meta_region_info_.set_end_key(""); meta_region_info_.set_offline(false); meta_region_info_.set_split(false); meta_region_info_.set_replica_id(0); meta_region_info_.set_split(false); meta_region_info_.set_region_id(1); meta_region_info_.mutable_table_name()->set_namespace_(MetaUtil::kSystemNamespace); meta_region_info_.mutable_table_name()->set_qualifier(MetaUtil::kMetaTableQualifier); } std::string MetaUtil::RegionLookupRowkey(const TableName &tn, const std::string &row) const { return folly::to<std::string>(tn, ",", row, ",", "999999999999999999"); } std::unique_ptr<Request> MetaUtil::MetaRequest(const TableName tn, const std::string &row) const { auto request = Request::scan(); auto msg = std::static_pointer_cast<ScanRequest>(request->req_msg()); msg->set_number_of_rows(1); msg->set_close_scanner(true); // Set the region this scan goes to auto region = msg->mutable_region(); region->set_value(MetaUtil::kMetaRegion); region->set_type( RegionSpecifier_RegionSpecifierType::RegionSpecifier_RegionSpecifierType_ENCODED_REGION_NAME); auto scan = msg->mutable_scan(); // We don't care about before, just now. scan->set_max_versions(1); // Meta should be cached at all times. scan->set_cache_blocks(true); // We only want one row right now. // // TODO(eclark): Figure out if we should get more. scan->set_caching(1); // Close the scan after we have data. scan->set_small(true); // We know where to start but not where to end. scan->set_reversed(true); // Give me everything or nothing. scan->set_allow_partial_results(false); // Set the columns that we need auto info_col = scan->add_column(); info_col->set_family(MetaUtil::kCatalogFamily); info_col->add_qualifier(MetaUtil::kServerColumn); info_col->add_qualifier(MetaUtil::kRegionInfoColumn); scan->set_start_row(RegionLookupRowkey(tn, row)); return request; } std::shared_ptr<RegionLocation> MetaUtil::CreateLocation(const Response &resp, const TableName &tn) { std::vector<std::shared_ptr<Result>> results = ResponseConverter::FromScanResponse(resp); if (results.size() == 0) { throw TableNotFoundException(folly::to<std::string>(tn)); } if (results.size() != 1) { throw std::runtime_error("Was expecting exactly 1 result in meta scan response, got:" + std::to_string(results.size())); } auto result = *results[0]; auto region_info_str = result.Value(MetaUtil::kCatalogFamily, MetaUtil::kRegionInfoColumn); auto server_str = result.Value(MetaUtil::kCatalogFamily, MetaUtil::kServerColumn); CHECK(region_info_str); CHECK(server_str); auto row = result.Row(); auto region_info = folly::to<RegionInfo>(*region_info_str); auto server_name = folly::to<ServerName>(*server_str); return std::make_shared<RegionLocation>(row, std::move(region_info), server_name); } bool MetaUtil::IsMeta(const hbase::pb::TableName &tn) { return folly::to<std::string>(tn) == MetaUtil::kMetaTableName; } } // namespace hbase
36.261905
100
0.730794
[ "vector" ]
33926d1a77d245d7a7fd073b88d01a53c3f3276c
1,227
cpp
C++
geode/vector/blas.cpp
jjqcat/geode
157cc904c113cc5e29a1ffe7c091a83b8ec2cf8e
[ "BSD-3-Clause" ]
75
2015-02-08T22:04:31.000Z
2022-02-26T14:31:43.000Z
geode/vector/blas.cpp
bantamtools/geode
d906f1230b14953b68af63aeec2f7b0418d5fdfd
[ "BSD-3-Clause" ]
15
2015-01-08T15:11:38.000Z
2021-09-05T13:27:22.000Z
geode/vector/blas.cpp
bantamtools/geode
d906f1230b14953b68af63aeec2f7b0418d5fdfd
[ "BSD-3-Clause" ]
22
2015-03-11T16:43:13.000Z
2021-02-15T09:37:51.000Z
//##################################################################### // Header blas //##################################################################### #include "blas.h" #ifdef GEODE_BLAS #include <geode/python/from_python.h> #ifdef GEODE_MKL #define ILAENV ::ilaenv #else extern "C" { #ifndef __APPLE__ extern int ilaenv_(int*,char*,char*,int*,int*,int*,int*); #endif } #define ILAENV ::ilaenv_ #endif namespace geode { template<class T> int ilaenv(int ispec,const char* name,const char* opts,int m,int n) { char xname[20]; xname[0] = is_same<T,float>::value?'s':'d'; strcpy(xname+1,name); #ifndef __APPLE__ int no = -1; return ILAENV(&ispec,xname,(char*)opts,&m,&n,&no,&no); #else GEODE_NOT_IMPLEMENTED(); #endif } #ifdef GEODE_PYTHON CBLAS_TRANSPOSE FromPython<CBLAS_TRANSPOSE>::convert(PyObject* object) { const char* s = from_python<const char*>(object); switch (s[0]?s[1]?0:s[0]:0){ case 'n': case 'N': return CblasNoTrans; case 't': case 'T': return CblasTrans; default: throw ValueError("expected n or t (or N or T)");} } #endif template int ilaenv<float>(int,const char*,const char*,int,int); template int ilaenv<double>(int,const char*,const char*,int,int); } #endif
26.673913
85
0.605542
[ "object" ]
33998f8a6bfb1d006e907aad3cf34b59ba4a66a5
23,932
cc
C++
L1Trigger/L1TMuonCPPF/src/RecHitProcessor.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
2
2020-05-09T16:03:43.000Z
2020-05-09T16:03:50.000Z
L1Trigger/L1TMuonCPPF/src/RecHitProcessor.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
8
2020-03-20T23:18:36.000Z
2020-05-27T11:00:06.000Z
L1Trigger/L1TMuonCPPF/src/RecHitProcessor.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
3
2019-03-09T13:06:43.000Z
2020-07-03T00:47:30.000Z
#include "L1Trigger/L1TMuonCPPF/interface/RecHitProcessor.h" RecHitProcessor::RecHitProcessor() {} RecHitProcessor::~RecHitProcessor() {} void RecHitProcessor::processLook(const edm::Event &iEvent, const edm::EventSetup &iSetup, const edm::EDGetToken &recHitToken, std::vector<RecHitProcessor::CppfItem> &CppfVec1, l1t::CPPFDigiCollection &cppfDigis, const int MaxClusterSize) const { edm::Handle<RPCRecHitCollection> recHits; iEvent.getByToken(recHitToken, recHits); edm::ESHandle<RPCGeometry> rpcGeom; iSetup.get<MuonGeometryRecord>().get(rpcGeom); // The loop is over the detector container in the rpc geometry collection. We // are interested in the RPDdetID (inside of RPCChamber vectors), // specifically, the RPCrechits. to assignment the CPPFDigis. for (TrackingGeometry::DetContainer::const_iterator iDet = rpcGeom->dets().begin(); iDet < rpcGeom->dets().end(); iDet++) { // we do a cast over the class RPCChamber to obtain the RPCroll vectors, // inside of them, the RPCRechits are found. in other words, the method // ->rolls() does not exist for other kind of vector within DetContainer // and we can not obtain the rpcrechits in a suitable way. if (dynamic_cast<const RPCChamber *>(*iDet) == nullptr) continue; auto chamb = dynamic_cast<const RPCChamber *>(*iDet); std::vector<const RPCRoll *> rolls = (chamb->rolls()); // Loop over rolls in the chamber for (auto &iRoll : rolls) { RPCDetId rpcId = (*iRoll).id(); typedef std::pair<RPCRecHitCollection::const_iterator, RPCRecHitCollection::const_iterator> rangeRecHits; rangeRecHits recHitCollection = recHits->get(rpcId); // Loop over the RPC digis for (RPCRecHitCollection::const_iterator rechit_it = recHitCollection.first; rechit_it != recHitCollection.second; rechit_it++) { // const RPCDetId& rpcId = rechit_it->rpcId(); int rawId = rpcId.rawId(); // int station = rpcId.station(); int Bx = rechit_it->BunchX(); int isValid = rechit_it->isValid(); int firststrip = rechit_it->firstClusterStrip(); int clustersize = rechit_it->clusterSize(); LocalPoint lPos = rechit_it->localPosition(); const RPCRoll *roll = rpcGeom->roll(rpcId); const BoundPlane &rollSurface = roll->surface(); GlobalPoint gPos = rollSurface.toGlobal(lPos); float global_theta = emtf::rad_to_deg(gPos.theta().value()); float global_phi = emtf::rad_to_deg(gPos.phi().value()); //:::::::::::::::::::::::::::: // Establish the average position of the rechit int rechitstrip = firststrip; if (clustersize > 2) { int medium = 0; if (clustersize % 2 == 0) medium = 0.5 * (clustersize); else medium = 0.5 * (clustersize - 1); rechitstrip += medium; } if (clustersize > MaxClusterSize) continue; // This is just for test CPPFDigis with the RPC Geometry, It must be // "true" in the normal runs bool Geo = true; ////::::::::::::::::::::::::::::::::::::::::::::::::: // Set the EMTF Sector int EMTFsector1 = 0; int EMTFsector2 = 0; // sector 1 if ((global_phi > 15.) && (global_phi <= 16.3)) { EMTFsector1 = 1; EMTFsector2 = 6; } else if ((global_phi > 16.3) && (global_phi <= 53.)) { EMTFsector1 = 1; EMTFsector2 = 0; } else if ((global_phi > 53.) && (global_phi <= 75.)) { EMTFsector1 = 1; EMTFsector2 = 2; } // sector 2 else if ((global_phi > 75.) && (global_phi <= 76.3)) { EMTFsector1 = 1; EMTFsector2 = 2; } else if ((global_phi > 76.3) && (global_phi <= 113.)) { EMTFsector1 = 2; EMTFsector2 = 0; } else if ((global_phi > 113.) && (global_phi <= 135.)) { EMTFsector1 = 2; EMTFsector2 = 3; } // sector 3 // less than 180 else if ((global_phi > 135.) && (global_phi <= 136.3)) { EMTFsector1 = 2; EMTFsector2 = 3; } else if ((global_phi > 136.3) && (global_phi <= 173.)) { EMTFsector1 = 3; EMTFsector2 = 0; } else if ((global_phi > 173.) && (global_phi <= 180.)) { EMTFsector1 = 3; EMTFsector2 = 4; } // Greater than -180 else if ((global_phi < -165.) && (global_phi >= -180.)) { EMTFsector1 = 3; EMTFsector2 = 4; } // Fourth sector else if ((global_phi > -165.) && (global_phi <= -163.7)) { EMTFsector1 = 3; EMTFsector2 = 4; } else if ((global_phi > -163.7) && (global_phi <= -127.)) { EMTFsector1 = 4; EMTFsector2 = 0; } else if ((global_phi > -127.) && (global_phi <= -105.)) { EMTFsector1 = 4; EMTFsector2 = 5; } // fifth sector else if ((global_phi > -105.) && (global_phi <= -103.7)) { EMTFsector1 = 4; EMTFsector2 = 5; } else if ((global_phi > -103.7) && (global_phi <= -67.)) { EMTFsector1 = 5; EMTFsector2 = 0; } else if ((global_phi > -67.) && (global_phi <= -45.)) { EMTFsector1 = 5; EMTFsector2 = 6; } // sixth sector else if ((global_phi > -45.) && (global_phi <= -43.7)) { EMTFsector1 = 5; EMTFsector2 = 6; } else if ((global_phi > -43.7) && (global_phi <= -7.)) { EMTFsector1 = 6; EMTFsector2 = 0; } else if ((global_phi > -7.) && (global_phi <= 15.)) { EMTFsector1 = 6; EMTFsector2 = 1; } // std::vector<RecHitProcessor::CppfItem>::iterator it; // for(it = CppfVec1.begin(); it != CppfVec1.end(); it++){ // if( (*it).rawId == rawId) if(Geo_true) std::cout << (*it).rawId //<< "rawid" << rawId << std::endl; // } // Loop over the look up table double EMTFLink1 = 0.; double EMTFLink2 = 0.; std::vector<RecHitProcessor::CppfItem>::iterator cppf1; std::vector<RecHitProcessor::CppfItem>::iterator cppf; for (cppf1 = CppfVec1.begin(); cppf1 != CppfVec1.end(); cppf1++) { // Condition to save the CPPFDigi if (((*cppf1).rawId == rawId) && ((*cppf1).strip == rechitstrip)) { int old_strip = (*cppf1).strip; int before = 0; int after = 0; if (cppf1 != CppfVec1.begin()) before = (*(cppf1 - 2)).strip; else if (cppf1 == CppfVec1.begin()) before = (*cppf1).strip; if (cppf1 != CppfVec1.end()) after = (*(cppf1 + 2)).strip; else if (cppf1 == CppfVec1.end()) after = (*cppf1).strip; cppf = cppf1; if (clustersize == 2) { if (firststrip == 1) { if (before < after) cppf = (cppf1 - 1); else if (before > after) cppf = (cppf1 + 1); } else if (firststrip > 1) { if (before < after) cppf = (cppf1 + 1); else if (before > after) cppf = (cppf1 - 1); } } // Using the RPCGeometry if (Geo) { std::shared_ptr<l1t::CPPFDigi> MainVariables1(new l1t::CPPFDigi(rpcId, Bx, (*cppf).int_phi, (*cppf).int_theta, isValid, (*cppf).lb, (*cppf).halfchannel, EMTFsector1, EMTFLink1, old_strip, clustersize, global_phi, global_theta)); std::shared_ptr<l1t::CPPFDigi> MainVariables2(new l1t::CPPFDigi(rpcId, Bx, (*cppf).int_phi, (*cppf).int_theta, isValid, (*cppf).lb, (*cppf).halfchannel, EMTFsector2, EMTFLink2, old_strip, clustersize, global_phi, global_theta)); if ((EMTFsector1 > 0) && (EMTFsector2 == 0)) { cppfDigis.push_back(*MainVariables1.get()); } else if ((EMTFsector1 > 0) && (EMTFsector2 > 0)) { cppfDigis.push_back(*MainVariables1.get()); cppfDigis.push_back(*MainVariables2.get()); } else if ((EMTFsector1 == 0) && (EMTFsector2 == 0)) { continue; } } // Geo is true else { global_phi = 0.; global_theta = 0.; std::shared_ptr<l1t::CPPFDigi> MainVariables1(new l1t::CPPFDigi(rpcId, Bx, (*cppf).int_phi, (*cppf).int_theta, isValid, (*cppf).lb, (*cppf).halfchannel, EMTFsector1, EMTFLink1, old_strip, clustersize, global_phi, global_theta)); std::shared_ptr<l1t::CPPFDigi> MainVariables2(new l1t::CPPFDigi(rpcId, Bx, (*cppf).int_phi, (*cppf).int_theta, isValid, (*cppf).lb, (*cppf).halfchannel, EMTFsector2, EMTFLink2, old_strip, clustersize, global_phi, global_theta)); if ((EMTFsector1 > 0) && (EMTFsector2 == 0)) { cppfDigis.push_back(*MainVariables1.get()); } else if ((EMTFsector1 > 0) && (EMTFsector2 > 0)) { cppfDigis.push_back(*MainVariables1.get()); cppfDigis.push_back(*MainVariables2.get()); } else if ((EMTFsector1 == 0) && (EMTFsector2 == 0)) { continue; } } } // Condition to save the CPPFDigi } // Loop over the LUTVector } // Loop over the recHits } // End loop: for (std::vector<const RPCRoll*>::const_iterator r = // rolls.begin(); r != rolls.end(); ++r) } // End loop: for (TrackingGeometry::DetContainer::const_iterator iDet = // rpcGeom->dets().begin(); iDet < rpcGeom->dets().end(); iDet++) } void RecHitProcessor::process(const edm::Event &iEvent, const edm::EventSetup &iSetup, const edm::EDGetToken &recHitToken, l1t::CPPFDigiCollection &cppfDigis) const { // Get the RPC Geometry edm::ESHandle<RPCGeometry> rpcGeom; iSetup.get<MuonGeometryRecord>().get(rpcGeom); // Get the RecHits from the event edm::Handle<RPCRecHitCollection> recHits; iEvent.getByToken(recHitToken, recHits); // The loop is over the detector container in the rpc geometry collection. We // are interested in the RPDdetID (inside of RPCChamber vectors), // specifically, the RPCrechits. to assignment the CPPFDigis. for (TrackingGeometry::DetContainer::const_iterator iDet = rpcGeom->dets().begin(); iDet < rpcGeom->dets().end(); iDet++) { // we do a cast over the class RPCChamber to obtain the RPCroll vectors, // inside of them, the RPCRechits are found. in other words, the method // ->rolls() does not exist for other kind of vector within DetContainer // and we can not obtain the rpcrechits in a suitable way. if (dynamic_cast<const RPCChamber *>(*iDet) == nullptr) continue; auto chamb = dynamic_cast<const RPCChamber *>(*iDet); std::vector<const RPCRoll *> rolls = (chamb->rolls()); // Loop over rolls in the chamber for (auto &iRoll : rolls) { RPCDetId rpcId = (*iRoll).id(); typedef std::pair<RPCRecHitCollection::const_iterator, RPCRecHitCollection::const_iterator> rangeRecHits; rangeRecHits recHitCollection = recHits->get(rpcId); for (RPCRecHitCollection::const_iterator rechit_it = recHitCollection.first; rechit_it != recHitCollection.second; rechit_it++) { // const RPCDetId& rpcId = rechit_it->rpcId(); // int rawId = rpcId.rawId(); int region = rpcId.region(); // int station = rpcId.station(); int Bx = rechit_it->BunchX(); int isValid = rechit_it->isValid(); int firststrip = rechit_it->firstClusterStrip(); int clustersize = rechit_it->clusterSize(); LocalPoint lPos = rechit_it->localPosition(); const RPCRoll *roll = rpcGeom->roll(rpcId); const BoundPlane &rollSurface = roll->surface(); GlobalPoint gPos = rollSurface.toGlobal(lPos); float global_theta = emtf::rad_to_deg(gPos.theta().value()); float global_phi = emtf::rad_to_deg(gPos.phi().value()); // Endcap region only if (region != 0) { int int_theta = (region == -1 ? 180. * 32. / 36.5 : 0.) + (float)region * global_theta * 32. / 36.5 - 8.5 * 32 / 36.5; if (region == 1) { if (global_theta < 8.5) int_theta = 0; if (global_theta > 45.) int_theta = 31; } else if (region == -1) { if (global_theta < 135.) int_theta = 31; if (global_theta > 171.5) int_theta = 0; } // Local EMTF double local_phi = 0.; int EMTFsector1 = 0; int EMTFsector2 = 0; // sector 1 if ((global_phi > 15.) && (global_phi <= 16.3)) { local_phi = global_phi - 15.; EMTFsector1 = 1; EMTFsector2 = 6; } else if ((global_phi > 16.3) && (global_phi <= 53.)) { local_phi = global_phi - 15.; EMTFsector1 = 1; EMTFsector2 = 0; } else if ((global_phi > 53.) && (global_phi <= 75.)) { local_phi = global_phi - 15.; EMTFsector1 = 1; EMTFsector2 = 2; } // sector 2 else if ((global_phi > 75.) && (global_phi <= 76.3)) { local_phi = global_phi - 15.; EMTFsector1 = 1; EMTFsector2 = 2; } else if ((global_phi > 76.3) && (global_phi <= 113.)) { local_phi = global_phi - 75.; EMTFsector1 = 2; EMTFsector2 = 0; } else if ((global_phi > 113.) && (global_phi <= 135.)) { local_phi = global_phi - 75.; EMTFsector1 = 2; EMTFsector2 = 3; } // sector 3 // less than 180 else if ((global_phi > 135.) && (global_phi <= 136.3)) { local_phi = global_phi - 75.; EMTFsector1 = 2; EMTFsector2 = 3; } else if ((global_phi > 136.3) && (global_phi <= 173.)) { local_phi = global_phi - 135.; EMTFsector1 = 3; EMTFsector2 = 0; } else if ((global_phi > 173.) && (global_phi <= 180.)) { local_phi = global_phi - 135.; EMTFsector1 = 3; EMTFsector2 = 4; } // Greater than -180 else if ((global_phi < -165.) && (global_phi >= -180.)) { local_phi = global_phi + 225.; EMTFsector1 = 3; EMTFsector2 = 4; } // Fourth sector else if ((global_phi > -165.) && (global_phi <= -163.7)) { local_phi = global_phi + 225.; EMTFsector1 = 3; EMTFsector2 = 4; } else if ((global_phi > -163.7) && (global_phi <= -127.)) { local_phi = global_phi + 165.; EMTFsector1 = 4; EMTFsector2 = 0; } else if ((global_phi > -127.) && (global_phi <= -105.)) { local_phi = global_phi + 165.; EMTFsector1 = 4; EMTFsector2 = 5; } // fifth sector else if ((global_phi > -105.) && (global_phi <= -103.7)) { local_phi = global_phi + 165.; EMTFsector1 = 4; EMTFsector2 = 5; } else if ((global_phi > -103.7) && (global_phi <= -67.)) { local_phi = global_phi + 105.; EMTFsector1 = 5; EMTFsector2 = 0; } else if ((global_phi > -67.) && (global_phi <= -45.)) { local_phi = global_phi + 105.; EMTFsector1 = 5; EMTFsector2 = 6; } // sixth sector else if ((global_phi > -45.) && (global_phi <= -43.7)) { local_phi = global_phi + 105.; EMTFsector1 = 5; EMTFsector2 = 6; } else if ((global_phi > -43.7) && (global_phi <= -7.)) { local_phi = global_phi + 45.; EMTFsector1 = 6; EMTFsector2 = 0; } else if ((global_phi > -7.) && (global_phi <= 15.)) { local_phi = global_phi + 45.; EMTFsector1 = 6; EMTFsector2 = 1; } int int_phi = int((local_phi + 22.0) * 15. + .5); double EMTFLink1 = 0.; double EMTFLink2 = 0.; double lb = 0.; double halfchannel = 0.; // Invalid hit if (isValid == 0) int_phi = 2047; // Right integers range assert(0 <= int_phi && int_phi < 1250); assert(0 <= int_theta && int_theta < 32); std::shared_ptr<l1t::CPPFDigi> MainVariables1(new l1t::CPPFDigi(rpcId, Bx, int_phi, int_theta, isValid, lb, halfchannel, EMTFsector1, EMTFLink1, firststrip, clustersize, global_phi, global_theta)); std::shared_ptr<l1t::CPPFDigi> MainVariables2(new l1t::CPPFDigi(rpcId, Bx, int_phi, int_theta, isValid, lb, halfchannel, EMTFsector2, EMTFLink2, firststrip, clustersize, global_phi, global_theta)); if (int_theta == 31) continue; if ((EMTFsector1 > 0) && (EMTFsector2 == 0)) { cppfDigis.push_back(*MainVariables1.get()); } if ((EMTFsector1 > 0) && (EMTFsector2 > 0)) { cppfDigis.push_back(*MainVariables1.get()); cppfDigis.push_back(*MainVariables2.get()); } if ((EMTFsector1 == 0) && (EMTFsector2 == 0)) { continue; } } // No barrel rechits } // End loop: for (RPCRecHitCollection::const_iterator recHit = // recHitCollection.first; recHit != recHitCollection.second; recHit++) } // End loop: for (std::vector<const RPCRoll*>::const_iterator r = // rolls.begin(); r != rolls.end(); ++r) } // End loop: for (TrackingGeometry::DetContainer::const_iterator iDet = // rpcGeom->dets().begin(); iDet < rpcGeom->dets().end(); iDet++) } // End function: void RecHitProcessor::process()
46.833659
120
0.409577
[ "geometry", "vector" ]
339a25d566443663840f08b96142c3a27cf2c031
3,003
cpp
C++
Code/Tools/SceneAPI/SceneData/Rules/SkinRule.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Code/Tools/SceneAPI/SceneData/Rules/SkinRule.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Code/Tools/SceneAPI/SceneData/Rules/SkinRule.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/RTTI/ReflectContext.h> #include <AzCore/Memory/SystemAllocator.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Serialization/EditContext.h> #include <SceneAPI/SceneData/Rules/SkinRule.h> namespace AZ { namespace SceneAPI { namespace SceneData { AZ_CLASS_ALLOCATOR_IMPL(SkinRule, AZ::SystemAllocator, 0) SkinRule::SkinRule() : m_maxWeightsPerVertex(4) , m_weightThreshold(0.001f) { } AZ::u32 SkinRule::GetMaxWeightsPerVertex() const { return m_maxWeightsPerVertex; } float SkinRule::GetWeightThreshold() const { return m_weightThreshold; } void SkinRule::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context); if (!serializeContext) { return; } serializeContext->Class<ISkinRule, AZ::SceneAPI::DataTypes::IRule>()->Version(1); serializeContext->Class<SkinRule, ISkinRule>()->Version(2) ->Field("maxWeightsPerVertex", &SkinRule::m_maxWeightsPerVertex) ->Field("weightThreshold", &SkinRule::m_weightThreshold); AZ::EditContext* editContext = serializeContext->GetEditContext(); if (editContext) { editContext->Class<SkinRule>("Skin", "") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute("AutoExpand", true) ->Attribute(AZ::Edit::Attributes::NameLabelOverride, "") ->DataElement(AZ::Edit::UIHandlers::Default, &SkinRule::m_maxWeightsPerVertex, "Max weights per vertex", "The maximum number of joints that can influence a single vertex.") ->Attribute(AZ::Edit::Attributes::Min, 1) ->Attribute(AZ::Edit::Attributes::Max, 32) ->DataElement(AZ::Edit::UIHandlers::Default, &SkinRule::m_weightThreshold, "Weight threshold", "Weight value less than this will be ignored during import.") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Max, 0.01f) ->Attribute(AZ::Edit::Attributes::Step, 0.0001f) ->Attribute(AZ::Edit::Attributes::Decimals, 6) ->Attribute(AZ::Edit::Attributes::DisplayDecimals, 6); } } } // Rule } // Pipeline } // EMotionFX
41.136986
196
0.559774
[ "3d" ]
339b8581e000b757ce250aca3a134d995d1fefc5
342
hpp
C++
stan/math/prim/arr/fun/dot_self.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
stan/math/prim/arr/fun/dot_self.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
stan/math/prim/arr/fun/dot_self.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_PRIM_ARR_FUN_DOT_SELF_HPP #define STAN_MATH_PRIM_ARR_FUN_DOT_SELF_HPP #include <vector> #include <cstddef> namespace stan { namespace math { inline double dot_self(const std::vector<double>& x) { double sum = 0.0; for (double i : x) sum += i * i; return sum; } } // namespace math } // namespace stan #endif
17.1
54
0.710526
[ "vector" ]
339cbdffd60f0bdac44fd972a8f49c2946391938
9,414
hpp
C++
applications/SolidMechanicsApplication/custom_processes/assign_flags_to_model_part_entities_process.hpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
778
2017-01-27T16:29:17.000Z
2022-03-30T03:01:51.000Z
applications/SolidMechanicsApplication/custom_processes/assign_flags_to_model_part_entities_process.hpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
6,634
2017-01-15T22:56:13.000Z
2022-03-31T15:03:36.000Z
applications/SolidMechanicsApplication/custom_processes/assign_flags_to_model_part_entities_process.hpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
224
2017-02-07T14:12:49.000Z
2022-03-06T23:09:34.000Z
// // Project Name: KratosSolidMechanicsApplication $ // Created by: $Author: JMCarbonell $ // Last modified by: $Co-Author: $ // Date: $Date: August 2016 $ // Revision: $Revision: 0.0 $ // // #if !defined(KRATOS_ASSIGN_FLAGS_TO_MODEL_PART_ENTITIES_PROCESS_H_INCLUDED) #define KRATOS_ASSIGN_FLAGS_TO_MODEL_PART_ENTITIES_PROCESS_H_INCLUDED // System includes // External includes // Project includes #include "includes/model_part.h" #include "includes/kratos_parameters.h" #include "processes/process.h" namespace Kratos { ///@name Kratos Classes ///@{ /// The base class for assigning a value to scalar variables or array_1d components processes in Kratos. /** This function assigns a value to a variable belonging to all of the nodes in a given mesh */ class AssignFlagsToModelPartEntitiesProcess : public Process { public: ///@name Type Definitions ///@{ /// Pointer definition of AssignFlagsToModelPartEntitiesProcess KRATOS_CLASS_POINTER_DEFINITION(AssignFlagsToModelPartEntitiesProcess); ///@} ///@name Life Cycle ///@{ AssignFlagsToModelPartEntitiesProcess(ModelPart& rModelPart, const std::string EntityType, const std::vector<Flags>& rAssignFlags) : Process(Flags()) , mrModelPart(rModelPart), mEntityType(EntityType), mrTransferFlags(std::vector<Flags>()), mrAssignFlags(rAssignFlags) { KRATOS_TRY KRATOS_CATCH(""); } AssignFlagsToModelPartEntitiesProcess(ModelPart& rModelPart, const std::string EntityType, const std::vector<Flags>& rAssignFlags, const std::vector<Flags>& rTransferFlags) : Process(Flags()) , mrModelPart(rModelPart), mEntityType(EntityType), mrTransferFlags(rTransferFlags), mrAssignFlags(rAssignFlags) { KRATOS_TRY KRATOS_CATCH(""); } /// Destructor. ~AssignFlagsToModelPartEntitiesProcess() override {} ///@} ///@name Operators ///@{ /// This operator is provided to call the process as a function and simply calls the Execute method. void operator()() { Execute(); } ///@} ///@name Operations ///@{ /// Execute method is used to execute the AssignFlagsToModelPartEntitiesProcess algorithms. void Execute() override { KRATOS_TRY; if (mEntityType == "Nodes") { const int nnodes = mrModelPart.Nodes().size(); if (nnodes != 0) { ModelPart::NodesContainerType::iterator it_begin = mrModelPart.NodesBegin(); #pragma omp parallel for for (int i = 0; i < nnodes; i++) { ModelPart::NodesContainerType::iterator it = it_begin + i; if (this->MatchTransferFlags(*(it.base()))) { this->AssignFlags(*(it.base())); } } } } else if (mEntityType == "Elements") { const int nelements = mrModelPart.Elements().size(); if (nelements != 0) { ModelPart::ElementsContainerType::iterator it_begin = mrModelPart.ElementsBegin(); #pragma omp parallel for for (int i = 0; i < nelements; i++) { ModelPart::ElementsContainerType::iterator it = it_begin + i; if (this->MatchTransferFlags(*(it.base()))) { this->AssignFlags(*(it.base())); } } } } else if (mEntityType == "Conditions") { const int nconditions = mrModelPart.Conditions().size(); if (nconditions != 0) { ModelPart::ConditionsContainerType::iterator it_begin = mrModelPart.ConditionsBegin(); //#pragma omp parallel for for (int i = 0; i < nconditions; i++) { ModelPart::ConditionsContainerType::iterator it = it_begin + i; if (this->MatchTransferFlags(*(it.base()))) { this->AssignFlags(*(it.base())); } } } } KRATOS_CATCH(""); } /// this function is designed for being called at the beginning of the computations /// right after reading the model and the groups void ExecuteInitialize() override { } /// this function is designed for being execute once before the solution loop but after all of the /// solvers where built void ExecuteBeforeSolutionLoop() override { } /// this function will be executed at every time step BEFORE performing the solve phase void ExecuteInitializeSolutionStep() override { } /// this function will be executed at every time step AFTER performing the solve phase void ExecuteFinalizeSolutionStep() override { } /// this function will be executed at every time step BEFORE writing the output void ExecuteBeforeOutputStep() override { } /// this function will be executed at every time step AFTER writing the output void ExecuteAfterOutputStep() override { } /// this function is designed for being called at the end of the computations /// right after reading the model and the groups void ExecuteFinalize() override { } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "AssignFlagsToModelPartEntitiesProcess"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << "AssignFlagsToModelPartEntitiesProcess"; } /// Print object's data. void PrintData(std::ostream& rOStream) const override { } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ /// Copy constructor. AssignFlagsToModelPartEntitiesProcess(AssignFlagsToModelPartEntitiesProcess const& rOther); ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ModelPart& mrModelPart; const std::string mEntityType; const std::vector<Flags> mrTransferFlags; const std::vector<Flags> mrAssignFlags; ///@} ///@name Private Operators ///@{ bool MatchTransferFlags(const Node<3>::Pointer& pNode) { for(unsigned int i = 0; i<mrTransferFlags.size(); i++) { if( pNode->IsNot(mrTransferFlags[i]) ) return false; } return true; } void AssignFlags(const Node<3>::Pointer& pNode) { for(unsigned int i = 0; i<mrAssignFlags.size(); i++) pNode->Set(mrAssignFlags[i]); } bool MatchTransferFlags(const Element::Pointer& pElement) { for(unsigned int i = 0; i<mrTransferFlags.size(); i++) { if( pElement->IsNot(mrTransferFlags[i]) ) return false; } return true; } void AssignFlags(const Element::Pointer& pElement) { for(unsigned int i = 0; i<mrAssignFlags.size(); i++) pElement->Set(mrAssignFlags[i]); } bool MatchTransferFlags(const Condition::Pointer& pCondition) { for(unsigned int i = 0; i<mrTransferFlags.size(); i++) { if( pCondition->IsNot(mrTransferFlags[i]) ) return false; } return true; } void AssignFlags(const Condition::Pointer& pCondition) { for(unsigned int i = 0; i<mrAssignFlags.size(); i++) pCondition->Set(mrAssignFlags[i]); } ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ /// Assignment operator. AssignFlagsToModelPartEntitiesProcess& operator=(AssignFlagsToModelPartEntitiesProcess const& rOther); ///@} ///@name Serialization ///@{ ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; // Class AssignFlagsToModelPartEntitiesProcess ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function inline std::istream& operator >> (std::istream& rIStream, AssignFlagsToModelPartEntitiesProcess& rThis); /// output stream function inline std::ostream& operator << (std::ostream& rOStream, const AssignFlagsToModelPartEntitiesProcess& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} } // namespace Kratos. #endif // KRATOS_ASSIGN_FLAGS_TO_MODEL_PART_ENTITIES_PROCESS_H_INCLUDED defined
23.359801
219
0.575738
[ "mesh", "object", "vector", "model" ]
339f0745b0ababc093cf893833875fcabe86e2bc
23,508
hpp
C++
h5cpp/H5Pall.hpp
pini-gh/h5cpp
852dbcf14632c12d5567092ea638434a0f0f5d71
[ "MIT", "BSD-3-Clause-LBNL", "BSD-3-Clause" ]
9
2022-01-29T22:21:19.000Z
2022-03-10T06:26:40.000Z
h5cpp/H5Pall.hpp
pini-gh/h5cpp
852dbcf14632c12d5567092ea638434a0f0f5d71
[ "MIT", "BSD-3-Clause-LBNL", "BSD-3-Clause" ]
null
null
null
h5cpp/H5Pall.hpp
pini-gh/h5cpp
852dbcf14632c12d5567092ea638434a0f0f5d71
[ "MIT", "BSD-3-Clause-LBNL", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2018 vargaconsulting, Toronto,ON Canada * Author: Varga, Steven <steven@vargaconsulting.ca> * */ #ifndef H5CPP_PALL_HPP #define H5CPP_PALL_HPP namespace h5 { namespace impl { /* proxy object that gets converted to property_id with restriction that * only same class properties may be daisy chained */ template <class Derived, class phid_t> struct prop_base { using hidtype = phid_t; using type = phid_t; prop_base(){ } // removed ctor ~prop_base(){ if( H5Iis_valid( handle ) ){ H5Pclose( handle ); } } // prevents property type mismatch at compile time: template <class R> typename std::enable_if< std::is_same<typename R::hidtype, hidtype>::value , const prop_base<Derived, phid_t>& >::type operator|( const R& rhs ) const { rhs.copy( handle ); return *this; } // convert to propery void copy(::hid_t handle_) const { /*CRTP idiom*/ static_cast<const Derived*>(this)->copy_impl( handle_ ); } /*transfering ownership to managed handle*/ operator phid_t( ) const { static_cast<const Derived*>(this)->copy_impl( handle ); H5Iinc_ref( handle ); /*keep this alive */ return phid_t{handle}; } ::hid_t handle; }; /*property with a capi function call with some arguments, also is the base for other properties */ template <class phid_t, defprop_t init, class capi, typename capi::fn_t capi_call> struct prop_t : prop_base< prop_t<phid_t,init,capi,capi_call>, phid_t > { using base_t = prop_base<prop_t<phid_t,init,capi,capi_call>, phid_t>; using args_t = typename capi::args_t; using capi_t = typename capi::type; using type = phid_t; prop_t( typename capi::args_t values ) : args( values ) { H5CPP_CHECK_NZ( (this->handle = H5Pcreate(init())), h5::error::property_list::misc, "failed to create property"); } prop_t(){ H5CPP_CHECK_NZ( (this->handle = H5Pcreate(init())), h5::error::property_list::misc, "failed to create property"); } void copy_impl(::hid_t id) const { //int i = capi_call + 1; /*CAPI needs `this` hid_t id passed along */ capi_t capi_args = std::tuple_cat( std::tie(id), args ); H5CPP_CHECK_NZ( compat::apply(capi_call, capi_args), h5::error::property_list::argument,"failed to parse arguments..."); } args_t args; }; /* T prop is much similar to other properties, except the value needs HDF5 type info and passed by * const void* pointer type. This is reflected by templating `prop_t` */ template <class phid_t, defprop_t init, class capi, typename capi::fn_t capi_call, class T> struct tprop_t final : prop_t<phid_t,init,capi,capi_call> { // ::hid_t,const void* using type = phid_t; using base_t = prop_t<phid_t,init,capi,capi_call>; tprop_t( T value ) : base_t( std::make_tuple( h5::copy<T>( h5::dt_t<T>() ), &this->value) ), value(value) { } ~tprop_t(){ // don't forget that the first argument is a HDF5 type info, that needs closing if( H5Iis_valid( std::get<0>(this->args) ) ) H5Tclose( std::get<0>(this->args) ); } T value; }; /* takes an arbitrary length of hsize_t sequence and calls H5Pset_xxx */ template <class phid_t, defprop_t init, class capi, typename capi::fn_t capi_call> struct aprop_t final : prop_t<phid_t,init,capi,capi_call> { using type = phid_t; using base_t = prop_t<phid_t,init,capi,capi_call>; aprop_t( std::initializer_list<hsize_t> values ) : base_t( std::make_tuple( values.size(), this->values) ) { std::copy( std::begin(values), std::end(values), this->values); } template <class T, size_t N> aprop_t( std::array<T,N> values ) : base_t( std::make_tuple( values.size(), this->values) ) { std::copy( std::begin(values), std::end(values), this->values); } hsize_t values[H5CPP_MAX_RANK]; }; /* CAPI macros are sequence calls: (H5OPEN, register_property_class), these are all meant to be read only/copied from, */ #define H5CPP__capicall( name, default_id ) ::hid_t inline default_##name(){ return default_id; } \ template <class... args> using name##_args = impl::capi_t<args...>; \ template <class capi, typename capi::fn_t capi_call> \ using name##_call = prop_t<h5::name##_t, default_##name, capi, capi_call>; \ //impl::fapl_call< impl::fapl_args<hid_t,H5F_libver_t,H5F_libver_t>,H5Pset_libver_bounds>; H5CPP__capicall( acpl, H5P_ATTRIBUTE_CREATE) H5CPP__capicall( dapl, H5P_DATASET_ACCESS ) H5CPP__capicall( dxpl, H5P_DATASET_XFER ) H5CPP__capicall( dcpl, H5P_DATASET_CREATE ) H5CPP__capicall( tapl, H5P_DATATYPE_ACCESS ) H5CPP__capicall( tcpl, H5P_DATATYPE_CREATE ) H5CPP__capicall( fapl, H5P_FILE_ACCESS ) H5CPP__capicall( fcpl, H5P_FILE_CREATE ) H5CPP__capicall( fmpl, H5P_FILE_MOUNT ) H5CPP__capicall( gapl, H5P_GROUP_ACCESS) H5CPP__capicall( gcpl, H5P_GROUP_CREATE ) H5CPP__capicall( lapl, H5P_LINK_ACCESS) H5CPP__capicall( lcpl, H5P_LINK_CREATE ) H5CPP__capicall( ocpl, H5P_OBJECT_COPY) H5CPP__capicall( ocrl, H5P_OBJECT_CREATE ) H5CPP__capicall( scpl, H5P_STRING_CREATE) #undef H5CPP__defid // only data control property list set_chunk has this pattern, lets allow to define CAPI argument lists // the same way as with others template <class capi, typename capi::fn_t capi_call> using dcpl_acall = aprop_t<h5::dcpl_t,default_dcpl, capi,capi_call>; // only data control property list set_value has this pattern, lets allow to define CAPI argument lists // the same way as with others template <class capi, typename capi::fn_t capi_call, class T> using dcpl_tcall = tprop_t<h5::dcpl_t,default_dcpl, capi, capi_call, T>; }} namespace h5::impl { template <bool version, class capi, typename capi::fn_t capi_call > using fapl_vcall = typename std::conditional<version, impl::fapl_call<capi,capi_call>,void>::type; } /** impl::property_group<H5Pset_property, args...> args... ::= all argument types except the first `this` hid_t prop_ID * since it is implicitly passed by template class. */ namespace h5 { // FILE CREATION PROPERTY LISTS #if H5_VERSION_GE(1,8,0) using sizes = impl::fcpl_call< impl::fcpl_args<hid_t,size_t,size_t>, H5Pset_sizes>; using sym_k = impl::fcpl_call< impl::fcpl_args<hid_t,unsigned,unsigned>, H5Pset_sym_k>; using istore_k = impl::fcpl_call< impl::fcpl_args<hid_t,unsigned>, H5Pset_istore_k>; using shared_mesg_nindexes = impl::fcpl_call< impl::fcpl_args<hid_t,unsigned>, H5Pset_shared_mesg_nindexes>; using shared_mesg_index = impl::fcpl_call< impl::fcpl_args<hid_t,unsigned,unsigned,unsigned>,H5Pset_shared_mesg_index>; using shared_mesg_phase_change = impl::fcpl_call< impl::fcpl_args<hid_t,unsigned,unsigned>, H5Pset_shared_mesg_phase_change>; #endif #if H5_VERSION_GE(1,10,0) using userblock = impl::fcpl_call< impl::fcpl_args<hid_t,hsize_t>, H5Pset_userblock>; #endif #if H5_VERSION_GE(1,10,1) using file_space_page_size = impl::fcpl_call< impl::fcpl_args<hid_t,hsize_t>, H5Pset_file_space_page_size>; using file_space_page_strategy = impl::fcpl_call< impl::fcpl_args<hid_t,H5F_fspace_strategy_t,hbool_t,hsize_t>,H5Pset_file_space_strategy>; /* FIXME: takes arguments, should be a template! const static h5::file_space_page_strategy strategy_fsm_aggr{H5F_FSPACE_STRATEGY_FSM_AGGR}; const static h5::file_space_page_strategy strategy_aggr{H5F_FSPACE_STRATEGY_AGGR}; const static h5::file_space_page_strategy strategy_none{H5F_FSPACE_STRATEGY_NONE}; */ #ifdef H5_HAVE_PARALLEL const static h5::file_space_page_strategy strategy_page{H5F_FSPACE_STRATEGY_PAGE}; #endif #endif // FILE ACCESS PROPERTY LISTS using fclose_degree = impl::fapl_call< impl::fapl_args<hid_t,H5F_close_degree_t>, H5Pset_fclose_degree>; using fapl_core = impl::fapl_call< impl::fapl_args<hid_t,size_t,hbool_t>, H5Pset_fapl_core>; using fapl_family = impl::fapl_call< impl::fapl_args<hid_t,hsize_t,hid_t>, H5Pset_fapl_family>; using family_offset = impl::fapl_call< impl::fapl_args<hid_t,hsize_t>, H5Pset_family_offset>; using fapl_multi = impl::fapl_call< impl::fapl_args<hid_t,const H5FD_mem_t *, const hid_t *, const char * const *, const haddr_t *, hbool_t>,H5Pset_fapl_multi>; using multi_type = impl::fapl_call< impl::fapl_args<hid_t,H5FD_mem_t>,H5Pset_multi_type>; using fapl_split = impl::fapl_call< impl::fapl_args<hid_t,const char*, hid_t,const char*,hid_t>,H5Pset_fapl_split>; using meta_block_size = impl::fapl_call< impl::fapl_args<hid_t,hsize_t>,H5Pset_meta_block_size>; using sieve_buf_size = impl::fapl_call< impl::fapl_args<hid_t,size_t>,H5Pset_sieve_buf_size>; using alignment = impl::fapl_call< impl::fapl_args<hid_t,hsize_t, hsize_t>,H5Pset_alignment>; using cache = impl::fapl_call< impl::fapl_args<hid_t,int,size_t,size_t,double>,H5Pset_cache>; using libver_bounds = impl::fapl_call< impl::fapl_args<hid_t,H5F_libver_t,H5F_libver_t>,H5Pset_libver_bounds>; #if H5_VERSION_GE(1,8,2) using driver = impl::fapl_call< impl::fapl_args<hid_t,hid_t, const void *>, H5Pset_driver>;; #endif #if H5_VERSION_GE(1,8,9) using file_image = impl::fapl_call< impl::fapl_args<hid_t,void*,size_t>,H5Pset_file_image>; //FIXME: using file_image_callback = impl::fapl_call< impl::fapl_args<hid_t,H5_file_image_callbacks_t *callbacks_ptr>,H5Pset_file_image_callback>; using elink_file_cache_size = impl::fapl_call< impl::fapl_args<hid_t,unsigned>,H5Pset_elink_file_cache_size>; #endif #if H5_VERSION_GE(1,8,14) using core_write_tracking = impl::fapl_call< impl::fapl_args<hid_t,hbool_t,size_t>, H5Pset_core_write_tracking>; using fapl_log = impl::fapl_call< impl::fapl_args<hid_t,const char*,unsigned long long,size_t>,H5Pset_fapl_log>; #endif #if H5_VERSION_GE(1,10,1) using page_buffer_size = impl::fapl_call< impl::fapl_args<hid_t,size_t,unsigned,unsigned>,H5Pset_page_buffer_size>; using evict_on_close = impl::fapl_call< impl::fapl_args<hid_t,hbool_t>,H5Pset_evict_on_close>; using metadata_read_attempts = impl::fapl_call< impl::fapl_args<hid_t,unsigned>,H5Pset_metadata_read_attempts>; using mdc_config = impl::fapl_call< impl::fapl_args<hid_t,H5AC_cache_config_t *>,H5Pset_mdc_config>; using mdc_image_config = impl::fapl_call< impl::fapl_args<hid_t,H5AC_cache_image_config_t*>,H5Pset_mdc_image_config>; using mdc_log_options = impl::fapl_call< impl::fapl_args<hid_t,hbool_t,const char*,hbool_t>,H5Pset_mdc_log_options>; #endif #if H5_VERSION_GE(1,14,0) //FIXME: find out why the compile error with valid 1.8.0 version using fapl_direct = impl::fapl_call<impl::fapl_args<hid_t,size_t,size_t,size_t, H5Pset_fapl_direct>; #endif // namespace flag { using fapl_sec2 = impl::fapl_call< impl::fapl_args<hid_t>,H5Pset_fapl_sec2>; using fapl_stdio = impl::fapl_call< impl::fapl_args<hid_t>,H5Pset_fapl_stdio>; #if H5_HAVE_WIN32_API using fapl_windows = impl::fapl_call< impl::fapl_args<hid_t>,H5Pset_fapl_windows>; #endif } const static h5::libver_bounds latest_version({H5F_LIBVER_LATEST, H5F_LIBVER_LATEST}); const static flag::fapl_sec2 sec2; const static flag::fapl_stdio stdio; const static h5::fclose_degree fclose_degree_weak{H5F_CLOSE_WEAK}; const static h5::fclose_degree fclose_degree_semi{H5F_CLOSE_SEMI}; const static h5::fclose_degree fclose_degree_strong{H5F_CLOSE_STRONG}; const static h5::fclose_degree fclose_degree_default{H5F_CLOSE_DEFAULT}; const static h5::multi_type multi_type_super{H5FD_MEM_SUPER}; const static h5::multi_type multi_type_btree{H5FD_MEM_BTREE}; const static h5::multi_type multi_type_draw{H5FD_MEM_DRAW}; const static h5::multi_type multi_type_gheap{H5FD_MEM_GHEAP}; const static h5::multi_type multi_type_lheap{H5FD_MEM_LHEAP}; const static h5::multi_type multi_type_ohdr{H5FD_MEM_OHDR}; // GROUP CREATION PROPERTY LISTS using local_heap_size_hint = impl::gcpl_call< impl::gcpl_args<hid_t,size_t>,H5Pset_local_heap_size_hint>; using link_creation_order = impl::gcpl_call< impl::gcpl_args<hid_t,unsigned>,H5Pset_link_creation_order>; using est_link_info = impl::gcpl_call< impl::gcpl_args<hid_t,unsigned, unsigned>,H5Pset_est_link_info>; using link_phase_change = impl::gcpl_call< impl::gcpl_args<hid_t,unsigned, unsigned>,H5Pset_link_phase_change>; // GROUP ACCESS PROPERTY LISTS //using local_heap_size_hint = impl::gapl_call< impl::gcpl_args<hid_t,hbool_t>, H5Pset_all_coll_metadata_ops>; // LINK CREATION PROPERTY LISTS using char_encoding = impl::lcpl_call< impl::lcpl_args<hid_t,H5T_cset_t>,H5Pset_char_encoding>; using create_intermediate_group= impl::lcpl_call< impl::lcpl_args<hid_t,unsigned>,H5Pset_create_intermediate_group>; const static h5::char_encoding ascii{H5T_CSET_ASCII}; const static h5::char_encoding utf8{H5T_CSET_UTF8}; const static h5::create_intermediate_group create_path{1}; const static h5::create_intermediate_group dont_create_path{0}; // LINK ACCESS PROPERTY LISTS using nlinks = impl::lapl_call< impl::lapl_args<hid_t,size_t>,H5Pset_nlinks>; using elink_cb = impl::lapl_call< impl::lapl_args<hid_t,H5L_elink_traverse_t, void*>,H5Pset_elink_cb>; using elink_prefix = impl::lapl_call< impl::lapl_args<hid_t,const char*>,H5Pset_elink_prefix>; #if H5_VERSION_GE(1,9,0) using elink_fapl = impl::lapl_call< impl::lapl_args<hid_t,hid_t>,H5Pset_elink_fapl>; #endif using elink_acc_flags = impl::lapl_call< impl::lapl_args<hid_t,unsigned>,H5Pset_elink_acc_flags>; const static h5::elink_acc_flags acc_rdwr{H5F_ACC_RDWR}; const static h5::elink_acc_flags acc_rdonly{H5F_ACC_RDONLY}; const static h5::elink_acc_flags acc_default{H5F_ACC_DEFAULT}; // DATA CREATION PROPERTY LISTS #if H5_VERSION_GE(1,8,16) using chunk = impl::dcpl_acall< impl::dcpl_args<hid_t,int,const hsize_t*>, H5Pset_chunk>; /*acall ::= array call of hsize_t */ #endif #if H5_VERSION_GE(1,10,0) using layout = impl::dcpl_call< impl::dcpl_args<hid_t,H5D_layout_t>,H5Pset_layout>; using chunk_opts = impl::dcpl_call< impl::dcpl_args<hid_t,unsigned>,H5Pset_chunk_opts>; #endif using deflate = impl::dcpl_call< impl::dcpl_args<hid_t,unsigned>,H5Pset_deflate>; using gzip = deflate; using fill_time = impl::dcpl_call< impl::dcpl_args<hid_t,H5D_fill_time_t>,H5Pset_fill_time>; using alloc_time = impl::dcpl_call< impl::dcpl_args<hid_t,H5D_alloc_time_t>,H5Pset_alloc_time>; using chunk_opts = impl::dcpl_call< impl::dcpl_args<hid_t,unsigned>,H5Pset_chunk_opts>; template<class T> /*tcall ::= templated call with T*/ using fill_value = impl::dcpl_tcall< impl::dcpl_args<hid_t,hid_t,const void*>, H5Pset_fill_value, T>; using chunk = impl::dcpl_acall< impl::dcpl_args<hid_t,int,const hsize_t*>, H5Pset_chunk>; /*acall ::= array call of hsize_t */ namespace flag{ using fletcher32 = impl::dcpl_call< impl::dcpl_args<hid_t>,H5Pset_fletcher32>; using shuffle = impl::dcpl_call< impl::dcpl_args<hid_t>,H5Pset_shuffle>; using nbit = impl::dcpl_call< impl::dcpl_args<hid_t>,H5Pset_nbit>; } const static flag::fletcher32 fletcher32; const static flag::shuffle shuffle; const static flag::nbit nbit; const static h5::layout layout_compact{H5D_COMPACT}; const static h5::layout layout_contigous{H5D_CONTIGUOUS}; const static h5::layout layout_chunked{H5D_CHUNKED}; const static h5::layout layout_virtual{H5D_VIRTUAL}; const static h5::fill_time fill_time_ifset{H5D_FILL_TIME_IFSET}; const static h5::fill_time fill_time_alloc{H5D_FILL_TIME_ALLOC}; const static h5::fill_time fill_time_never{H5D_FILL_TIME_NEVER}; const static h5::alloc_time alloc_time_default{H5D_ALLOC_TIME_DEFAULT}; const static h5::alloc_time alloc_time_early{H5D_ALLOC_TIME_EARLY}; const static h5::alloc_time alloc_time_incr{H5D_ALLOC_TIME_INCR}; const static h5::alloc_time alloc_time_late{H5D_ALLOC_TIME_LATE}; const static h5::chunk_opts dont_filter_partial_chunks{H5D_CHUNK_DONT_FILTER_PARTIAL_CHUNKS}; // DATA ACCESS PROPERTY LISTS: see H5Pdapl.hpp // DATA TRANSFER PROPERTY LISTS #if H5_VERSION_GE(1,10,0) using type_conv_cb = impl::dxpl_call< impl::dxpl_args<hid_t,H5T_conv_except_func_t,void*>,H5Pset_type_conv_cb>; #endif using buffer = impl::dxpl_call< impl::dxpl_args<hid_t,size_t,void*,void*>,H5Pset_buffer>; using edc_check = impl::dxpl_call< impl::dxpl_args<hid_t,H5Z_EDC_t>,H5Pset_edc_check>; using filter_callback = impl::dxpl_call< impl::dxpl_args<hid_t,H5Z_filter_func_t,void*>,H5Pset_filter_callback>; using data_transform = impl::dxpl_call< impl::dxpl_args<hid_t,const char *>,H5Pset_data_transform>; using hyper_vector_size = impl::dxpl_call< impl::dxpl_args<hid_t,size_t>,H5Pset_hyper_vector_size>; using btree_ratios = impl::dxpl_call< impl::dxpl_args<hid_t,double,double,double>,H5Pset_btree_ratios>; using vlen_mem_manager = impl::dxpl_call< impl::dxpl_args<hid_t,H5MM_allocate_t, void *, H5MM_free_t, void *>,H5Pset_vlen_mem_manager>; // OBJECT CREATION PROPERTY LISTS using ocreate_intermediate_group = impl::ocrl_call< impl::ocrl_args<hid_t,unsigned>,H5Pset_create_intermediate_group>; using obj_track_times = impl::ocrl_call< impl::ocrl_args<hid_t,hbool_t>,H5Pset_obj_track_times>; using attr_phase_change = impl::ocrl_call< impl::ocrl_args<hid_t,unsigned,unsigned>,H5Pset_attr_phase_change>; using attr_creation_order = impl::ocrl_call< impl::ocrl_args<hid_t,unsigned>,H5Pset_attr_creation_order>; const static h5::attr_creation_order crt_order_tracked{H5P_CRT_ORDER_TRACKED}; const static h5::attr_creation_order crt_order_indexed{H5P_CRT_ORDER_INDEXED}; //static h5::ocreate_intermediate_group ocreate_intermediate_group{1}; // OBJECT COPY PROPERTY LISTS using copy_object = impl::ocpl_call< impl::ocpl_args<hid_t,unsigned>,H5Pset_copy_object>; using mcdt_search_cb = impl::ocpl_call< impl::ocpl_args<hid_t,H5O_mcdt_search_cb_t,void*>,H5Pset_mcdt_search_cb>; const static h5::copy_object shallow_hierarchy{H5O_COPY_SHALLOW_HIERARCHY_FLAG}; const static h5::copy_object expand_soft_link{H5O_COPY_EXPAND_SOFT_LINK_FLAG}; const static h5::copy_object expand_ext_link{H5O_COPY_EXPAND_EXT_LINK_FLAG}; const static h5::copy_object expand_reference{H5O_COPY_EXPAND_REFERENCE_FLAG}; const static h5::copy_object copy_without_attr{H5O_COPY_WITHOUT_ATTR_FLAG}; const static h5::copy_object merge_commited_dtype{H5O_COPY_MERGE_COMMITTED_DTYPE_FLAG}; #ifdef H5CPP_HAVE_KITA // follow instructions: https://bitbucket.hdfgroup.org/users/jhenderson/repos/rest-vol/browse using fapl_rest_vol = impl::fapl_call< impl::fapl_args<hid_t>,H5Pset_fapl_rest_vol>; using kita = impl::fapl_call< impl::fapl_args<hid_t>,H5Pset_fapl_rest_vol>; #endif #ifdef H5_HAVE_PARALLEL using fapl_mpiio = impl::fapl_call< impl::fapl_args<hid_t,MPI_Comm, MPI_Info>,H5Pset_fapl_mpio>; using all_coll_metadata_ops = impl::fapl_call< impl::fapl_args<hid_t,hbool_t>,H5Pset_all_coll_metadata_ops>; using coll_metadata_write = impl::fapl_call< impl::fapl_args<hid_t,hbool_t>,H5Pset_coll_metadata_write>; using gc_references = impl::fapl_call< impl::fapl_args<hid_t,unsigned>,H5Pset_gc_references>; using small_data_block_size = impl::fapl_call< impl::fapl_args<hid_t,hsize_t>,H5Pset_small_data_block_size>; using object_flush_cb = impl::fapl_call< impl::fapl_args<hid_t,H5F_flush_cb_t,void*>,H5Pset_object_flush_cb>; using fapl_coll_metadata_ops = impl::fapl_call< impl::fapl_args<hid_t,hbool_t>,H5Pset_all_coll_metadata_ops>; // file using gapl_coll_metadata_ops = impl::gapl_call< impl::gapl_args<hid_t,hbool_t>,H5Pset_all_coll_metadata_ops>; // group using dapl_coll_metadata_ops = impl::gapl_call< impl::dapl_args<hid_t,hbool_t>,H5Pset_all_coll_metadata_ops>; // dataset using tapl_coll_metadata_ops = impl::tapl_call< impl::tapl_args<hid_t,hbool_t>,H5Pset_all_coll_metadata_ops>; // type using lapl_coll_metadata_ops = impl::lapl_call< impl::lapl_args<hid_t,hbool_t>,H5Pset_all_coll_metadata_ops>; // link using aapl_coll_metadata_ops = impl::gapl_call< impl::gapl_args<hid_t,hbool_t>,H5Pset_all_coll_metadata_ops>; // attribute using dxpl_mpiio = impl::dxpl_call< impl::dxpl_args<hid_t,H5FD_mpio_xfer_t>,H5Pset_dxpl_mpio>; using dxpl_mpiio_chunk_opt = impl::dxpl_call< impl::dxpl_args<hid_t,H5FD_mpio_chunk_opt_t>,H5Pset_dxpl_mpio_chunk_opt>; using dxpl_mpiio_chunk_opt_num = impl::dxpl_call< impl::dxpl_args<hid_t,unsigned>,H5Pset_dxpl_mpio_chunk_opt_num>; using dxpl_mpiio_chunk_opt_ratio = impl::dxpl_call< impl::dxpl_args<hid_t,unsigned>,H5Pset_dxpl_mpio_chunk_opt_ratio>; using dxpl_mpiio_collective_opt = impl::dxpl_call< impl::dxpl_args<hid_t,H5FD_mpio_collective_opt_t>,H5Pset_dxpl_mpio_collective_opt>; //TODO; verify * -> ref? using dxpl_mpiio = impl::dxpl_call< impl::dxpl_args<hid_t,H5FD_mpio_xfer_t>,H5Pset_dxpl_mpio>; using mpiio = fapl_mpiio; const static h5::dxpl_mpiio collective{H5FD_MPIO_COLLECTIVE}; const static h5::dxpl_mpiio independent{H5FD_MPIO_INDEPENDENT}; const static h5::dxpl_mpiio_chunk_opt chunk_one_io{H5FD_MPIO_CHUNK_ONE_IO}; const static h5::dxpl_mpiio_chunk_opt chunk_multi_io{H5FD_MPIO_CHUNK_MULTI_IO}; const static h5::dxpl_mpiio_collective_opt collective_io{H5FD_MPIO_COLLECTIVE_IO}; const static h5::dxpl_mpiio_collective_opt individual_io{H5FD_MPIO_INDIVIDUAL_IO}; #endif } namespace h5 { namespace notimplemented_yet { // OBJECT COPY PROPERTY LISTS //using char_encoding_ = = impl::fapl_call< impl::fapl_args<hid_t, >,H5Pset_char_encoding, H5T_cset_t) //static h5::char_encoding_ ascii{H5T_CSET_ASCII}; //static h5::char_encoding_ utf8{H5T_CSET_UTF8}; //FIXME: using fapl_direct = impl::fapl_call< impl::fapl_args<hid_t, >, .. , size_t, size_t, size_t>; //TODO: using vlen_mem_manager,) too complex to implement //TODO: using append_flush -- too complex to implement //NOT MAPPED: fapl_direct, mpiposix, fapl_multi //MISSING: H5CPP__PROPERTYLIST_FLAG(fapl, fapl_windows) //MISSING: using file_image_callbacks, H5_file_image_callbacks_t* >; }} namespace h5 { const static h5::acpl_t acpl = static_cast<h5::acpl_t>( H5P_DEFAULT ); const static h5::dcpl_t dcpl = static_cast<h5::dcpl_t>( H5P_DEFAULT ); const static h5::dxpl_t dxpl = static_cast<h5::dxpl_t>( H5P_DEFAULT ); const static h5::lcpl_t lcpl = h5::char_encoding{H5T_CSET_UTF8} | h5::create_intermediate_group{1}; const static h5::fapl_t fapl = static_cast<h5::fapl_t>( H5P_DEFAULT ); const static h5::fcpl_t fcpl = static_cast<h5::fcpl_t>( H5P_DEFAULT ); const static h5::acpl_t default_acpl = static_cast<h5::acpl_t>( H5P_DEFAULT ); const static h5::dcpl_t default_dcpl = static_cast<h5::dcpl_t>( H5P_DEFAULT ); const static h5::dxpl_t default_dxpl = static_cast<h5::dxpl_t>( H5P_DEFAULT ); const static h5::lcpl_t default_lcpl = h5::char_encoding{H5T_CSET_UTF8} | h5::create_intermediate_group{1}; const static h5::fapl_t default_fapl = static_cast<h5::fapl_t>( H5P_DEFAULT ); const static h5::fcpl_t default_fcpl = static_cast<h5::fcpl_t>( H5P_DEFAULT ); } #endif
58.044444
174
0.748979
[ "object" ]
33a05190af69bbc17523f19f574a7d1892138379
4,038
cpp
C++
src/navigation_function/SphereWorldNavigationFunction.cpp
licaili193/roboflow
994b2515049c67e0ea573fd33c1004a89cf5c26e
[ "MIT" ]
null
null
null
src/navigation_function/SphereWorldNavigationFunction.cpp
licaili193/roboflow
994b2515049c67e0ea573fd33c1004a89cf5c26e
[ "MIT" ]
null
null
null
src/navigation_function/SphereWorldNavigationFunction.cpp
licaili193/roboflow
994b2515049c67e0ea573fd33c1004a89cf5c26e
[ "MIT" ]
null
null
null
// The MIT License (MIT) // Copyright (c) 2019 Caili Li // 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. /* code */ #include "SphereWorldNavigationFunction.hpp" namespace roboflow { namespace navigation_function { void SphereWorldNavigationFunction::setKappa(double kappa) { kappa_ = kappa; } double SphereWorldNavigationFunction::getKappa() const { return kappa_; } void SphereWorldNavigationFunction::setZerothObstacle(std::shared_ptr<math::Sphere> obj) { zeroth_obstacle_ = obj; } bool SphereWorldNavigationFunction::setObstacle(std::shared_ptr<math::Sphere> obj) { if (!obj) return false; uint64_t id = obj->getId(); auto res = obstacles_.insert(std::make_pair(id, obj)); return res.second; } bool SphereWorldNavigationFunction::eraseObstacle(uint64_t id) { return static_cast<bool>(obstacles_.erase(id)); } void SphereWorldNavigationFunction::setDestination(std::shared_ptr<math::ScalarObject> dest, DestinationFunctionType type) { destination_ = dest; d_type_ = type; } void SphereWorldNavigationFunction::clear() { obstacles_.clear(); zeroth_obstacle_.reset(); destination_.reset(); kappa_ = 1.0; } std::pair<double, bool> SphereWorldNavigationFunction::evaluate(Eigen::Vector2d p) { double J = 0; if (auto t = destination_.lock()) J = t->evaluate(p); else return std::make_pair(1, false); // TODO: log here double beta = 1.0; if (auto t = zeroth_obstacle_.lock()) { double tmp = t->evaluate(p); if (tmp > 0) return std::make_pair(1, false); // TODO: log here else beta *= std::fabs(tmp); } else { // TODO: log here return std::make_pair(1, false); } for (auto pr : obstacles_) { auto o = pr.second; if (auto t = o.lock()) { double tmp = t->evaluate(p); if (tmp < 0) return std::make_pair(1, false); // TODO: log here else beta *= tmp; } else { // eraseObstacle(pr.first); // TODO: log here } } double res = J / std::pow(std::pow(J, kappa_) + beta, 1.0 / kappa_); return std::make_pair(res, true); } std::pair<double, bool> SphereWorldNavigationFunction::evaluate(double x, double y) { return evaluate({x, y}); } std::vector<std::shared_ptr<math::StarObject>> SphereWorldNavigationFunction::getObstacles() const { std::vector<std::shared_ptr<math::StarObject>> res; res.push_back(zeroth_obstacle_.lock()); for (auto p : obstacles_) { res.push_back(p.second.lock()); } return res; } std::pair<std::shared_ptr<math::ScalarObject>, DestinationFunctionType> SphereWorldNavigationFunction::getDestinationFunction() const { return std::make_pair(destination_.lock(), d_type_); } } // namespace navigation_function } // namespace roboflow
28.237762
98
0.659733
[ "vector" ]
33a09c499246d123d43fea36ef1e0c0faa841236
2,848
cc
C++
paddle/utils/array_ref_test.cc
Li-fAngyU/Paddle
e548f65f96697830035a28f9070b40829408ccdb
[ "Apache-2.0" ]
2
2022-03-30T09:55:45.000Z
2022-03-30T09:55:49.000Z
paddle/utils/array_ref_test.cc
Li-fAngyU/Paddle
e548f65f96697830035a28f9070b40829408ccdb
[ "Apache-2.0" ]
1
2022-01-28T07:23:22.000Z
2022-01-28T07:23:22.000Z
paddle/utils/array_ref_test.cc
Li-fAngyU/Paddle
e548f65f96697830035a28f9070b40829408ccdb
[ "Apache-2.0" ]
1
2022-03-02T11:36:03.000Z
2022-03-02T11:36:03.000Z
// Copyright (c) 2022 PaddlePaddle Authors. 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 "paddle/utils/array_ref.h" #include <cstdlib> #include <ctime> #include "glog/logging.h" #include "gtest/gtest.h" TEST(array_ref, array_ref) { paddle::ArrayRef<int> a; CHECK_EQ(a.size(), size_t(0)); CHECK_EQ(a.data(), static_cast<int*>(nullptr)); paddle::ArrayRef<int> b(paddle::none); CHECK_EQ(b.size(), size_t(0)); CHECK_EQ(b.data(), static_cast<int*>(nullptr)); int v = 1; paddle::ArrayRef<int> c(v); CHECK_EQ(c.size(), size_t(1)); CHECK_EQ(c.data(), &v); CHECK_EQ(c.equals(paddle::makeArrayRef(v)), true); int v1[5] = {1, 2, 3, 4, 5}; paddle::ArrayRef<int> d(v1, 5); CHECK_EQ(d.size(), size_t(5)); CHECK_EQ(d.data(), v1); CHECK_EQ(d.equals(paddle::makeArrayRef(v1, 5)), true); paddle::ArrayRef<int> e(&v1[0], &v1[4]); CHECK_EQ(e.size(), size_t(4)); CHECK_EQ(e.data(), v1); CHECK_EQ(e.equals(paddle::makeArrayRef(&v1[0], &v1[4])), true); paddle::SmallVector<int, 3> small_vector{1, 2, 3}; paddle::ArrayRef<int> f(small_vector); CHECK_EQ(f.size(), size_t(3)); CHECK_EQ(f.data(), small_vector.data()); CHECK_EQ(f.equals(paddle::makeArrayRef(small_vector)), true); std::vector<int> vector{1, 2, 3}; paddle::ArrayRef<int> g(vector); CHECK_EQ(g.size(), size_t(3)); CHECK_EQ(g.data(), vector.data()); CHECK_EQ(g.equals(paddle::makeArrayRef(vector)), true); std::initializer_list<int> list = {1, 2, 3}; paddle::ArrayRef<int> h(list); CHECK_EQ(h.size(), size_t(3)); CHECK_EQ(h.data(), list.begin()); paddle::ArrayRef<int> i(h); CHECK_EQ(i.size(), size_t(3)); CHECK_EQ(i.data(), list.begin()); CHECK_EQ(i.equals(h), true); CHECK_EQ(i.equals(paddle::makeArrayRef(h)), true); auto slice = i.slice(1, 2); CHECK_EQ(slice.size(), size_t(2)); CHECK_EQ(slice[0], 2); CHECK_EQ(slice[1], 3); auto drop = i.drop_front(2); CHECK_EQ(drop.size(), size_t(1)); CHECK_EQ(drop[0], 3); paddle::ArrayRef<int> nums = {1, 2, 3, 4, 5, 6, 7, 8}; auto front = nums.take_front(3); CHECK_EQ(front.size(), size_t(3)); for (size_t i = 0; i < 3; ++i) { CHECK_EQ(front[i], nums[i]); } auto back = nums.take_back(3); CHECK_EQ(back.size(), size_t(3)); for (size_t i = 0; i < 3; ++i) { CHECK_EQ(back[i], nums[i + 5]); } }
30.623656
75
0.653441
[ "vector" ]
33a74441be351e836030735de25080884dd268af
1,428
cc
C++
src/events/MessageCommand.cc
meesokim/openmsx-0.13.0
287033a3fcade297e008a544b715eb3906da3848
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/events/MessageCommand.cc
meesokim/openmsx-0.13.0
287033a3fcade297e008a544b715eb3906da3848
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/events/MessageCommand.cc
meesokim/openmsx-0.13.0
287033a3fcade297e008a544b715eb3906da3848
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#include "MessageCommand.hh" #include "CommandException.hh" #include "CliComm.hh" #include "TclObject.hh" #include "xrange.hh" namespace openmsx { MessageCommand::MessageCommand(CommandController& controller) : Command(controller, "message") { } static CliComm::LogLevel getLevel(string_ref level) { auto levels = CliComm::getLevelStrings(); for (auto i : xrange(levels.size())) { if (level == levels[i]) { return static_cast<CliComm::LogLevel>(i); } } throw CommandException("Unknown level string: " + level); } void MessageCommand::execute(array_ref<TclObject> tokens, TclObject& /*result*/) { CliComm& cliComm = getCliComm(); CliComm::LogLevel level = CliComm::INFO; switch (tokens.size()) { case 3: level = getLevel(tokens[2].getString()); // fall-through case 2: cliComm.log(level, tokens[1].getString()); break; default: throw SyntaxError(); } } std::string MessageCommand::help(const std::vector<std::string>& /*tokens*/) const { return "message <text> [<level>]\n" "Print a message. (By default) this message will be shown in " "a colored box at the top of the screen. It's possible to " "specify a level for the message (e.g. 'info', 'warning' or " "'error')."; } void MessageCommand::tabCompletion(std::vector<std::string>& tokens) const { if (tokens.size() == 3) { completeString(tokens, CliComm::getLevelStrings()); } } } // namespace openmsx
24.62069
82
0.684174
[ "vector" ]
33a8b392a194def0b95ddc046b02e100dd9778a3
4,869
cpp
C++
tests/stress_tests/common/utils.cpp
uikilin100/openvino
afc5191b8c75b1de4adc8cb07c6269b52882ddfe
[ "Apache-2.0" ]
1
2021-12-30T05:47:43.000Z
2021-12-30T05:47:43.000Z
tests/stress_tests/common/utils.cpp
uikilin100/openvino
afc5191b8c75b1de4adc8cb07c6269b52882ddfe
[ "Apache-2.0" ]
42
2020-11-23T08:09:57.000Z
2022-02-21T13:03:34.000Z
tests/stress_tests/common/utils.cpp
v-Golubev/openvino
26936d1fbb025c503ee43fe74593ee9d7862ab15
[ "Apache-2.0" ]
4
2021-04-02T08:48:38.000Z
2021-07-01T06:59:02.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "utils.h" #include <string> #include <string.h> #ifdef _WIN32 #include <windows.h> #include <psapi.h> #include <tlhelp32.h> #else #include <sys/unistd.h> #include <sys/wait.h> #endif std::string OS_PATH_JOIN(std::initializer_list<std::string> list) { if (!list.size()) return ""; std::string res = *list.begin(); for (auto it = list.begin() + 1; it != list.end(); it++) { res += OS_SEP + *it; } return res; } std::string fileNameNoExt(const std::string &filepath) { auto pos = filepath.rfind('.'); if (pos == std::string::npos) return filepath; return filepath.substr(0, pos); } /// Parses number from provided string static int parseLine(std::string line) { std::string res = ""; for (auto c: line) if (isdigit(c)) res += c; if (res.empty()) // If number wasn't found return -1 return -1; return std::stoi(res); } #ifdef _WIN32 static PROCESS_MEMORY_COUNTERS getMemoryInfo() { static PROCESS_MEMORY_COUNTERS pmc; pmc.cb = sizeof(PROCESS_MEMORY_COUNTERS); GetProcessMemoryInfo(GetCurrentProcess(),&pmc, pmc.cb); return pmc; } size_t getVmSizeInKB() { return getMemoryInfo().PagefileUsage / 1024; } size_t getVmPeakInKB() { return getMemoryInfo().PeakPagefileUsage / 1024; } size_t getVmRSSInKB() { return getMemoryInfo().WorkingSetSize / 1024; } size_t getVmHWMInKB() { return getMemoryInfo().PeakWorkingSetSize / 1024; } size_t getThreadsNum() { // first determine the id of the current process DWORD const id = GetCurrentProcessId(); // then get a process list snapshot. HANDLE const snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPALL, 0 ); // initialize the process entry structure. PROCESSENTRY32 entry = { 0 }; entry.dwSize = sizeof( entry ); // get the first process info. BOOL ret = true; ret = Process32First( snapshot, &entry ); while( ret && entry.th32ProcessID != id ) { ret = Process32Next( snapshot, &entry ); } CloseHandle( snapshot ); return ret ? entry.cntThreads : -1; } #else size_t getSystemDataByName(char *name){ FILE* file = fopen("/proc/self/status", "r"); size_t result = 0; if (file != nullptr) { char line[128]; while (fgets(line, 128, file) != NULL) { if (strncmp(line, name, strlen(name)) == 0) { result = parseLine(line); break; } } fclose(file); } return result; } size_t getVmSizeInKB() {return getSystemDataByName((char*) "VmSize:");} size_t getVmPeakInKB() {return getSystemDataByName((char*) "VmPeak:");} size_t getVmRSSInKB() {return getSystemDataByName((char*) "VmRSS:");} size_t getVmHWMInKB() {return getSystemDataByName((char*) "VmHWM:");} size_t getThreadsNum() {return getSystemDataByName((char*) "Threads:");} #endif int run_in_processes(const int &numprocesses, const std::function<void()> &function) { #ifdef _WIN32 // TODO: implement run in separate process by using WinAPI function; return 0; #else std::vector<pid_t> child_pids(numprocesses); for (int i = 0; i < numprocesses; i++) { child_pids[i] = fork(); if (child_pids[i] == 0) { function; exit(EXIT_SUCCESS); } } int status = 0; for (int i = 0; i < numprocesses; i++) { int _status = 0; waitpid(child_pids[i], &_status, WSTOPPED); if (_status) { log_err("Process run # " << i << " failed with exitcode " << _status); status = _status; } } return status; #endif } void auto_expand_env_vars(std::string &input) { const static std::string pattern1 = "${", pattern2 = "}"; size_t pattern1_pos, pattern2_pos, envvar_start_pos, envvar_finish_pos; while ((pattern1_pos = input.find(pattern1)) != std::string::npos) { envvar_start_pos = pattern1_pos + pattern1.length(); if ((pattern2_pos = input.find(pattern2)) != std::string::npos) { envvar_finish_pos = pattern2_pos - pattern2.length(); const std::string envvar_name = input.substr(envvar_start_pos, envvar_finish_pos - envvar_start_pos + 1); const char *envvar_val = getenv(envvar_name.c_str()); if (envvar_val == NULL) throw std::logic_error("Expected environment variable " + envvar_name + " is not set."); const std::string envvar_val_s(envvar_val); input.replace(pattern1_pos, pattern2_pos - pattern1_pos + 1, envvar_val_s); } } } std::string expand_env_vars(const std::string &input) { std::string _input = input; auto_expand_env_vars(_input); return _input; }
28.30814
117
0.623126
[ "vector" ]
33afc1a7e799de07430de8e3e674ce9c574cc6c5
1,277
cc
C++
decoder/ff_charset.cc
agesmundo/FasterCubePruning
f80150140b5273fd1eb0dfb34bdd789c4cbd35e6
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
1
2019-06-03T00:44:01.000Z
2019-06-03T00:44:01.000Z
decoder/ff_charset.cc
jhclark/cdec
237ddc67ffa61da310e19710f902d4771dc323c2
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
null
null
null
decoder/ff_charset.cc
jhclark/cdec
237ddc67ffa61da310e19710f902d4771dc323c2
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
1
2021-02-19T12:44:54.000Z
2021-02-19T12:44:54.000Z
#include "ff_charset.h" #include "fdict.h" #include "stringlib.h" using namespace std; NonLatinCount::NonLatinCount(const string& param) : FeatureFunction(), fid_(FD::Convert("NonLatinCount")) {} bool ContainsNonLatin(const char* word) { int cur = 0; while(word[cur]) { const int size = UTF8Len(word[cur]); if (size > 1) return true; cur += size; } return false; } void NonLatinCount::TraversalFeaturesImpl(const SentenceMetadata& smeta, const Hypergraph::Edge& edge, const std::vector<const void*>& ant_contexts, FeatureVector* features, FeatureVector* estimated_features, void* context) const { const vector<WordID>& e = edge.rule_->e(); int count = 0; for (int i = 0; i < e.size(); ++i) { if (e[i] > 0) { map<WordID, bool>::iterator it = is_non_latin_.find(e[i]); if (it == is_non_latin_.end()) { if ((is_non_latin_[e[i]] = ContainsNonLatin(TD::Convert(e[i])))) ++count; } else { if (it->second) ++count; } } } if (count) features->set_value(fid_, count); }
29.697674
108
0.52545
[ "vector" ]
33b38daff39182180c322973099b8acb5fb69d55
8,042
cpp
C++
cpp/getting_started/parallel_accel/src/main.cpp
TonyWu1973/SDSoC_Examples
368305ee44f0610cf97328f4feadb3750a96ae68
[ "BSD-3-Clause" ]
1
2018-10-24T18:46:36.000Z
2018-10-24T18:46:36.000Z
cpp/getting_started/parallel_accel/src/main.cpp
TonyWu1973/SDSoC_Examples
368305ee44f0610cf97328f4feadb3750a96ae68
[ "BSD-3-Clause" ]
null
null
null
cpp/getting_started/parallel_accel/src/main.cpp
TonyWu1973/SDSoC_Examples
368305ee44f0610cf97328f4feadb3750a96ae68
[ "BSD-3-Clause" ]
null
null
null
/********** Copyright (c) 2018, Xilinx, Inc. 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. **********/ /******************************************************************************* This is an example which showcases effectiveness of direct connection which helps in achieving increasing system parallelism and concurrency. *******************************************************************************/ #include <iostream> #include <cstring> #include <stdlib.h> #include "vadd_vmul.h" #include "sds_utils.h" // Software implementation of Vector Multiplication, the inputs // are of the size TEST_DATA_SIZE void vmul_softwareGold( int *in1, //Input Matrix 1 int *in2, //Input Matrix 2 int *out, //Output Matrix int dim ) { //Perform vector multiply out = in1 x in2 for(int i = 0; i < dim; i++) { out[i] = in1[i] * in2[i]; } } // Software implementation of Vector Addition, the inputs // are of the size TEST_DATA_SIZE void vadd_softwareGold( int *in1, //Input Matrix 1 int *in2, //Input Matrix 2 int *out, //Output Matrix int dim ) { //Perform vector addition Out = in1 + in2 for(int i = 0; i < dim; i++) { out[i] = in1[i] + in2[i]; } } int main(int argc, char** argv) { // Size of the vector size_t vector_size_bytes = sizeof(int) * TEST_DATA_SIZE; // Allocate buffers using sds_alloc int *source_in1 = (int *) sds_alloc(vector_size_bytes); int *source_in2 = (int *) sds_alloc(vector_size_bytes); int *source_vadd_hw_results = (int *) sds_alloc(vector_size_bytes); int *source_vmul_hw_results = (int *) sds_alloc(vector_size_bytes); // Allocate software output buffer int *source_vadd_sw_results = (int *) malloc(vector_size_bytes); int *source_vmul_sw_results = (int *) malloc(vector_size_bytes); // Check for failed memory allocation if((source_in1 == NULL) || (source_in2 == NULL) || (source_vadd_hw_results == NULL) || (source_vmul_hw_results == NULL) || (source_vadd_sw_results == NULL) || (source_vmul_sw_results == NULL)){ std::cout << "TEST FAILED : Failed to allocate memory" << std::endl; return -1; } int size = TEST_DATA_SIZE; sds_utils::perf_counter seq_hw_ctr, par_hw_ctr; bool match = true; // Create the test data for(int i = 0 ; i < TEST_DATA_SIZE; i++){ source_in1[i] = rand(); source_in2[i] = rand(); source_vadd_sw_results[i] = 0; source_vmul_sw_results[i] = 0; source_vadd_hw_results[i] = 0; source_vmul_hw_results[i] = 0; } //Two hw functions are called back to back. First the //vadd_accel is executed, then vmul_accel is executed. //The execution of both accelerators is sequential here. //To prevent automatic dataflow between calls to the two //hw functions, async and wait pragma is used here so as //to ensure that the two hw functions will be running sequentially. seq_hw_ctr.start(); // Launch Hardware Solution for(int itr = 0; itr < MAX_NUM_TIMES; itr++) { #pragma SDS async(1) vadd_accel(source_in1, source_in2, source_vadd_hw_results, size); #pragma SDS wait(1) #pragma SDS async(2) vmul_accel(source_in1, source_in2, source_vmul_hw_results, size); #pragma SDS wait(2) } seq_hw_ctr.stop(); //Two hw functions are called back to back. //The program running on the hardware first transfers in1 and in2 //to the vadd_accel hardware and returns immediately. Then the program //transfers in1 and in2 to the vmul_accel hardware and returns //immediately. When the program later executes to the point of //#pragma SDS wait(id), it waits for the particular output to be ready. par_hw_ctr.start(); // Launch Hardware Solution #pragma SDS async(1) vadd_accel(source_in1, source_in2, source_vadd_hw_results, size); #pragma SDS async(2) vmul_accel(source_in1, source_in2, source_vmul_hw_results, size); for(int itr = 0; itr < MAX_NUM_TIMES; itr++) { #pragma SDS wait(1) #pragma SDS async(1) vadd_accel(source_in1, source_in2, source_vadd_hw_results, size); #pragma SDS wait(2) #pragma SDS async(2) vmul_accel(source_in1, source_in2, source_vmul_hw_results, size); } #pragma SDS wait(1) #pragma SDS wait(2) par_hw_ctr.stop(); // Launch Software Solution vadd_softwareGold(source_in1, source_in2, source_vadd_sw_results, size); vmul_softwareGold(source_in1, source_in2, source_vmul_sw_results, size); // Compare the results for(int i = 0 ; i < TEST_DATA_SIZE; i++){ if(source_vadd_hw_results[i] != source_vadd_sw_results[i]){ std::cout << "Error: Result mismatch in vadd" << std::endl; std::cout << "i = " << i << " CPU result = " << source_vadd_sw_results[i] << " Hardware result = " << source_vadd_hw_results[i] << std::endl; match = false; break; } if(source_vmul_hw_results[i] != source_vmul_sw_results[i]){ std::cout << "Error: Result mismatch in vmul" << std::endl; std::cout << "i = " << i << " CPU result = " << source_vmul_sw_results[i] << " Hardware result = " << source_vmul_hw_results[i] << std::endl; match = false; break; } } uint64_t seq_hw_cycles = seq_hw_ctr.avg_cpu_cycles(); uint64_t par_hw_cycles = par_hw_ctr.avg_cpu_cycles(); double par_speedup = (double) seq_hw_cycles / (double) par_hw_cycles; std::cout << "Number of average CPU cycles running application sequentially in hardware: " << seq_hw_cycles << std::endl; std::cout << "Number of average CPU cycles running application parallel in hardware: " << par_hw_cycles << std::endl; std::cout << "Parallel speed up compare to sequential execution is: " << par_speedup << std::endl; std::cout << "Note: Speed up is meaningful for real hardware execution only, not for emulation." << std::endl; // Release memory sds_free(source_in1); sds_free(source_in2); sds_free(source_vadd_hw_results); sds_free(source_vmul_hw_results); free(source_vadd_sw_results); free(source_vmul_sw_results); std::cout << "TEST " << ((match) ? "PASSED" : "FAILED") << std::endl; return (match ? 0 : 1); }
40.21
114
0.648346
[ "vector" ]
33b65efdff7dd37502d12099b712fa1aafc27311
286,269
cpp
C++
modules/gdscript/gdscript_parser.cpp
filipworksdev/goblin-test
c2a251fc66e43f7e74327cbec73b1d1fc5aa4b1d
[ "MIT", "Apache-2.0", "Unlicense" ]
9
2022-02-07T09:53:17.000Z
2022-03-31T17:50:38.000Z
modules/gdscript/gdscript_parser.cpp
filipworksdev/goblin-test
c2a251fc66e43f7e74327cbec73b1d1fc5aa4b1d
[ "MIT", "Apache-2.0", "Unlicense" ]
null
null
null
modules/gdscript/gdscript_parser.cpp
filipworksdev/goblin-test
c2a251fc66e43f7e74327cbec73b1d1fc5aa4b1d
[ "MIT", "Apache-2.0", "Unlicense" ]
6
2021-11-27T17:31:06.000Z
2022-03-26T02:22:11.000Z
/*************************************************************************/ /* gdscript_parser.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gdscript_parser.h" #include "core/core_string_names.h" #include "core/engine.h" #include "core/io/resource_loader.h" #include "core/os/file_access.h" #include "core/print_string.h" #include "core/project_settings.h" #include "core/reference.h" #include "core/script_language.h" #include "gdscript.h" template <class T> T *GDScriptParser::alloc_node() { T *t = memnew(T); t->next = list; list = t; if (!head) { head = t; } t->line = tokenizer->get_token_line(); t->column = tokenizer->get_token_column(); return t; } #ifdef DEBUG_ENABLED static String _find_function_name(const GDScriptParser::OperatorNode *p_call); #endif // DEBUG_ENABLED bool GDScriptParser::_end_statement() { if (tokenizer->get_token() == GDScriptTokenizer::TK_SEMICOLON) { tokenizer->advance(); return true; //handle next } else if (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE || tokenizer->get_token() == GDScriptTokenizer::TK_EOF) { return true; //will be handled properly } return false; } void GDScriptParser::_set_end_statement_error(String p_name) { String error_msg; if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER) { error_msg = vformat("Expected end of statement (\"%s\"), got %s (\"%s\") instead.", p_name, tokenizer->get_token_name(tokenizer->get_token()), tokenizer->get_token_identifier()); } else { error_msg = vformat("Expected end of statement (\"%s\"), got %s instead.", p_name, tokenizer->get_token_name(tokenizer->get_token())); } _set_error(error_msg); } bool GDScriptParser::_enter_indent_block(BlockNode *p_block) { if (tokenizer->get_token() != GDScriptTokenizer::TK_COLON) { // report location at the previous token (on the previous line) int error_line = tokenizer->get_token_line(-1); int error_column = tokenizer->get_token_column(-1); _set_error("':' expected at end of line.", error_line, error_column); return false; } tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_EOF) { return false; } if (tokenizer->get_token() != GDScriptTokenizer::TK_NEWLINE) { // be more python-like IndentLevel current_level = indent_level.back()->get(); indent_level.push_back(current_level); return true; //_set_error("newline expected after ':'."); //return false; } while (true) { if (tokenizer->get_token() != GDScriptTokenizer::TK_NEWLINE) { return false; //wtf } else if (tokenizer->get_token(1) == GDScriptTokenizer::TK_EOF) { return false; } else if (tokenizer->get_token(1) != GDScriptTokenizer::TK_NEWLINE) { int indent = tokenizer->get_token_line_indent(); int tabs = tokenizer->get_token_line_tab_indent(); IndentLevel current_level = indent_level.back()->get(); IndentLevel new_indent(indent, tabs); if (new_indent.is_mixed(current_level)) { _set_error("Mixed tabs and spaces in indentation."); return false; } if (indent <= current_level.indent) { return false; } indent_level.push_back(new_indent); tokenizer->advance(); return true; } else if (p_block) { NewLineNode *nl = alloc_node<NewLineNode>(); nl->line = tokenizer->get_token_line(); p_block->statements.push_back(nl); } tokenizer->advance(); // go to next newline } } bool GDScriptParser::_parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete, bool p_parsing_constant) { if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { tokenizer->advance(); } else { parenthesis++; int argidx = 0; while (true) { if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) { _make_completable_call(argidx); completion_node = p_parent; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING && tokenizer->get_token(1) == GDScriptTokenizer::TK_CURSOR) { //completing a string argument.. completion_cursor = tokenizer->get_token_constant(); _make_completable_call(argidx); completion_node = p_parent; tokenizer->advance(1); return false; } Node *arg = _parse_expression(p_parent, p_static, false, p_parsing_constant); if (!arg) { return false; } p_args.push_back(arg); if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { tokenizer->advance(); break; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { if (tokenizer->get_token(1) == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expression expected"); return false; } tokenizer->advance(); argidx++; } else { // something is broken _set_error("Expected ',' or ')'"); return false; } } parenthesis--; } return true; } void GDScriptParser::_make_completable_call(int p_arg) { completion_cursor = StringName(); completion_type = COMPLETION_CALL_ARGUMENTS; completion_class = current_class; completion_function = current_function; completion_line = tokenizer->get_token_line(); completion_argument = p_arg; completion_block = current_block; completion_found = true; tokenizer->advance(); } bool GDScriptParser::_get_completable_identifier(CompletionType p_type, StringName &identifier) { identifier = StringName(); if (tokenizer->is_token_literal()) { identifier = tokenizer->get_token_literal(); tokenizer->advance(); } if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) { completion_cursor = identifier; completion_type = p_type; completion_class = current_class; completion_function = current_function; completion_line = tokenizer->get_token_line(); completion_block = current_block; completion_found = true; completion_ident_is_call = false; tokenizer->advance(); if (tokenizer->is_token_literal()) { identifier = identifier.operator String() + tokenizer->get_token_literal().operator String(); tokenizer->advance(); } if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_OPEN) { completion_ident_is_call = true; } return true; } return false; } GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_static, bool p_allow_assign, bool p_parsing_constant) { //Vector<Node*> expressions; //Vector<OperatorNode::Operator> operators; Vector<Expression> expression; Node *expr = nullptr; int op_line = tokenizer->get_token_line(); // when operators are created at the bottom, the line might have been changed (\n found) while (true) { /*****************/ /* Parse Operand */ /*****************/ if (parenthesis > 0) { //remove empty space (only allowed if inside parenthesis while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) { tokenizer->advance(); } } // Check that the next token is not TK_CURSOR and if it is, the offset should be incremented. int next_valid_offset = 1; if (tokenizer->get_token(next_valid_offset) == GDScriptTokenizer::TK_CURSOR) { next_valid_offset++; // There is a chunk of the identifier that also needs to be ignored (not always there!) if (tokenizer->get_token(next_valid_offset) == GDScriptTokenizer::TK_IDENTIFIER) { next_valid_offset++; } } if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_OPEN) { //subexpression () tokenizer->advance(); parenthesis++; Node *subexpr = _parse_expression(p_parent, p_static, p_allow_assign, p_parsing_constant); parenthesis--; if (!subexpr) { return nullptr; } if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' in expression"); return nullptr; } tokenizer->advance(); expr = subexpr; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_DOLLAR) { tokenizer->advance(); String path; bool need_identifier = true; bool done = false; int line = tokenizer->get_token_line(); while (!done) { switch (tokenizer->get_token()) { case GDScriptTokenizer::TK_CURSOR: { completion_type = COMPLETION_GET_NODE; completion_class = current_class; completion_function = current_function; completion_line = tokenizer->get_token_line(); completion_cursor = path; completion_argument = 0; completion_block = current_block; completion_found = true; tokenizer->advance(); } break; case GDScriptTokenizer::TK_CONSTANT: { if (!need_identifier) { done = true; break; } if (tokenizer->get_token_constant().get_type() != Variant::STRING) { _set_error("Expected string constant or identifier after '$' or '/'."); return nullptr; } path += String(tokenizer->get_token_constant()); tokenizer->advance(); need_identifier = false; } break; case GDScriptTokenizer::TK_OP_DIV: { if (need_identifier) { done = true; break; } path += "/"; tokenizer->advance(); need_identifier = true; } break; default: { // Instead of checking for TK_IDENTIFIER, we check with is_token_literal, as this allows us to use match/sync/etc. as a name if (need_identifier && tokenizer->is_token_literal()) { path += String(tokenizer->get_token_literal()); tokenizer->advance(); need_identifier = false; } else { done = true; } break; } } } if (path == "") { _set_error("Path expected after $."); return nullptr; } OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_CALL; op->line = line; op->arguments.push_back(alloc_node<SelfNode>()); op->arguments[0]->line = line; IdentifierNode *funcname = alloc_node<IdentifierNode>(); funcname->name = "get_node"; funcname->line = line; op->arguments.push_back(funcname); ConstantNode *nodepath = alloc_node<ConstantNode>(); nodepath->value = NodePath(StringName(path)); nodepath->datatype = _type_from_variant(nodepath->value); nodepath->line = line; op->arguments.push_back(nodepath); expr = op; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) { tokenizer->advance(); continue; //no point in cursor in the middle of expression } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT) { //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = tokenizer->get_token_constant(); constant->datatype = _type_from_variant(constant->value); tokenizer->advance(); expr = constant; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONST_PI) { //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = Math_PI; constant->datatype = _type_from_variant(constant->value); tokenizer->advance(); expr = constant; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONST_TAU) { //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = Math_TAU; constant->datatype = _type_from_variant(constant->value); tokenizer->advance(); expr = constant; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONST_INF) { //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = Math_INF; constant->datatype = _type_from_variant(constant->value); tokenizer->advance(); expr = constant; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONST_NAN) { //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = Math_NAN; constant->datatype = _type_from_variant(constant->value); tokenizer->advance(); expr = constant; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_PRELOAD) { //constant defined by tokenizer tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after 'preload'"); return nullptr; } tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) { completion_cursor = StringName(); completion_node = p_parent; completion_type = COMPLETION_RESOURCE_PATH; completion_class = current_class; completion_function = current_function; completion_line = tokenizer->get_token_line(); completion_block = current_block; completion_argument = 0; completion_found = true; tokenizer->advance(); } String path; bool found_constant = false; bool valid = false; ConstantNode *cn; parenthesis++; Node *subexpr = _parse_and_reduce_expression(p_parent, p_static); parenthesis--; if (subexpr) { if (subexpr->type == Node::TYPE_CONSTANT) { cn = static_cast<ConstantNode *>(subexpr); found_constant = true; } if (subexpr->type == Node::TYPE_IDENTIFIER) { IdentifierNode *in = static_cast<IdentifierNode *>(subexpr); // Try to find the constant expression by the identifier if (current_class->constant_expressions.has(in->name)) { Node *cn_exp = current_class->constant_expressions[in->name].expression; if (cn_exp->type == Node::TYPE_CONSTANT) { cn = static_cast<ConstantNode *>(cn_exp); found_constant = true; } } } if (found_constant && cn->value.get_type() == Variant::STRING) { valid = true; path = (String)cn->value; } } if (!valid) { _set_error("expected string constant as 'preload' argument."); return nullptr; } if (!path.is_abs_path() && base_path != "") { path = base_path.plus_file(path); } path = path.replace("///", "//").simplify_path(); if (path == self_path) { _set_error("Can't preload itself (use 'get_script()')."); return nullptr; } Ref<Resource> res; dependencies.push_back(path); if (!dependencies_only) { if (!validating) { //this can be too slow for just validating code if (for_completion && ScriptCodeCompletionCache::get_singleton() && FileAccess::exists(path)) { res = ScriptCodeCompletionCache::get_singleton()->get_cached_resource(path); } else if (!for_completion || FileAccess::exists(path)) { res = ResourceLoader::load(path); } } else { if (!FileAccess::exists(path)) { _set_error("Can't preload resource at path: " + path); return nullptr; } else if (ScriptCodeCompletionCache::get_singleton()) { res = ScriptCodeCompletionCache::get_singleton()->get_cached_resource(path); } } if (!res.is_valid()) { _set_error("Can't preload resource at path: " + path); return nullptr; } } if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' after 'preload' path"); return nullptr; } Ref<GDScript> gds = res; if (gds.is_valid() && !gds->is_valid()) { _set_error("Couldn't fully preload the script, possible cyclic reference or compilation error. Use \"load()\" instead if a cyclic reference is intended."); return nullptr; } tokenizer->advance(); ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = res; constant->datatype = _type_from_variant(constant->value); expr = constant; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_YIELD) { if (!current_function) { _set_error("\"yield()\" can only be used inside function blocks."); return nullptr; } current_function->has_yield = true; tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) { _set_error("Expected \"(\" after \"yield\"."); return nullptr; } tokenizer->advance(); OperatorNode *yield = alloc_node<OperatorNode>(); yield->op = OperatorNode::OP_YIELD; while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) { tokenizer->advance(); } if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { expr = yield; tokenizer->advance(); } else { parenthesis++; Node *object = _parse_and_reduce_expression(p_parent, p_static); if (!object) { return nullptr; } yield->arguments.push_back(object); if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { _set_error("Expected \",\" after the first argument of \"yield\"."); return nullptr; } tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) { completion_cursor = StringName(); completion_node = object; completion_type = COMPLETION_YIELD; completion_class = current_class; completion_function = current_function; completion_line = tokenizer->get_token_line(); completion_argument = 0; completion_block = current_block; completion_found = true; tokenizer->advance(); } Node *signal = _parse_and_reduce_expression(p_parent, p_static); if (!signal) { return nullptr; } yield->arguments.push_back(signal); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected \")\" after the second argument of \"yield\"."); return nullptr; } parenthesis--; tokenizer->advance(); expr = yield; } } else if (tokenizer->get_token() == GDScriptTokenizer::TK_SELF) { if (p_static) { _set_error("\"self\" isn't allowed in a static function or constant expression."); return nullptr; } //constant defined by tokenizer SelfNode *self = alloc_node<SelfNode>(); tokenizer->advance(); expr = self; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token(1) == GDScriptTokenizer::TK_PERIOD) { Variant::Type bi_type = tokenizer->get_token_type(); tokenizer->advance(2); StringName identifier; if (_get_completable_identifier(COMPLETION_BUILT_IN_TYPE_CONSTANT, identifier)) { completion_built_in_constant = bi_type; } if (identifier == StringName()) { _set_error("Built-in type constant or static function expected after \".\"."); return nullptr; } if (!Variant::has_constant(bi_type, identifier)) { if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_OPEN && Variant::is_method_const(bi_type, identifier) && Variant::get_method_return_type(bi_type, identifier) == bi_type) { tokenizer->advance(); OperatorNode *construct = alloc_node<OperatorNode>(); construct->op = OperatorNode::OP_CALL; TypeNode *tn = alloc_node<TypeNode>(); tn->vtype = bi_type; construct->arguments.push_back(tn); OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_CALL; op->arguments.push_back(construct); IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = identifier; op->arguments.push_back(id); if (!_parse_arguments(op, op->arguments, p_static, true, p_parsing_constant)) { return nullptr; } expr = op; } else { // Object is a special case bool valid = false; if (bi_type == Variant::OBJECT) { int object_constant = ClassDB::get_integer_constant("Object", identifier, &valid); if (valid) { ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = object_constant; cn->datatype = _type_from_variant(cn->value); expr = cn; } } if (!valid) { _set_error("Static constant '" + identifier.operator String() + "' not present in built-in type " + Variant::get_type_name(bi_type) + "."); return nullptr; } } } else { ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = Variant::get_constant_value(bi_type, identifier); cn->datatype = _type_from_variant(cn->value); expr = cn; } } else if (tokenizer->get_token(next_valid_offset) == GDScriptTokenizer::TK_PARENTHESIS_OPEN && tokenizer->is_token_literal()) { // We check with is_token_literal, as this allows us to use match/sync/etc. as a name //function or constructor OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_CALL; //Do a quick Array and Dictionary Check. Replace if either require no arguments. bool replaced = false; if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_TYPE) { Variant::Type ct = tokenizer->get_token_type(); if (!p_parsing_constant) { if (ct == Variant::ARRAY) { if (tokenizer->get_token(2) == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { ArrayNode *arr = alloc_node<ArrayNode>(); expr = arr; replaced = true; tokenizer->advance(3); } } if (ct == Variant::DICTIONARY) { if (tokenizer->get_token(2) == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { DictionaryNode *dict = alloc_node<DictionaryNode>(); expr = dict; replaced = true; tokenizer->advance(3); } } } if (!replaced) { TypeNode *tn = alloc_node<TypeNode>(); tn->vtype = tokenizer->get_token_type(); op->arguments.push_back(tn); tokenizer->advance(2); } } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_FUNC) { BuiltInFunctionNode *bn = alloc_node<BuiltInFunctionNode>(); bn->function = tokenizer->get_token_built_in_func(); op->arguments.push_back(bn); tokenizer->advance(2); } else { SelfNode *self = alloc_node<SelfNode>(); op->arguments.push_back(self); StringName identifier; if (_get_completable_identifier(COMPLETION_FUNCTION, identifier)) { } IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = identifier; op->arguments.push_back(id); tokenizer->advance(1); } if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) { _make_completable_call(0); completion_node = op; } if (!replaced) { if (!_parse_arguments(op, op->arguments, p_static, true, p_parsing_constant)) { return nullptr; } expr = op; } } else if (tokenizer->is_token_literal(0, true)) { // We check with is_token_literal, as this allows us to use match/sync/etc. as a name //identifier (reference) const ClassNode *cln = current_class; bool bfn = false; StringName identifier; int id_line = tokenizer->get_token_line(); if (_get_completable_identifier(COMPLETION_IDENTIFIER, identifier)) { } BlockNode *b = current_block; while (!bfn && b) { if (b->variables.has(identifier)) { IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = identifier; id->declared_block = b; id->line = id_line; expr = id; bfn = true; #ifdef DEBUG_ENABLED LocalVarNode *lv = b->variables[identifier]; switch (tokenizer->get_token()) { case GDScriptTokenizer::TK_OP_ASSIGN_ADD: case GDScriptTokenizer::TK_OP_ASSIGN_BIT_AND: case GDScriptTokenizer::TK_OP_ASSIGN_BIT_OR: case GDScriptTokenizer::TK_OP_ASSIGN_BIT_XOR: case GDScriptTokenizer::TK_OP_ASSIGN_DIV: case GDScriptTokenizer::TK_OP_ASSIGN_MOD: case GDScriptTokenizer::TK_OP_ASSIGN_MUL: case GDScriptTokenizer::TK_OP_ASSIGN_SHIFT_LEFT: case GDScriptTokenizer::TK_OP_ASSIGN_SHIFT_RIGHT: case GDScriptTokenizer::TK_OP_ASSIGN_SUB: { if (lv->assignments == 0) { if (!lv->datatype.has_type) { _set_error("Using assignment with operation on a variable that was never assigned."); return nullptr; } _add_warning(GDScriptWarning::UNASSIGNED_VARIABLE_OP_ASSIGN, -1, identifier.operator String()); } FALLTHROUGH; } case GDScriptTokenizer::TK_OP_ASSIGN: { lv->assignments += 1; lv->usages--; // Assignment is not really usage } break; default: { lv->usages++; } } #endif // DEBUG_ENABLED break; } b = b->parent_block; } if (!bfn && p_parsing_constant) { if (cln->constant_expressions.has(identifier)) { expr = cln->constant_expressions[identifier].expression; bfn = true; } else if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) { //check from constants ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = GDScriptLanguage::get_singleton()->get_global_array()[GDScriptLanguage::get_singleton()->get_global_map()[identifier]]; constant->datatype = _type_from_variant(constant->value); constant->line = id_line; expr = constant; bfn = true; } if (!bfn && GDScriptLanguage::get_singleton()->get_named_globals_map().has(identifier)) { //check from singletons ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = GDScriptLanguage::get_singleton()->get_named_globals_map()[identifier]; expr = constant; bfn = true; } if (!dependencies_only) { if (!bfn && ScriptServer::is_global_class(identifier)) { Ref<Script> scr = ResourceLoader::load(ScriptServer::get_global_class_path(identifier)); if (scr.is_valid() && scr->is_valid()) { ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = scr; expr = constant; bfn = true; } } // Check parents for the constant if (!bfn) { // Using current_class instead of cln here, since cln is const* _determine_inheritance(current_class, false); if (cln->base_type.has_type && cln->base_type.kind == DataType::GDSCRIPT && cln->base_type.script_type->is_valid()) { Map<StringName, Variant> parent_constants; current_class->base_type.script_type->get_constants(&parent_constants); if (parent_constants.has(identifier)) { ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = parent_constants[identifier]; expr = constant; bfn = true; } } } } } if (!bfn) { #ifdef DEBUG_ENABLED if (current_function) { int arg_idx = current_function->arguments.find(identifier); if (arg_idx != -1) { switch (tokenizer->get_token()) { case GDScriptTokenizer::TK_OP_ASSIGN_ADD: case GDScriptTokenizer::TK_OP_ASSIGN_BIT_AND: case GDScriptTokenizer::TK_OP_ASSIGN_BIT_OR: case GDScriptTokenizer::TK_OP_ASSIGN_BIT_XOR: case GDScriptTokenizer::TK_OP_ASSIGN_DIV: case GDScriptTokenizer::TK_OP_ASSIGN_MOD: case GDScriptTokenizer::TK_OP_ASSIGN_MUL: case GDScriptTokenizer::TK_OP_ASSIGN_SHIFT_LEFT: case GDScriptTokenizer::TK_OP_ASSIGN_SHIFT_RIGHT: case GDScriptTokenizer::TK_OP_ASSIGN_SUB: case GDScriptTokenizer::TK_OP_ASSIGN: { // Assignment is not really usage } break; default: { current_function->arguments_usage.write[arg_idx] = current_function->arguments_usage[arg_idx] + 1; } } } } #endif // DEBUG_ENABLED IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = identifier; id->line = id_line; expr = id; } } else if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_ADD || tokenizer->get_token() == GDScriptTokenizer::TK_OP_SUB || tokenizer->get_token() == GDScriptTokenizer::TK_OP_NOT || tokenizer->get_token() == GDScriptTokenizer::TK_OP_BIT_INVERT) { //single prefix operators like !expr +expr -expr ++expr --expr alloc_node<OperatorNode>(); Expression e; e.is_op = true; switch (tokenizer->get_token()) { case GDScriptTokenizer::TK_OP_ADD: e.op = OperatorNode::OP_POS; break; case GDScriptTokenizer::TK_OP_SUB: e.op = OperatorNode::OP_NEG; break; case GDScriptTokenizer::TK_OP_NOT: e.op = OperatorNode::OP_NOT; break; case GDScriptTokenizer::TK_OP_BIT_INVERT: e.op = OperatorNode::OP_BIT_INVERT; break; default: { } } tokenizer->advance(); if (e.op != OperatorNode::OP_NOT && tokenizer->get_token() == GDScriptTokenizer::TK_OP_NOT) { _set_error("Misplaced 'not'."); return nullptr; } expression.push_back(e); continue; //only exception, must continue... /* Node *subexpr=_parse_expression(op,p_static); if (!subexpr) return NULL; op->arguments.push_back(subexpr); expr=op;*/ } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_IS && tokenizer->get_token(1) == GDScriptTokenizer::TK_BUILT_IN_TYPE) { // 'is' operator with built-in type if (!expr) { _set_error("Expected identifier before 'is' operator"); return nullptr; } OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_IS_BUILTIN; op->arguments.push_back(expr); tokenizer->advance(); TypeNode *tn = alloc_node<TypeNode>(); tn->vtype = tokenizer->get_token_type(); op->arguments.push_back(tn); tokenizer->advance(); expr = op; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BRACKET_OPEN) { // array tokenizer->advance(); ArrayNode *arr = alloc_node<ArrayNode>(); bool expecting_comma = false; while (true) { if (tokenizer->get_token() == GDScriptTokenizer::TK_EOF) { _set_error("Unterminated array"); return nullptr; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BRACKET_CLOSE) { tokenizer->advance(); break; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) { tokenizer->advance(); //ignore newline } else if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { if (!expecting_comma) { _set_error("expression or ']' expected"); return nullptr; } expecting_comma = false; tokenizer->advance(); //ignore newline } else { //parse expression if (expecting_comma) { _set_error("',' or ']' expected"); return nullptr; } Node *n = _parse_expression(arr, p_static, p_allow_assign, p_parsing_constant); if (!n) { return nullptr; } arr->elements.push_back(n); expecting_comma = true; } } expr = arr; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CURLY_BRACKET_OPEN) { // array tokenizer->advance(); DictionaryNode *dict = alloc_node<DictionaryNode>(); enum DictExpect { DICT_EXPECT_KEY, DICT_EXPECT_COLON, DICT_EXPECT_VALUE, DICT_EXPECT_COMMA }; Node *key = nullptr; Set<Variant> keys; DictExpect expecting = DICT_EXPECT_KEY; while (true) { if (tokenizer->get_token() == GDScriptTokenizer::TK_EOF) { _set_error("Unterminated dictionary"); return nullptr; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CURLY_BRACKET_CLOSE) { if (expecting == DICT_EXPECT_COLON) { _set_error("':' expected"); return nullptr; } if (expecting == DICT_EXPECT_VALUE) { _set_error("value expected"); return nullptr; } tokenizer->advance(); break; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) { tokenizer->advance(); //ignore newline } else if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { if (expecting == DICT_EXPECT_KEY) { _set_error("key or '}' expected"); return nullptr; } if (expecting == DICT_EXPECT_VALUE) { _set_error("value expected"); return nullptr; } if (expecting == DICT_EXPECT_COLON) { _set_error("':' expected"); return nullptr; } expecting = DICT_EXPECT_KEY; tokenizer->advance(); //ignore newline } else if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) { if (expecting == DICT_EXPECT_KEY) { _set_error("key or '}' expected"); return nullptr; } if (expecting == DICT_EXPECT_VALUE) { _set_error("value expected"); return nullptr; } if (expecting == DICT_EXPECT_COMMA) { _set_error("',' or '}' expected"); return nullptr; } expecting = DICT_EXPECT_VALUE; tokenizer->advance(); //ignore newline } else { if (expecting == DICT_EXPECT_COMMA) { _set_error("',' or '}' expected"); return nullptr; } if (expecting == DICT_EXPECT_COLON) { _set_error("':' expected"); return nullptr; } if (expecting == DICT_EXPECT_KEY) { if (tokenizer->is_token_literal() && tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) { // We check with is_token_literal, as this allows us to use match/sync/etc. as a name //lua style identifier, easier to write ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = tokenizer->get_token_literal(); cn->datatype = _type_from_variant(cn->value); key = cn; tokenizer->advance(2); expecting = DICT_EXPECT_VALUE; } else { //python/js style more flexible key = _parse_expression(dict, p_static, p_allow_assign, p_parsing_constant); if (!key) { return nullptr; } expecting = DICT_EXPECT_COLON; } } if (expecting == DICT_EXPECT_VALUE) { Node *value = _parse_expression(dict, p_static, p_allow_assign, p_parsing_constant); if (!value) { return nullptr; } expecting = DICT_EXPECT_COMMA; if (key->type == GDScriptParser::Node::TYPE_CONSTANT) { Variant const &keyName = static_cast<const GDScriptParser::ConstantNode *>(key)->value; if (keys.has(keyName)) { _set_error("Duplicate key found in Dictionary literal"); return nullptr; } keys.insert(keyName); } DictionaryNode::Pair pair; pair.key = key; pair.value = value; dict->elements.push_back(pair); key = nullptr; } } } expr = dict; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD && (tokenizer->is_token_literal(1) || tokenizer->get_token(1) == GDScriptTokenizer::TK_CURSOR)) { // We check with is_token_literal, as this allows us to use match/sync/etc. as a name // parent call tokenizer->advance(); //goto identifier OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_PARENT_CALL; /*SelfNode *self = alloc_node<SelfNode>(); op->arguments.push_back(self); forbidden for now */ StringName identifier; bool is_completion = _get_completable_identifier(COMPLETION_PARENT_FUNCTION, identifier) && for_completion; IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = identifier; op->arguments.push_back(id); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) { if (!is_completion) { _set_error("Expected '(' for parent function call."); return nullptr; } } else { tokenizer->advance(); if (!_parse_arguments(op, op->arguments, p_static, false, p_parsing_constant)) { return nullptr; } } expr = op; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_TYPE && expression.size() > 0 && expression[expression.size() - 1].is_op && expression[expression.size() - 1].op == OperatorNode::OP_IS) { Expression e = expression[expression.size() - 1]; e.op = OperatorNode::OP_IS_BUILTIN; expression.write[expression.size() - 1] = e; TypeNode *tn = alloc_node<TypeNode>(); tn->vtype = tokenizer->get_token_type(); expr = tn; tokenizer->advance(); } else { //find list [ or find dictionary { _set_error("Error parsing expression, misplaced: " + String(tokenizer->get_token_name(tokenizer->get_token()))); return nullptr; //nothing } ERR_FAIL_COND_V_MSG(!expr, nullptr, "GDScriptParser bug, couldn't figure out what expression is."); /******************/ /* Parse Indexing */ /******************/ while (true) { //expressions can be indexed any number of times if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD) { //indexing using "." if (tokenizer->get_token(1) != GDScriptTokenizer::TK_CURSOR && !tokenizer->is_token_literal(1)) { // We check with is_token_literal, as this allows us to use match/sync/etc. as a name _set_error("Expected identifier as member"); return nullptr; } else if (tokenizer->get_token(2) == GDScriptTokenizer::TK_PARENTHESIS_OPEN) { //call!! OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_CALL; tokenizer->advance(); IdentifierNode *id = alloc_node<IdentifierNode>(); StringName identifier; if (_get_completable_identifier(COMPLETION_METHOD, identifier)) { completion_node = op; //indexing stuff } id->name = identifier; op->arguments.push_back(expr); // call what op->arguments.push_back(id); // call func //get arguments tokenizer->advance(1); if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) { _make_completable_call(0); completion_node = op; } if (!_parse_arguments(op, op->arguments, p_static, true, p_parsing_constant)) { return nullptr; } expr = op; } else { //simple indexing! OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_INDEX_NAMED; tokenizer->advance(); StringName identifier; if (_get_completable_identifier(COMPLETION_INDEX, identifier)) { if (identifier == StringName()) { identifier = "@temp"; //so it parses alright } completion_node = op; //indexing stuff } IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = identifier; op->arguments.push_back(expr); op->arguments.push_back(id); expr = op; } } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BRACKET_OPEN) { //indexing using "[]" OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_INDEX; tokenizer->advance(1); parenthesis++; Node *subexpr = _parse_expression(op, p_static, p_allow_assign, p_parsing_constant); parenthesis--; if (!subexpr) { return nullptr; } if (tokenizer->get_token() != GDScriptTokenizer::TK_BRACKET_CLOSE) { _set_error("Expected ']'"); return nullptr; } op->arguments.push_back(expr); op->arguments.push_back(subexpr); tokenizer->advance(1); expr = op; } else { break; } } /*****************/ /* Parse Casting */ /*****************/ bool has_casting = expr->type == Node::TYPE_CAST; if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_AS) { if (has_casting) { _set_error("Unexpected 'as'."); return nullptr; } CastNode *cn = alloc_node<CastNode>(); if (!_parse_type(cn->cast_type)) { _set_error("Expected type after 'as'."); return nullptr; } has_casting = true; cn->source_node = expr; expr = cn; } /******************/ /* Parse Operator */ /******************/ if (parenthesis > 0) { //remove empty space (only allowed if inside parenthesis while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) { tokenizer->advance(); } } Expression e; e.is_op = false; e.node = expr; expression.push_back(e); // determine which operator is next OperatorNode::Operator op; bool valid = true; //assign, if allowed is only allowed on the first operator #define _VALIDATE_ASSIGN \ if (!p_allow_assign || has_casting) { \ _set_error("Unexpected assign."); \ return NULL; \ } \ p_allow_assign = false; switch (tokenizer->get_token()) { //see operator case GDScriptTokenizer::TK_OP_IN: op = OperatorNode::OP_IN; break; case GDScriptTokenizer::TK_OP_EQUAL: op = OperatorNode::OP_EQUAL; break; case GDScriptTokenizer::TK_OP_NOT_EQUAL: op = OperatorNode::OP_NOT_EQUAL; break; case GDScriptTokenizer::TK_OP_LESS: op = OperatorNode::OP_LESS; break; case GDScriptTokenizer::TK_OP_LESS_EQUAL: op = OperatorNode::OP_LESS_EQUAL; break; case GDScriptTokenizer::TK_OP_GREATER: op = OperatorNode::OP_GREATER; break; case GDScriptTokenizer::TK_OP_GREATER_EQUAL: op = OperatorNode::OP_GREATER_EQUAL; break; case GDScriptTokenizer::TK_OP_AND: op = OperatorNode::OP_AND; break; case GDScriptTokenizer::TK_OP_OR: op = OperatorNode::OP_OR; break; case GDScriptTokenizer::TK_OP_ADD: op = OperatorNode::OP_ADD; break; case GDScriptTokenizer::TK_OP_SUB: op = OperatorNode::OP_SUB; break; case GDScriptTokenizer::TK_OP_MUL: op = OperatorNode::OP_MUL; break; case GDScriptTokenizer::TK_OP_DIV: op = OperatorNode::OP_DIV; break; case GDScriptTokenizer::TK_OP_MOD: op = OperatorNode::OP_MOD; break; //case GDScriptTokenizer::TK_OP_NEG: op=OperatorNode::OP_NEG ; break; case GDScriptTokenizer::TK_OP_SHIFT_LEFT: op = OperatorNode::OP_SHIFT_LEFT; break; case GDScriptTokenizer::TK_OP_SHIFT_RIGHT: op = OperatorNode::OP_SHIFT_RIGHT; break; case GDScriptTokenizer::TK_OP_ASSIGN: { _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN; if (tokenizer->get_token(1) == GDScriptTokenizer::TK_CURSOR) { //code complete assignment completion_type = COMPLETION_ASSIGN; completion_node = expr; completion_class = current_class; completion_function = current_function; completion_line = tokenizer->get_token_line(); completion_block = current_block; completion_found = true; tokenizer->advance(); } } break; case GDScriptTokenizer::TK_OP_ASSIGN_ADD: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_ADD; break; case GDScriptTokenizer::TK_OP_ASSIGN_SUB: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SUB; break; case GDScriptTokenizer::TK_OP_ASSIGN_MUL: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_MUL; break; case GDScriptTokenizer::TK_OP_ASSIGN_DIV: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_DIV; break; case GDScriptTokenizer::TK_OP_ASSIGN_MOD: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_MOD; break; case GDScriptTokenizer::TK_OP_ASSIGN_SHIFT_LEFT: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SHIFT_LEFT; break; case GDScriptTokenizer::TK_OP_ASSIGN_SHIFT_RIGHT: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SHIFT_RIGHT; break; case GDScriptTokenizer::TK_OP_ASSIGN_BIT_AND: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_AND; break; case GDScriptTokenizer::TK_OP_ASSIGN_BIT_OR: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_OR; break; case GDScriptTokenizer::TK_OP_ASSIGN_BIT_XOR: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_XOR; break; case GDScriptTokenizer::TK_OP_BIT_AND: op = OperatorNode::OP_BIT_AND; break; case GDScriptTokenizer::TK_OP_BIT_OR: op = OperatorNode::OP_BIT_OR; break; case GDScriptTokenizer::TK_OP_BIT_XOR: op = OperatorNode::OP_BIT_XOR; break; case GDScriptTokenizer::TK_PR_IS: op = OperatorNode::OP_IS; break; case GDScriptTokenizer::TK_CF_IF: op = OperatorNode::OP_TERNARY_IF; break; case GDScriptTokenizer::TK_CF_ELSE: op = OperatorNode::OP_TERNARY_ELSE; break; default: valid = false; break; } if (valid) { e.is_op = true; e.op = op; expression.push_back(e); tokenizer->advance(); } else { break; } } /* Reduce the set set of expressions and place them in an operator tree, respecting precedence */ while (expression.size() > 1) { int next_op = -1; int min_priority = 0xFFFFF; bool is_unary = false; bool is_ternary = false; for (int i = 0; i < expression.size(); i++) { if (!expression[i].is_op) { continue; } int priority; bool unary = false; bool ternary = false; bool error = false; bool right_to_left = false; switch (expression[i].op) { case OperatorNode::OP_IS: case OperatorNode::OP_IS_BUILTIN: priority = -1; break; //before anything case OperatorNode::OP_BIT_INVERT: priority = 0; unary = true; break; case OperatorNode::OP_NEG: case OperatorNode::OP_POS: priority = 1; unary = true; break; case OperatorNode::OP_MUL: priority = 2; break; case OperatorNode::OP_DIV: priority = 2; break; case OperatorNode::OP_MOD: priority = 2; break; case OperatorNode::OP_ADD: priority = 3; break; case OperatorNode::OP_SUB: priority = 3; break; case OperatorNode::OP_SHIFT_LEFT: priority = 4; break; case OperatorNode::OP_SHIFT_RIGHT: priority = 4; break; case OperatorNode::OP_BIT_AND: priority = 5; break; case OperatorNode::OP_BIT_XOR: priority = 6; break; case OperatorNode::OP_BIT_OR: priority = 7; break; case OperatorNode::OP_LESS: priority = 8; break; case OperatorNode::OP_LESS_EQUAL: priority = 8; break; case OperatorNode::OP_GREATER: priority = 8; break; case OperatorNode::OP_GREATER_EQUAL: priority = 8; break; case OperatorNode::OP_EQUAL: priority = 8; break; case OperatorNode::OP_NOT_EQUAL: priority = 8; break; case OperatorNode::OP_IN: priority = 10; break; case OperatorNode::OP_NOT: priority = 11; unary = true; break; case OperatorNode::OP_AND: priority = 12; break; case OperatorNode::OP_OR: priority = 13; break; case OperatorNode::OP_TERNARY_IF: priority = 14; ternary = true; right_to_left = true; break; case OperatorNode::OP_TERNARY_ELSE: priority = 14; error = true; // Rigth-to-left should be false in this case, otherwise it would always error. break; case OperatorNode::OP_ASSIGN: priority = 15; break; case OperatorNode::OP_ASSIGN_ADD: priority = 15; break; case OperatorNode::OP_ASSIGN_SUB: priority = 15; break; case OperatorNode::OP_ASSIGN_MUL: priority = 15; break; case OperatorNode::OP_ASSIGN_DIV: priority = 15; break; case OperatorNode::OP_ASSIGN_MOD: priority = 15; break; case OperatorNode::OP_ASSIGN_SHIFT_LEFT: priority = 15; break; case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: priority = 15; break; case OperatorNode::OP_ASSIGN_BIT_AND: priority = 15; break; case OperatorNode::OP_ASSIGN_BIT_OR: priority = 15; break; case OperatorNode::OP_ASSIGN_BIT_XOR: priority = 15; break; default: { _set_error("GDScriptParser bug, invalid operator in expression: " + itos(expression[i].op)); return nullptr; } } if (priority < min_priority || (right_to_left && priority == min_priority)) { // < is used for left to right (default) // <= is used for right to left if (error) { _set_error("Unexpected operator"); return nullptr; } next_op = i; min_priority = priority; is_unary = unary; is_ternary = ternary; } } if (next_op == -1) { _set_error("Yet another parser bug...."); ERR_FAIL_V(nullptr); } // OK! create operator.. if (is_unary) { int expr_pos = next_op; while (expression[expr_pos].is_op) { expr_pos++; if (expr_pos == expression.size()) { //can happen.. _set_error("Unexpected end of expression..."); return nullptr; } } //consecutively do unary operators for (int i = expr_pos - 1; i >= next_op; i--) { OperatorNode *op = alloc_node<OperatorNode>(); op->op = expression[i].op; op->arguments.push_back(expression[i + 1].node); op->line = op_line; //line might have been changed from a \n expression.write[i].is_op = false; expression.write[i].node = op; expression.remove(i + 1); } } else if (is_ternary) { if (next_op < 1 || next_op >= (expression.size() - 1)) { _set_error("Parser bug..."); ERR_FAIL_V(nullptr); } if (next_op >= (expression.size() - 2) || expression[next_op + 2].op != OperatorNode::OP_TERNARY_ELSE) { _set_error("Expected else after ternary if."); return nullptr; } if (next_op >= (expression.size() - 3)) { _set_error("Expected value after ternary else."); return nullptr; } OperatorNode *op = alloc_node<OperatorNode>(); op->op = expression[next_op].op; op->line = op_line; //line might have been changed from a \n if (expression[next_op - 1].is_op) { _set_error("Parser bug..."); ERR_FAIL_V(nullptr); } if (expression[next_op + 1].is_op) { // this is not invalid and can really appear // but it becomes invalid anyway because no binary op // can be followed by a unary op in a valid combination, // due to how precedence works, unaries will always disappear first _set_error("Unexpected two consecutive operators after ternary if."); return nullptr; } if (expression[next_op + 3].is_op) { // this is not invalid and can really appear // but it becomes invalid anyway because no binary op // can be followed by a unary op in a valid combination, // due to how precedence works, unaries will always disappear first _set_error("Unexpected two consecutive operators after ternary else."); return nullptr; } op->arguments.push_back(expression[next_op + 1].node); //next expression goes as first op->arguments.push_back(expression[next_op - 1].node); //left expression goes as when-true op->arguments.push_back(expression[next_op + 3].node); //expression after next goes as when-false //replace all 3 nodes by this operator and make it an expression expression.write[next_op - 1].node = op; expression.remove(next_op); expression.remove(next_op); expression.remove(next_op); expression.remove(next_op); } else { if (next_op < 1 || next_op >= (expression.size() - 1)) { _set_error("Parser bug..."); ERR_FAIL_V(nullptr); } OperatorNode *op = alloc_node<OperatorNode>(); op->op = expression[next_op].op; op->line = op_line; //line might have been changed from a \n if (expression[next_op - 1].is_op) { _set_error("Parser bug..."); ERR_FAIL_V(nullptr); } if (expression[next_op + 1].is_op) { // this is not invalid and can really appear // but it becomes invalid anyway because no binary op // can be followed by a unary op in a valid combination, // due to how precedence works, unaries will always disappear first _set_error("Unexpected two consecutive operators."); return nullptr; } op->arguments.push_back(expression[next_op - 1].node); //expression goes as left op->arguments.push_back(expression[next_op + 1].node); //next expression goes as right //replace all 3 nodes by this operator and make it an expression expression.write[next_op - 1].node = op; expression.remove(next_op); expression.remove(next_op); } } return expression[0].node; } GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to_const) { switch (p_node->type) { case Node::TYPE_BUILT_IN_FUNCTION: { //many may probably be optimizable return p_node; } break; case Node::TYPE_ARRAY: { ArrayNode *an = static_cast<ArrayNode *>(p_node); bool all_constants = true; for (int i = 0; i < an->elements.size(); i++) { an->elements.write[i] = _reduce_expression(an->elements[i], p_to_const); if (an->elements[i]->type != Node::TYPE_CONSTANT) { all_constants = false; } } if (all_constants && p_to_const) { //reduce constant array expression ConstantNode *cn = alloc_node<ConstantNode>(); Array arr; arr.resize(an->elements.size()); for (int i = 0; i < an->elements.size(); i++) { ConstantNode *acn = static_cast<ConstantNode *>(an->elements[i]); arr[i] = acn->value; } cn->value = arr; cn->datatype = _type_from_variant(cn->value); return cn; } return an; } break; case Node::TYPE_DICTIONARY: { DictionaryNode *dn = static_cast<DictionaryNode *>(p_node); bool all_constants = true; for (int i = 0; i < dn->elements.size(); i++) { dn->elements.write[i].key = _reduce_expression(dn->elements[i].key, p_to_const); if (dn->elements[i].key->type != Node::TYPE_CONSTANT) { all_constants = false; } dn->elements.write[i].value = _reduce_expression(dn->elements[i].value, p_to_const); if (dn->elements[i].value->type != Node::TYPE_CONSTANT) { all_constants = false; } } if (all_constants && p_to_const) { //reduce constant array expression ConstantNode *cn = alloc_node<ConstantNode>(); Dictionary dict; for (int i = 0; i < dn->elements.size(); i++) { ConstantNode *key_c = static_cast<ConstantNode *>(dn->elements[i].key); ConstantNode *value_c = static_cast<ConstantNode *>(dn->elements[i].value); dict[key_c->value] = value_c->value; } cn->value = dict; cn->datatype = _type_from_variant(cn->value); return cn; } return dn; } break; case Node::TYPE_OPERATOR: { OperatorNode *op = static_cast<OperatorNode *>(p_node); bool all_constants = true; int last_not_constant = -1; for (int i = 0; i < op->arguments.size(); i++) { op->arguments.write[i] = _reduce_expression(op->arguments[i], p_to_const); if (op->arguments[i]->type != Node::TYPE_CONSTANT) { all_constants = false; last_not_constant = i; } } if (op->op == OperatorNode::OP_IS) { //nothing much return op; } if (op->op == OperatorNode::OP_PARENT_CALL) { //nothing much return op; } else if (op->op == OperatorNode::OP_CALL) { //can reduce base type constructors if ((op->arguments[0]->type == Node::TYPE_TYPE || (op->arguments[0]->type == Node::TYPE_BUILT_IN_FUNCTION && GDScriptFunctions::is_deterministic(static_cast<BuiltInFunctionNode *>(op->arguments[0])->function))) && last_not_constant == 0) { //native type constructor or intrinsic function const Variant **vptr = nullptr; Vector<Variant *> ptrs; if (op->arguments.size() > 1) { ptrs.resize(op->arguments.size() - 1); for (int i = 0; i < ptrs.size(); i++) { ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[i + 1]); ptrs.write[i] = &cn->value; } vptr = (const Variant **)&ptrs[0]; } Variant::CallError ce; Variant v; if (op->arguments[0]->type == Node::TYPE_TYPE) { TypeNode *tn = static_cast<TypeNode *>(op->arguments[0]); v = Variant::construct(tn->vtype, vptr, ptrs.size(), ce); } else { GDScriptFunctions::Function func = static_cast<BuiltInFunctionNode *>(op->arguments[0])->function; GDScriptFunctions::call(func, vptr, ptrs.size(), v, ce); } if (ce.error != Variant::CallError::CALL_OK) { String errwhere; if (op->arguments[0]->type == Node::TYPE_TYPE) { TypeNode *tn = static_cast<TypeNode *>(op->arguments[0]); errwhere = "'" + Variant::get_type_name(tn->vtype) + "' constructor"; } else { GDScriptFunctions::Function func = static_cast<BuiltInFunctionNode *>(op->arguments[0])->function; errwhere = String("'") + GDScriptFunctions::get_func_name(func) + "' intrinsic function"; } switch (ce.error) { case Variant::CallError::CALL_ERROR_INVALID_ARGUMENT: { _set_error("Invalid argument (#" + itos(ce.argument + 1) + ") for " + errwhere + "."); } break; case Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: { _set_error("Too many arguments for " + errwhere + "."); } break; case Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: { _set_error("Too few arguments for " + errwhere + "."); } break; default: { _set_error("Invalid arguments for " + errwhere + "."); } break; } error_line = op->line; return p_node; } ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = v; cn->datatype = _type_from_variant(v); return cn; } return op; //don't reduce yet } else if (op->op == OperatorNode::OP_YIELD) { return op; } else if (op->op == OperatorNode::OP_INDEX) { //can reduce indices into constant arrays or dictionaries if (all_constants) { ConstantNode *ca = static_cast<ConstantNode *>(op->arguments[0]); ConstantNode *cb = static_cast<ConstantNode *>(op->arguments[1]); bool valid; Variant v = ca->value.get(cb->value, &valid); if (!valid) { _set_error("invalid index in constant expression"); error_line = op->line; return op; } ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = v; cn->datatype = _type_from_variant(v); return cn; } return op; } else if (op->op == OperatorNode::OP_INDEX_NAMED) { if (op->arguments[0]->type == Node::TYPE_CONSTANT && op->arguments[1]->type == Node::TYPE_IDENTIFIER) { ConstantNode *ca = static_cast<ConstantNode *>(op->arguments[0]); IdentifierNode *ib = static_cast<IdentifierNode *>(op->arguments[1]); bool valid; Variant v = ca->value.get_named(ib->name, &valid); if (!valid) { _set_error("invalid index '" + String(ib->name) + "' in constant expression"); error_line = op->line; return op; } ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = v; cn->datatype = _type_from_variant(v); return cn; } return op; } //validate assignment (don't assign to constant expression switch (op->op) { case OperatorNode::OP_ASSIGN: case OperatorNode::OP_ASSIGN_ADD: case OperatorNode::OP_ASSIGN_SUB: case OperatorNode::OP_ASSIGN_MUL: case OperatorNode::OP_ASSIGN_DIV: case OperatorNode::OP_ASSIGN_MOD: case OperatorNode::OP_ASSIGN_SHIFT_LEFT: case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: case OperatorNode::OP_ASSIGN_BIT_AND: case OperatorNode::OP_ASSIGN_BIT_OR: case OperatorNode::OP_ASSIGN_BIT_XOR: { if (op->arguments[0]->type == Node::TYPE_CONSTANT) { _set_error("Can't assign to constant", tokenizer->get_token_line() - 1); error_line = op->line; return op; } else if (op->arguments[0]->type == Node::TYPE_SELF) { _set_error("Can't assign to self.", op->line); error_line = op->line; return op; } if (op->arguments[0]->type == Node::TYPE_OPERATOR) { OperatorNode *on = static_cast<OperatorNode *>(op->arguments[0]); if (on->op != OperatorNode::OP_INDEX && on->op != OperatorNode::OP_INDEX_NAMED) { _set_error("Can't assign to an expression", tokenizer->get_token_line() - 1); error_line = op->line; return op; } } } break; default: { break; } } //now se if all are constants if (!all_constants) { return op; //nothing to reduce from here on } #define _REDUCE_UNARY(m_vop) \ bool valid = false; \ Variant res; \ Variant::evaluate(m_vop, static_cast<ConstantNode *>(op->arguments[0])->value, Variant(), res, valid); \ if (!valid) { \ _set_error("Invalid operand for unary operator"); \ error_line = op->line; \ return p_node; \ } \ ConstantNode *cn = alloc_node<ConstantNode>(); \ cn->value = res; \ cn->datatype = _type_from_variant(res); \ return cn; #define _REDUCE_BINARY(m_vop) \ bool valid = false; \ Variant res; \ Variant::evaluate(m_vop, static_cast<ConstantNode *>(op->arguments[0])->value, static_cast<ConstantNode *>(op->arguments[1])->value, res, valid); \ if (!valid) { \ _set_error("Invalid operands for operator"); \ error_line = op->line; \ return p_node; \ } \ ConstantNode *cn = alloc_node<ConstantNode>(); \ cn->value = res; \ cn->datatype = _type_from_variant(res); \ return cn; switch (op->op) { //unary operators case OperatorNode::OP_NEG: { _REDUCE_UNARY(Variant::OP_NEGATE); } break; case OperatorNode::OP_POS: { _REDUCE_UNARY(Variant::OP_POSITIVE); } break; case OperatorNode::OP_NOT: { _REDUCE_UNARY(Variant::OP_NOT); } break; case OperatorNode::OP_BIT_INVERT: { _REDUCE_UNARY(Variant::OP_BIT_NEGATE); } break; //binary operators (in precedence order) case OperatorNode::OP_IN: { _REDUCE_BINARY(Variant::OP_IN); } break; case OperatorNode::OP_EQUAL: { _REDUCE_BINARY(Variant::OP_EQUAL); } break; case OperatorNode::OP_NOT_EQUAL: { _REDUCE_BINARY(Variant::OP_NOT_EQUAL); } break; case OperatorNode::OP_LESS: { _REDUCE_BINARY(Variant::OP_LESS); } break; case OperatorNode::OP_LESS_EQUAL: { _REDUCE_BINARY(Variant::OP_LESS_EQUAL); } break; case OperatorNode::OP_GREATER: { _REDUCE_BINARY(Variant::OP_GREATER); } break; case OperatorNode::OP_GREATER_EQUAL: { _REDUCE_BINARY(Variant::OP_GREATER_EQUAL); } break; case OperatorNode::OP_AND: { _REDUCE_BINARY(Variant::OP_AND); } break; case OperatorNode::OP_OR: { _REDUCE_BINARY(Variant::OP_OR); } break; case OperatorNode::OP_ADD: { _REDUCE_BINARY(Variant::OP_ADD); } break; case OperatorNode::OP_SUB: { _REDUCE_BINARY(Variant::OP_SUBTRACT); } break; case OperatorNode::OP_MUL: { _REDUCE_BINARY(Variant::OP_MULTIPLY); } break; case OperatorNode::OP_DIV: { _REDUCE_BINARY(Variant::OP_DIVIDE); } break; case OperatorNode::OP_MOD: { _REDUCE_BINARY(Variant::OP_MODULE); } break; case OperatorNode::OP_SHIFT_LEFT: { _REDUCE_BINARY(Variant::OP_SHIFT_LEFT); } break; case OperatorNode::OP_SHIFT_RIGHT: { _REDUCE_BINARY(Variant::OP_SHIFT_RIGHT); } break; case OperatorNode::OP_BIT_AND: { _REDUCE_BINARY(Variant::OP_BIT_AND); } break; case OperatorNode::OP_BIT_OR: { _REDUCE_BINARY(Variant::OP_BIT_OR); } break; case OperatorNode::OP_BIT_XOR: { _REDUCE_BINARY(Variant::OP_BIT_XOR); } break; case OperatorNode::OP_TERNARY_IF: { if (static_cast<ConstantNode *>(op->arguments[0])->value.booleanize()) { return op->arguments[1]; } else { return op->arguments[2]; } } break; default: { ERR_FAIL_V(op); } } } break; default: { return p_node; } break; } } GDScriptParser::Node *GDScriptParser::_parse_and_reduce_expression(Node *p_parent, bool p_static, bool p_reduce_const, bool p_allow_assign) { Node *expr = _parse_expression(p_parent, p_static, p_allow_assign, p_reduce_const); if (!expr || error_set) { return nullptr; } expr = _reduce_expression(expr, p_reduce_const); if (!expr || error_set) { return nullptr; } return expr; } bool GDScriptParser::_reduce_export_var_type(Variant &p_value, int p_line) { if (p_value.get_type() == Variant::ARRAY) { Array arr = p_value; for (int i = 0; i < arr.size(); i++) { if (!_reduce_export_var_type(arr[i], p_line)) { return false; } } return true; } if (p_value.get_type() == Variant::DICTIONARY) { Dictionary dict = p_value; for (int i = 0; i < dict.size(); i++) { Variant value = dict.get_value_at_index(i); if (!_reduce_export_var_type(value, p_line)) { return false; } } return true; } // validate type DataType type = _type_from_variant(p_value); if (type.kind == DataType::BUILTIN) { return true; } else if (type.kind == DataType::NATIVE) { if (ClassDB::is_parent_class(type.native_type, "Resource")) { return true; } } _set_error("Invalid export type. Only built-in and native resource types can be exported.", p_line); return false; } bool GDScriptParser::_recover_from_completion() { if (!completion_found) { return false; //can't recover if no completion } //skip stuff until newline while (tokenizer->get_token() != GDScriptTokenizer::TK_NEWLINE && tokenizer->get_token() != GDScriptTokenizer::TK_EOF && tokenizer->get_token() != GDScriptTokenizer::TK_ERROR) { tokenizer->advance(); } completion_found = false; error_set = false; if (tokenizer->get_token() == GDScriptTokenizer::TK_ERROR) { error_set = true; } return true; } GDScriptParser::PatternNode *GDScriptParser::_parse_pattern(bool p_static) { PatternNode *pattern = alloc_node<PatternNode>(); GDScriptTokenizer::Token token = tokenizer->get_token(); if (error_set) { return nullptr; } if (token == GDScriptTokenizer::TK_EOF) { return nullptr; } switch (token) { // array case GDScriptTokenizer::TK_BRACKET_OPEN: { tokenizer->advance(); pattern->pt_type = GDScriptParser::PatternNode::PT_ARRAY; while (true) { if (tokenizer->get_token() == GDScriptTokenizer::TK_BRACKET_CLOSE) { tokenizer->advance(); break; } if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD && tokenizer->get_token(1) == GDScriptTokenizer::TK_PERIOD) { // match everything tokenizer->advance(2); PatternNode *sub_pattern = alloc_node<PatternNode>(); sub_pattern->pt_type = GDScriptParser::PatternNode::PT_IGNORE_REST; pattern->array.push_back(sub_pattern); if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA && tokenizer->get_token(1) == GDScriptTokenizer::TK_BRACKET_CLOSE) { tokenizer->advance(2); break; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BRACKET_CLOSE) { tokenizer->advance(1); break; } else { _set_error("'..' pattern only allowed at the end of an array pattern"); return nullptr; } } PatternNode *sub_pattern = _parse_pattern(p_static); if (!sub_pattern) { return nullptr; } pattern->array.push_back(sub_pattern); if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { tokenizer->advance(); continue; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BRACKET_CLOSE) { tokenizer->advance(); break; } else { _set_error("Not a valid pattern"); return nullptr; } } } break; // bind case GDScriptTokenizer::TK_PR_VAR: { tokenizer->advance(); if (!tokenizer->is_token_literal()) { _set_error("Expected identifier for binding variable name."); return nullptr; } pattern->pt_type = GDScriptParser::PatternNode::PT_BIND; pattern->bind = tokenizer->get_token_literal(); // Check if variable name is already used BlockNode *bl = current_block; while (bl) { if (bl->variables.has(pattern->bind)) { _set_error("Binding name of '" + pattern->bind.operator String() + "' is already declared in this scope."); return nullptr; } bl = bl->parent_block; } // Create local variable for proper identifier detection later LocalVarNode *lv = alloc_node<LocalVarNode>(); lv->name = pattern->bind; current_block->variables.insert(lv->name, lv); tokenizer->advance(); } break; // dictionary case GDScriptTokenizer::TK_CURLY_BRACKET_OPEN: { tokenizer->advance(); pattern->pt_type = GDScriptParser::PatternNode::PT_DICTIONARY; while (true) { if (tokenizer->get_token() == GDScriptTokenizer::TK_CURLY_BRACKET_CLOSE) { tokenizer->advance(); break; } if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD && tokenizer->get_token(1) == GDScriptTokenizer::TK_PERIOD) { // match everything tokenizer->advance(2); PatternNode *sub_pattern = alloc_node<PatternNode>(); sub_pattern->pt_type = PatternNode::PT_IGNORE_REST; pattern->array.push_back(sub_pattern); if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA && tokenizer->get_token(1) == GDScriptTokenizer::TK_CURLY_BRACKET_CLOSE) { tokenizer->advance(2); break; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CURLY_BRACKET_CLOSE) { tokenizer->advance(1); break; } else { _set_error("'..' pattern only allowed at the end of a dictionary pattern"); return nullptr; } } Node *key = _parse_and_reduce_expression(pattern, p_static); if (!key) { _set_error("Not a valid key in pattern"); return nullptr; } if (key->type != GDScriptParser::Node::TYPE_CONSTANT) { _set_error("Not a constant expression as key"); return nullptr; } if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) { tokenizer->advance(); PatternNode *value = _parse_pattern(p_static); if (!value) { _set_error("Expected pattern in dictionary value"); return nullptr; } pattern->dictionary.insert(static_cast<ConstantNode *>(key), value); } else { pattern->dictionary.insert(static_cast<ConstantNode *>(key), NULL); } if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { tokenizer->advance(); continue; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CURLY_BRACKET_CLOSE) { tokenizer->advance(); break; } else { _set_error("Not a valid pattern"); return nullptr; } } } break; case GDScriptTokenizer::TK_WILDCARD: { tokenizer->advance(); pattern->pt_type = PatternNode::PT_WILDCARD; } break; // all the constants like strings and numbers default: { Node *value = _parse_and_reduce_expression(pattern, p_static); if (!value) { _set_error("Expect constant expression or variables in a pattern"); return nullptr; } if (value->type == Node::TYPE_OPERATOR) { // Maybe it's SomeEnum.VALUE Node *current_value = value; while (current_value->type == Node::TYPE_OPERATOR) { OperatorNode *op_node = static_cast<OperatorNode *>(current_value); if (op_node->op != OperatorNode::OP_INDEX_NAMED) { _set_error("Invalid operator in pattern. Only index (`A.B`) is allowed"); return nullptr; } current_value = op_node->arguments[0]; } if (current_value->type != Node::TYPE_IDENTIFIER) { _set_error("Only constant expression or variables allowed in a pattern"); return nullptr; } } else if (value->type != Node::TYPE_IDENTIFIER && value->type != Node::TYPE_CONSTANT) { _set_error("Only constant expressions or variables allowed in a pattern"); return nullptr; } pattern->pt_type = PatternNode::PT_CONSTANT; pattern->constant = value; } break; } return pattern; } void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode *> &p_branches, bool p_static) { IndentLevel current_level = indent_level.back()->get(); p_block->has_return = true; bool catch_all_appeared = false; while (true) { while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE && _parse_newline()) { ; } // GDScriptTokenizer::Token token = tokenizer->get_token(); if (error_set) { return; } if (current_level.indent > indent_level.back()->get().indent) { break; // go back a level } pending_newline = -1; PatternBranchNode *branch = alloc_node<PatternBranchNode>(); branch->body = alloc_node<BlockNode>(); branch->body->parent_block = p_block; p_block->sub_blocks.push_back(branch->body); current_block = branch->body; branch->patterns.push_back(_parse_pattern(p_static)); if (!branch->patterns[0]) { break; } bool has_binding = branch->patterns[0]->pt_type == PatternNode::PT_BIND; bool catch_all = has_binding || branch->patterns[0]->pt_type == PatternNode::PT_WILDCARD; #ifdef DEBUG_ENABLED // Branches after a wildcard or binding are unreachable if (catch_all_appeared && !current_function->has_unreachable_code) { _add_warning(GDScriptWarning::UNREACHABLE_CODE, -1, current_function->name.operator String()); current_function->has_unreachable_code = true; } #endif while (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { tokenizer->advance(); branch->patterns.push_back(_parse_pattern(p_static)); if (!branch->patterns[branch->patterns.size() - 1]) { return; } PatternNode::PatternType pt = branch->patterns[branch->patterns.size() - 1]->pt_type; if (pt == PatternNode::PT_BIND) { _set_error("Cannot use bindings with multipattern."); return; } catch_all = catch_all || pt == PatternNode::PT_WILDCARD; } catch_all_appeared = catch_all_appeared || catch_all; if (!_enter_indent_block()) { _set_error("Expected block in pattern branch"); return; } _parse_block(branch->body, p_static); current_block = p_block; if (!branch->body->has_return) { p_block->has_return = false; } p_branches.push_back(branch); } // Even if all branches return, there is possibility of default fallthrough if (!catch_all_appeared) { p_block->has_return = false; } } void GDScriptParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, Node *&p_resulting_node, Map<StringName, Node *> &p_bindings) { const DataType &to_match_type = p_node_to_match->get_datatype(); switch (p_pattern->pt_type) { case PatternNode::PT_CONSTANT: { DataType pattern_type = _reduce_node_type(p_pattern->constant); if (error_set) { return; } OperatorNode *type_comp = nullptr; // static type check if possible if (pattern_type.has_type && to_match_type.has_type) { if (!_is_type_compatible(to_match_type, pattern_type) && !_is_type_compatible(pattern_type, to_match_type)) { _set_error("The pattern type (" + pattern_type.to_string() + ") isn't compatible with the type of the value to match (" + to_match_type.to_string() + ").", p_pattern->line); return; } } else { // runtime typecheck BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>(); typeof_node->function = GDScriptFunctions::TYPE_OF; OperatorNode *typeof_match_value = alloc_node<OperatorNode>(); typeof_match_value->op = OperatorNode::OP_CALL; typeof_match_value->arguments.push_back(typeof_node); typeof_match_value->arguments.push_back(p_node_to_match); OperatorNode *typeof_pattern_value = alloc_node<OperatorNode>(); typeof_pattern_value->op = OperatorNode::OP_CALL; typeof_pattern_value->arguments.push_back(typeof_node); typeof_pattern_value->arguments.push_back(p_pattern->constant); type_comp = alloc_node<OperatorNode>(); type_comp->op = OperatorNode::OP_EQUAL; type_comp->arguments.push_back(typeof_match_value); type_comp->arguments.push_back(typeof_pattern_value); } // compare the actual values OperatorNode *value_comp = alloc_node<OperatorNode>(); value_comp->op = OperatorNode::OP_EQUAL; value_comp->arguments.push_back(p_pattern->constant); value_comp->arguments.push_back(p_node_to_match); if (type_comp) { OperatorNode *full_comparison = alloc_node<OperatorNode>(); full_comparison->op = OperatorNode::OP_AND; full_comparison->arguments.push_back(type_comp); full_comparison->arguments.push_back(value_comp); p_resulting_node = full_comparison; } else { p_resulting_node = value_comp; } } break; case PatternNode::PT_BIND: { p_bindings[p_pattern->bind] = p_node_to_match; // a bind always matches ConstantNode *true_value = alloc_node<ConstantNode>(); true_value->value = Variant(true); p_resulting_node = true_value; } break; case PatternNode::PT_ARRAY: { bool open_ended = false; if (p_pattern->array.size() > 0) { if (p_pattern->array[p_pattern->array.size() - 1]->pt_type == PatternNode::PT_IGNORE_REST) { open_ended = true; } } // typeof(value_to_match) == TYPE_ARRAY && value_to_match.size() >= length // typeof(value_to_match) == TYPE_ARRAY && value_to_match.size() == length { OperatorNode *type_comp = nullptr; // static type check if possible if (to_match_type.has_type) { // must be an array if (to_match_type.kind != DataType::BUILTIN || to_match_type.builtin_type != Variant::ARRAY) { _set_error("Cannot match an array pattern with a non-array expression.", p_pattern->line); return; } } else { // runtime typecheck BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>(); typeof_node->function = GDScriptFunctions::TYPE_OF; OperatorNode *typeof_match_value = alloc_node<OperatorNode>(); typeof_match_value->op = OperatorNode::OP_CALL; typeof_match_value->arguments.push_back(typeof_node); typeof_match_value->arguments.push_back(p_node_to_match); IdentifierNode *typeof_array = alloc_node<IdentifierNode>(); typeof_array->name = "TYPE_ARRAY"; type_comp = alloc_node<OperatorNode>(); type_comp->op = OperatorNode::OP_EQUAL; type_comp->arguments.push_back(typeof_match_value); type_comp->arguments.push_back(typeof_array); } // size ConstantNode *length = alloc_node<ConstantNode>(); length->value = Variant(open_ended ? p_pattern->array.size() - 1 : p_pattern->array.size()); OperatorNode *call = alloc_node<OperatorNode>(); call->op = OperatorNode::OP_CALL; call->arguments.push_back(p_node_to_match); IdentifierNode *size = alloc_node<IdentifierNode>(); size->name = "size"; call->arguments.push_back(size); OperatorNode *length_comparison = alloc_node<OperatorNode>(); length_comparison->op = open_ended ? OperatorNode::OP_GREATER_EQUAL : OperatorNode::OP_EQUAL; length_comparison->arguments.push_back(call); length_comparison->arguments.push_back(length); if (type_comp) { OperatorNode *type_and_length_comparison = alloc_node<OperatorNode>(); type_and_length_comparison->op = OperatorNode::OP_AND; type_and_length_comparison->arguments.push_back(type_comp); type_and_length_comparison->arguments.push_back(length_comparison); p_resulting_node = type_and_length_comparison; } else { p_resulting_node = length_comparison; } } for (int i = 0; i < p_pattern->array.size(); i++) { PatternNode *pattern = p_pattern->array[i]; Node *condition = nullptr; ConstantNode *index = alloc_node<ConstantNode>(); index->value = Variant(i); OperatorNode *indexed_value = alloc_node<OperatorNode>(); indexed_value->op = OperatorNode::OP_INDEX; indexed_value->arguments.push_back(p_node_to_match); indexed_value->arguments.push_back(index); _generate_pattern(pattern, indexed_value, condition, p_bindings); // concatenate all the patterns with && OperatorNode *and_node = alloc_node<OperatorNode>(); and_node->op = OperatorNode::OP_AND; and_node->arguments.push_back(p_resulting_node); and_node->arguments.push_back(condition); p_resulting_node = and_node; } } break; case PatternNode::PT_DICTIONARY: { bool open_ended = false; if (p_pattern->array.size() > 0) { open_ended = true; } // typeof(value_to_match) == TYPE_DICTIONARY && value_to_match.size() >= length // typeof(value_to_match) == TYPE_DICTIONARY && value_to_match.size() == length { OperatorNode *type_comp = nullptr; // static type check if possible if (to_match_type.has_type) { // must be an dictionary if (to_match_type.kind != DataType::BUILTIN || to_match_type.builtin_type != Variant::DICTIONARY) { _set_error("Cannot match an dictionary pattern with a non-dictionary expression.", p_pattern->line); return; } } else { // runtime typecheck BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>(); typeof_node->function = GDScriptFunctions::TYPE_OF; OperatorNode *typeof_match_value = alloc_node<OperatorNode>(); typeof_match_value->op = OperatorNode::OP_CALL; typeof_match_value->arguments.push_back(typeof_node); typeof_match_value->arguments.push_back(p_node_to_match); IdentifierNode *typeof_dictionary = alloc_node<IdentifierNode>(); typeof_dictionary->name = "TYPE_DICTIONARY"; type_comp = alloc_node<OperatorNode>(); type_comp->op = OperatorNode::OP_EQUAL; type_comp->arguments.push_back(typeof_match_value); type_comp->arguments.push_back(typeof_dictionary); } // size ConstantNode *length = alloc_node<ConstantNode>(); length->value = Variant(open_ended ? p_pattern->dictionary.size() - 1 : p_pattern->dictionary.size()); OperatorNode *call = alloc_node<OperatorNode>(); call->op = OperatorNode::OP_CALL; call->arguments.push_back(p_node_to_match); IdentifierNode *size = alloc_node<IdentifierNode>(); size->name = "size"; call->arguments.push_back(size); OperatorNode *length_comparison = alloc_node<OperatorNode>(); length_comparison->op = open_ended ? OperatorNode::OP_GREATER_EQUAL : OperatorNode::OP_EQUAL; length_comparison->arguments.push_back(call); length_comparison->arguments.push_back(length); if (type_comp) { OperatorNode *type_and_length_comparison = alloc_node<OperatorNode>(); type_and_length_comparison->op = OperatorNode::OP_AND; type_and_length_comparison->arguments.push_back(type_comp); type_and_length_comparison->arguments.push_back(length_comparison); p_resulting_node = type_and_length_comparison; } else { p_resulting_node = length_comparison; } } for (Map<ConstantNode *, PatternNode *>::Element *e = p_pattern->dictionary.front(); e; e = e->next()) { Node *condition = nullptr; // check for has, then for pattern IdentifierNode *has = alloc_node<IdentifierNode>(); has->name = "has"; OperatorNode *has_call = alloc_node<OperatorNode>(); has_call->op = OperatorNode::OP_CALL; has_call->arguments.push_back(p_node_to_match); has_call->arguments.push_back(has); has_call->arguments.push_back(e->key()); if (e->value()) { OperatorNode *indexed_value = alloc_node<OperatorNode>(); indexed_value->op = OperatorNode::OP_INDEX; indexed_value->arguments.push_back(p_node_to_match); indexed_value->arguments.push_back(e->key()); _generate_pattern(e->value(), indexed_value, condition, p_bindings); OperatorNode *has_and_pattern = alloc_node<OperatorNode>(); has_and_pattern->op = OperatorNode::OP_AND; has_and_pattern->arguments.push_back(has_call); has_and_pattern->arguments.push_back(condition); condition = has_and_pattern; } else { condition = has_call; } // concatenate all the patterns with && OperatorNode *and_node = alloc_node<OperatorNode>(); and_node->op = OperatorNode::OP_AND; and_node->arguments.push_back(p_resulting_node); and_node->arguments.push_back(condition); p_resulting_node = and_node; } } break; case PatternNode::PT_IGNORE_REST: case PatternNode::PT_WILDCARD: { // simply generate a `true` ConstantNode *true_value = alloc_node<ConstantNode>(); true_value->value = Variant(true); p_resulting_node = true_value; } break; default: { } break; } } void GDScriptParser::_transform_match_statment(MatchNode *p_match_statement) { IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = "#match_value"; id->line = p_match_statement->line; id->datatype = _reduce_node_type(p_match_statement->val_to_match); if (id->datatype.has_type) { _mark_line_as_safe(id->line); } else { _mark_line_as_unsafe(id->line); } if (error_set) { return; } for (int i = 0; i < p_match_statement->branches.size(); i++) { PatternBranchNode *branch = p_match_statement->branches[i]; MatchNode::CompiledPatternBranch compiled_branch; compiled_branch.compiled_pattern = nullptr; Map<StringName, Node *> binding; for (int j = 0; j < branch->patterns.size(); j++) { PatternNode *pattern = branch->patterns[j]; _mark_line_as_safe(pattern->line); Map<StringName, Node *> bindings; Node *resulting_node = nullptr; _generate_pattern(pattern, id, resulting_node, bindings); if (!resulting_node) { return; } if (!binding.empty() && !bindings.empty()) { _set_error("Multipatterns can't contain bindings"); return; } else { binding = bindings; } // Result is always a boolean DataType resulting_node_type; resulting_node_type.has_type = true; resulting_node_type.is_constant = true; resulting_node_type.kind = DataType::BUILTIN; resulting_node_type.builtin_type = Variant::BOOL; resulting_node->set_datatype(resulting_node_type); if (compiled_branch.compiled_pattern) { OperatorNode *or_node = alloc_node<OperatorNode>(); or_node->op = OperatorNode::OP_OR; or_node->arguments.push_back(compiled_branch.compiled_pattern); or_node->arguments.push_back(resulting_node); compiled_branch.compiled_pattern = or_node; } else { // single pattern | first one compiled_branch.compiled_pattern = resulting_node; } } // prepare the body ...hehe for (Map<StringName, Node *>::Element *e = binding.front(); e; e = e->next()) { if (!branch->body->variables.has(e->key())) { _set_error("Parser bug: missing pattern bind variable.", branch->line); ERR_FAIL(); } LocalVarNode *local_var = branch->body->variables[e->key()]; local_var->assign = e->value(); local_var->set_datatype(local_var->assign->get_datatype()); local_var->assignments++; IdentifierNode *id2 = alloc_node<IdentifierNode>(); id2->name = local_var->name; id2->datatype = local_var->datatype; id2->declared_block = branch->body; id2->set_datatype(local_var->assign->get_datatype()); OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_ASSIGN; op->arguments.push_back(id2); op->arguments.push_back(local_var->assign); local_var->assign_op = op; branch->body->statements.insert(0, op); branch->body->statements.insert(0, local_var); } compiled_branch.body = branch->body; p_match_statement->compiled_pattern_branches.push_back(compiled_branch); } } void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { IndentLevel current_level = indent_level.back()->get(); #ifdef DEBUG_ENABLED pending_newline = -1; // reset for the new block NewLineNode *nl = alloc_node<NewLineNode>(); nl->line = tokenizer->get_token_line(); p_block->statements.push_back(nl); #endif bool is_first_line = true; while (true) { if (!is_first_line && indent_level.back()->prev() && indent_level.back()->prev()->get().indent == current_level.indent) { if (indent_level.back()->prev()->get().is_mixed(current_level)) { _set_error("Mixed tabs and spaces in indentation."); return; } // pythonic single-line expression, don't parse future lines indent_level.pop_back(); p_block->end_line = tokenizer->get_token_line(); return; } is_first_line = false; GDScriptTokenizer::Token token = tokenizer->get_token(); if (error_set) { return; } if (current_level.indent > indent_level.back()->get().indent) { p_block->end_line = tokenizer->get_token_line(); return; //go back a level } if (pending_newline != -1) { NewLineNode *nl2 = alloc_node<NewLineNode>(); nl2->line = pending_newline; p_block->statements.push_back(nl2); pending_newline = -1; } #ifdef DEBUG_ENABLED switch (token) { case GDScriptTokenizer::TK_EOF: case GDScriptTokenizer::TK_ERROR: case GDScriptTokenizer::TK_NEWLINE: case GDScriptTokenizer::TK_CF_PASS: { // will check later } break; default: { if (p_block->has_return && !current_function->has_unreachable_code) { _add_warning(GDScriptWarning::UNREACHABLE_CODE, -1, current_function->name.operator String()); current_function->has_unreachable_code = true; } } break; } #endif // DEBUG_ENABLED switch (token) { case GDScriptTokenizer::TK_EOF: p_block->end_line = tokenizer->get_token_line(); case GDScriptTokenizer::TK_ERROR: { return; //go back //end of file! } break; case GDScriptTokenizer::TK_NEWLINE: { int line = tokenizer->get_token_line(); if (!_parse_newline()) { if (!error_set) { p_block->end_line = tokenizer->get_token_line(); pending_newline = p_block->end_line; } return; } _mark_line_as_safe(line); NewLineNode *nl2 = alloc_node<NewLineNode>(); nl2->line = line; p_block->statements.push_back(nl2); } break; case GDScriptTokenizer::TK_CF_PASS: { if (tokenizer->get_token(1) != GDScriptTokenizer::TK_SEMICOLON && tokenizer->get_token(1) != GDScriptTokenizer::TK_NEWLINE && tokenizer->get_token(1) != GDScriptTokenizer::TK_EOF) { _set_error("Expected \";\" or a line break."); return; } _mark_line_as_safe(tokenizer->get_token_line()); tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_SEMICOLON) { // Ignore semicolon after 'pass'. tokenizer->advance(); } } break; case GDScriptTokenizer::TK_PR_VAR: { // Variable declaration and (eventual) initialization. tokenizer->advance(); int var_line = tokenizer->get_token_line(); if (!tokenizer->is_token_literal(0, true)) { _set_error("Expected an identifier for the local variable name."); return; } StringName n = tokenizer->get_token_literal(); if (current_function) { for (int i = 0; i < current_function->arguments.size(); i++) { if (n == current_function->arguments[i]) { _set_error("Variable \"" + String(n) + "\" already defined in the scope (at line " + itos(current_function->line) + ")."); return; } } } BlockNode *check_block = p_block; while (check_block) { if (check_block->variables.has(n)) { _set_error("Variable \"" + String(n) + "\" already defined in the scope (at line " + itos(check_block->variables[n]->line) + ")."); return; } check_block = check_block->parent_block; } tokenizer->advance(); //must know when the local variable is declared LocalVarNode *lv = alloc_node<LocalVarNode>(); lv->name = n; lv->line = var_line; p_block->statements.push_back(lv); Node *assigned = nullptr; if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) { if (tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) { lv->datatype = DataType(); lv->datatype.infer_type = true; tokenizer->advance(); } else if (!_parse_type(lv->datatype)) { _set_error("Expected a type for the variable."); return; } } if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_ASSIGN) { tokenizer->advance(); Node *subexpr = _parse_and_reduce_expression(p_block, p_static); if (!subexpr) { if (_recover_from_completion()) { break; } return; } lv->assignments++; assigned = subexpr; } else { assigned = _get_default_value_for_type(lv->datatype, var_line); } //must be added later, to avoid self-referencing. p_block->variables.insert(n, lv); IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = n; id->declared_block = p_block; id->line = var_line; OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_ASSIGN; op->arguments.push_back(id); op->arguments.push_back(assigned); op->line = var_line; p_block->statements.push_back(op); lv->assign_op = op; lv->assign = assigned; if (!_end_statement()) { _set_end_statement_error("var"); return; } } break; case GDScriptTokenizer::TK_CF_IF: { tokenizer->advance(); Node *condition = _parse_and_reduce_expression(p_block, p_static); if (!condition) { if (_recover_from_completion()) { break; } return; } ControlFlowNode *cf_if = alloc_node<ControlFlowNode>(); cf_if->cf_type = ControlFlowNode::CF_IF; cf_if->arguments.push_back(condition); cf_if->body = alloc_node<BlockNode>(); cf_if->body->parent_block = p_block; cf_if->body->if_condition = condition; //helps code completion p_block->sub_blocks.push_back(cf_if->body); if (!_enter_indent_block(cf_if->body)) { _set_error("Expected an indented block after \"if\"."); p_block->end_line = tokenizer->get_token_line(); return; } current_block = cf_if->body; _parse_block(cf_if->body, p_static); current_block = p_block; if (error_set) { return; } p_block->statements.push_back(cf_if); bool all_have_return = cf_if->body->has_return; bool have_else = false; while (true) { while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE && _parse_newline()) { ; } if (indent_level.back()->get().indent < current_level.indent) { //not at current indent level p_block->end_line = tokenizer->get_token_line(); return; } if (tokenizer->get_token() == GDScriptTokenizer::TK_CF_ELIF) { if (indent_level.back()->get().indent > current_level.indent) { _set_error("Invalid indentation."); return; } tokenizer->advance(); cf_if->body_else = alloc_node<BlockNode>(); cf_if->body_else->parent_block = p_block; p_block->sub_blocks.push_back(cf_if->body_else); ControlFlowNode *cf_else = alloc_node<ControlFlowNode>(); cf_else->cf_type = ControlFlowNode::CF_IF; //condition Node *condition2 = _parse_and_reduce_expression(p_block, p_static); if (!condition2) { if (_recover_from_completion()) { break; } return; } cf_else->arguments.push_back(condition2); cf_else->cf_type = ControlFlowNode::CF_IF; cf_if->body_else->statements.push_back(cf_else); cf_if = cf_else; cf_if->body = alloc_node<BlockNode>(); cf_if->body->parent_block = p_block; p_block->sub_blocks.push_back(cf_if->body); if (!_enter_indent_block(cf_if->body)) { _set_error("Expected an indented block after \"elif\"."); p_block->end_line = tokenizer->get_token_line(); return; } current_block = cf_else->body; _parse_block(cf_else->body, p_static); current_block = p_block; if (error_set) { return; } all_have_return = all_have_return && cf_else->body->has_return; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CF_ELSE) { if (indent_level.back()->get().indent > current_level.indent) { _set_error("Invalid indentation."); return; } tokenizer->advance(); cf_if->body_else = alloc_node<BlockNode>(); cf_if->body_else->parent_block = p_block; p_block->sub_blocks.push_back(cf_if->body_else); if (!_enter_indent_block(cf_if->body_else)) { _set_error("Expected an indented block after \"else\"."); p_block->end_line = tokenizer->get_token_line(); return; } current_block = cf_if->body_else; _parse_block(cf_if->body_else, p_static); current_block = p_block; if (error_set) { return; } all_have_return = all_have_return && cf_if->body_else->has_return; have_else = true; break; //after else, exit } else { break; } } cf_if->body->has_return = all_have_return; // If there's no else block, path out of the if might not have a return p_block->has_return = all_have_return && have_else; } break; case GDScriptTokenizer::TK_CF_WHILE: { tokenizer->advance(); Node *condition2 = _parse_and_reduce_expression(p_block, p_static); if (!condition2) { if (_recover_from_completion()) { break; } return; } ControlFlowNode *cf_while = alloc_node<ControlFlowNode>(); cf_while->cf_type = ControlFlowNode::CF_WHILE; cf_while->arguments.push_back(condition2); cf_while->body = alloc_node<BlockNode>(); cf_while->body->parent_block = p_block; cf_while->body->can_break = true; cf_while->body->can_continue = true; p_block->sub_blocks.push_back(cf_while->body); if (!_enter_indent_block(cf_while->body)) { _set_error("Expected an indented block after \"while\"."); p_block->end_line = tokenizer->get_token_line(); return; } current_block = cf_while->body; _parse_block(cf_while->body, p_static); current_block = p_block; if (error_set) { return; } p_block->statements.push_back(cf_while); } break; case GDScriptTokenizer::TK_CF_FOR: { tokenizer->advance(); if (!tokenizer->is_token_literal(0, true)) { _set_error("Identifier expected after \"for\"."); } IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = tokenizer->get_token_identifier(); #ifdef DEBUG_ENABLED for (int j = 0; j < current_class->variables.size(); j++) { if (current_class->variables[j].identifier == id->name) { _add_warning(GDScriptWarning::SHADOWED_VARIABLE, id->line, id->name, itos(current_class->variables[j].line)); } } #endif // DEBUG_ENABLED BlockNode *check_block = p_block; while (check_block) { if (check_block->variables.has(id->name)) { _set_error("Variable \"" + String(id->name) + "\" already defined in the scope (at line " + itos(check_block->variables[id->name]->line) + ")."); return; } check_block = check_block->parent_block; } tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_OP_IN) { _set_error("\"in\" expected after identifier."); return; } tokenizer->advance(); Node *container = _parse_and_reduce_expression(p_block, p_static); if (!container) { if (_recover_from_completion()) { break; } return; } DataType iter_type; if (container->type == Node::TYPE_OPERATOR) { OperatorNode *op = static_cast<OperatorNode *>(container); if (op->op == OperatorNode::OP_CALL && op->arguments[0]->type == Node::TYPE_BUILT_IN_FUNCTION && static_cast<BuiltInFunctionNode *>(op->arguments[0])->function == GDScriptFunctions::GEN_RANGE) { //iterating a range, so see if range() can be optimized without allocating memory, by replacing it by vectors (which can work as iterable too!) Vector<Node *> args; Vector<double> constants; bool constant = true; for (int i = 1; i < op->arguments.size(); i++) { args.push_back(op->arguments[i]); if (op->arguments[i]->type == Node::TYPE_CONSTANT) { ConstantNode *c = static_cast<ConstantNode *>(op->arguments[i]); if (c->value.get_type() == Variant::REAL || c->value.get_type() == Variant::INT) { constants.push_back(c->value); } else { constant = false; } } else { constant = false; } } if (args.size() > 0 && args.size() < 4) { if (constant) { ConstantNode *cn = alloc_node<ConstantNode>(); switch (args.size()) { case 1: cn->value = (int)constants[0]; break; case 2: cn->value = Vector2(constants[0], constants[1]); break; case 3: cn->value = Vector3(constants[0], constants[1], constants[2]); break; } cn->datatype = _type_from_variant(cn->value); container = cn; } else { OperatorNode *on = alloc_node<OperatorNode>(); on->op = OperatorNode::OP_CALL; TypeNode *tn = alloc_node<TypeNode>(); on->arguments.push_back(tn); switch (args.size()) { case 1: tn->vtype = Variant::INT; break; case 2: tn->vtype = Variant::VECTOR2; break; case 3: tn->vtype = Variant::VECTOR3; break; } for (int i = 0; i < args.size(); i++) { on->arguments.push_back(args[i]); } container = on; } } iter_type.has_type = true; iter_type.kind = DataType::BUILTIN; iter_type.builtin_type = Variant::INT; } } ControlFlowNode *cf_for = alloc_node<ControlFlowNode>(); cf_for->cf_type = ControlFlowNode::CF_FOR; cf_for->arguments.push_back(id); cf_for->arguments.push_back(container); cf_for->body = alloc_node<BlockNode>(); cf_for->body->parent_block = p_block; cf_for->body->can_break = true; cf_for->body->can_continue = true; p_block->sub_blocks.push_back(cf_for->body); if (!_enter_indent_block(cf_for->body)) { _set_error("Expected indented block after \"for\"."); p_block->end_line = tokenizer->get_token_line(); return; } current_block = cf_for->body; // this is for checking variable for redefining // inside this _parse_block LocalVarNode *lv = alloc_node<LocalVarNode>(); lv->name = id->name; lv->line = id->line; lv->assignments++; id->declared_block = cf_for->body; lv->set_datatype(iter_type); id->set_datatype(iter_type); cf_for->body->variables.insert(id->name, lv); _parse_block(cf_for->body, p_static); current_block = p_block; if (error_set) { return; } p_block->statements.push_back(cf_for); } break; case GDScriptTokenizer::TK_CF_CONTINUE: { BlockNode *upper_block = p_block; bool is_continue_valid = false; while (upper_block) { if (upper_block->can_continue) { is_continue_valid = true; break; } upper_block = upper_block->parent_block; } if (!is_continue_valid) { _set_error("Unexpected keyword \"continue\" outside a loop."); return; } _mark_line_as_safe(tokenizer->get_token_line()); tokenizer->advance(); ControlFlowNode *cf_continue = alloc_node<ControlFlowNode>(); cf_continue->cf_type = ControlFlowNode::CF_CONTINUE; p_block->statements.push_back(cf_continue); if (!_end_statement()) { _set_end_statement_error("continue"); return; } } break; case GDScriptTokenizer::TK_CF_BREAK: { BlockNode *upper_block = p_block; bool is_break_valid = false; while (upper_block) { if (upper_block->can_break) { is_break_valid = true; break; } upper_block = upper_block->parent_block; } if (!is_break_valid) { _set_error("Unexpected keyword \"break\" outside a loop."); return; } _mark_line_as_safe(tokenizer->get_token_line()); tokenizer->advance(); ControlFlowNode *cf_break = alloc_node<ControlFlowNode>(); cf_break->cf_type = ControlFlowNode::CF_BREAK; p_block->statements.push_back(cf_break); if (!_end_statement()) { _set_end_statement_error("break"); return; } } break; case GDScriptTokenizer::TK_CF_RETURN: { tokenizer->advance(); ControlFlowNode *cf_return = alloc_node<ControlFlowNode>(); cf_return->cf_type = ControlFlowNode::CF_RETURN; cf_return->line = tokenizer->get_token_line(-1); if (tokenizer->get_token() == GDScriptTokenizer::TK_SEMICOLON || tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE || tokenizer->get_token() == GDScriptTokenizer::TK_EOF) { //expect end of statement p_block->statements.push_back(cf_return); if (!_end_statement()) { return; } } else { //expect expression Node *retexpr = _parse_and_reduce_expression(p_block, p_static); if (!retexpr) { if (_recover_from_completion()) { break; } return; } cf_return->arguments.push_back(retexpr); p_block->statements.push_back(cf_return); if (!_end_statement()) { _set_end_statement_error("return"); return; } } p_block->has_return = true; } break; case GDScriptTokenizer::TK_CF_MATCH: { tokenizer->advance(); MatchNode *match_node = alloc_node<MatchNode>(); Node *val_to_match = _parse_and_reduce_expression(p_block, p_static); if (!val_to_match) { if (_recover_from_completion()) { break; } return; } match_node->val_to_match = val_to_match; if (!_enter_indent_block()) { _set_error("Expected indented pattern matching block after \"match\"."); return; } BlockNode *compiled_branches = alloc_node<BlockNode>(); compiled_branches->parent_block = p_block; compiled_branches->parent_class = p_block->parent_class; compiled_branches->can_continue = true; p_block->sub_blocks.push_back(compiled_branches); _parse_pattern_block(compiled_branches, match_node->branches, p_static); if (error_set) { return; } ControlFlowNode *match_cf_node = alloc_node<ControlFlowNode>(); match_cf_node->cf_type = ControlFlowNode::CF_MATCH; match_cf_node->match = match_node; match_cf_node->body = compiled_branches; p_block->has_return = p_block->has_return || compiled_branches->has_return; p_block->statements.push_back(match_cf_node); _end_statement(); } break; case GDScriptTokenizer::TK_PR_ASSERT: { tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after assert"); return; } int assert_line = tokenizer->get_token_line(); tokenizer->advance(); Vector<Node *> args; const bool result = _parse_arguments(p_block, args, p_static); if (!result) { return; } if (args.empty() || args.size() > 2) { _set_error("Wrong number of arguments, expected 1 or 2", assert_line); return; } AssertNode *an = alloc_node<AssertNode>(); an->condition = _reduce_expression(args[0], p_static); an->line = assert_line; if (args.size() == 2) { an->message = _reduce_expression(args[1], p_static); } else { ConstantNode *message_node = alloc_node<ConstantNode>(); message_node->value = String(); an->message = message_node; } p_block->statements.push_back(an); if (!_end_statement()) { _set_end_statement_error("assert"); return; } } break; case GDScriptTokenizer::TK_PR_BREAKPOINT: { tokenizer->advance(); BreakpointNode *bn = alloc_node<BreakpointNode>(); p_block->statements.push_back(bn); if (!_end_statement()) { _set_end_statement_error("breakpoint"); return; } } break; default: { Node *expression = _parse_and_reduce_expression(p_block, p_static, false, true); if (!expression) { if (_recover_from_completion()) { break; } return; } p_block->statements.push_back(expression); if (!_end_statement()) { // Attempt to guess a better error message if the user "retypes" a variable if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON && tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) { _set_error("Unexpected ':=', use '=' instead. Expected end of statement after expression."); } else { _set_error(vformat("Expected end of statement after expression, got %s instead.", tokenizer->get_token_name(tokenizer->get_token()))); } return; } } break; } } } bool GDScriptParser::_parse_newline() { if (tokenizer->get_token(1) != GDScriptTokenizer::TK_EOF && tokenizer->get_token(1) != GDScriptTokenizer::TK_NEWLINE) { IndentLevel current_level = indent_level.back()->get(); int indent = tokenizer->get_token_line_indent(); int tabs = tokenizer->get_token_line_tab_indent(); IndentLevel new_level(indent, tabs); if (new_level.is_mixed(current_level)) { _set_error("Mixed tabs and spaces in indentation."); return false; } if (indent > current_level.indent) { _set_error("Unexpected indentation."); return false; } if (indent < current_level.indent) { while (indent < current_level.indent) { //exit block if (indent_level.size() == 1) { _set_error("Invalid indentation. Bug?"); return false; } indent_level.pop_back(); if (indent_level.back()->get().indent < indent) { _set_error("Unindent does not match any outer indentation level."); return false; } if (indent_level.back()->get().is_mixed(current_level)) { _set_error("Mixed tabs and spaces in indentation."); return false; } current_level = indent_level.back()->get(); } tokenizer->advance(); return false; } } tokenizer->advance(); return true; } void GDScriptParser::_parse_extends(ClassNode *p_class) { if (p_class->extends_used) { _set_error("\"extends\" can only be present once per script."); return; } if (!p_class->constant_expressions.empty() || !p_class->subclasses.empty() || !p_class->functions.empty() || !p_class->variables.empty()) { _set_error("\"extends\" must be used before anything else."); return; } p_class->extends_used = true; tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token_type() == Variant::OBJECT) { p_class->extends_class.push_back(Variant::get_type_name(Variant::OBJECT)); tokenizer->advance(); return; } // see if inheritance happens from a file if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT) { Variant constant = tokenizer->get_token_constant(); if (constant.get_type() != Variant::STRING) { _set_error("\"extends\" constant must be a string."); return; } p_class->extends_file = constant; tokenizer->advance(); // Add parent script as a dependency String parent = constant; if (parent.is_rel_path()) { parent = base_path.plus_file(parent).simplify_path(); } dependencies.push_back(parent); if (tokenizer->get_token() != GDScriptTokenizer::TK_PERIOD) { return; } else { tokenizer->advance(); } } while (true) { switch (tokenizer->get_token()) { case GDScriptTokenizer::TK_IDENTIFIER: { StringName identifier = tokenizer->get_token_identifier(); p_class->extends_class.push_back(identifier); } break; case GDScriptTokenizer::TK_CURSOR: case GDScriptTokenizer::TK_PERIOD: break; default: { _set_error("Invalid \"extends\" syntax, expected string constant (path) and/or identifier (parent class)."); return; } } tokenizer->advance(1); switch (tokenizer->get_token()) { case GDScriptTokenizer::TK_IDENTIFIER: case GDScriptTokenizer::TK_PERIOD: continue; case GDScriptTokenizer::TK_CURSOR: completion_type = COMPLETION_EXTENDS; completion_class = current_class; completion_function = current_function; completion_line = tokenizer->get_token_line(); completion_block = current_block; completion_ident_is_call = false; completion_found = true; return; default: return; } } } void GDScriptParser::_parse_class(ClassNode *p_class) { IndentLevel current_level = indent_level.back()->get(); while (true) { GDScriptTokenizer::Token token = tokenizer->get_token(); if (error_set) { return; } if (current_level.indent > indent_level.back()->get().indent) { p_class->end_line = tokenizer->get_token_line(); return; //go back a level } switch (token) { case GDScriptTokenizer::TK_CURSOR: { tokenizer->advance(); } break; case GDScriptTokenizer::TK_EOF: p_class->end_line = tokenizer->get_token_line(); case GDScriptTokenizer::TK_ERROR: { return; //go back //end of file! } break; case GDScriptTokenizer::TK_NEWLINE: { if (!_parse_newline()) { if (!error_set) { p_class->end_line = tokenizer->get_token_line(); } return; } } break; case GDScriptTokenizer::TK_PR_EXTENDS: { _mark_line_as_safe(tokenizer->get_token_line()); _parse_extends(p_class); if (error_set) { return; } if (!_end_statement()) { _set_end_statement_error("extends"); return; } } break; case GDScriptTokenizer::TK_PR_CLASS_NAME: { _mark_line_as_safe(tokenizer->get_token_line()); if (p_class->owner) { _set_error("\"class_name\" is only valid for the main class namespace."); return; } if (self_path.begins_with("res://") && self_path.find("::") != -1) { _set_error("\"class_name\" isn't allowed in built-in scripts."); return; } if (tokenizer->get_token(1) != GDScriptTokenizer::TK_IDENTIFIER) { _set_error("\"class_name\" syntax: \"class_name <UniqueName>\""); return; } if (p_class->classname_used) { _set_error("\"class_name\" can only be present once per script."); return; } p_class->classname_used = true; p_class->name = tokenizer->get_token_identifier(1); if (self_path != String() && ScriptServer::is_global_class(p_class->name) && ScriptServer::get_global_class_path(p_class->name) != self_path) { _set_error("Unique global class \"" + p_class->name + "\" already exists at path: " + ScriptServer::get_global_class_path(p_class->name)); return; } if (ClassDB::class_exists(p_class->name)) { _set_error("The class \"" + p_class->name + "\" shadows a native class."); return; } if (p_class->classname_used && ProjectSettings::get_singleton()->has_setting("autoload/" + p_class->name)) { const String autoload_path = ProjectSettings::get_singleton()->get_setting("autoload/" + p_class->name); if (autoload_path.begins_with("*")) { // It's a singleton, and not just a regular AutoLoad script. _set_error("The class \"" + p_class->name + "\" conflicts with the AutoLoad singleton of the same name, and is therefore redundant. Remove the class_name declaration to fix this error."); } return; } tokenizer->advance(2); if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { tokenizer->advance(); if ((tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING)) { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { Variant constant = tokenizer->get_token_constant(); String icon_path = constant.operator String(); String abs_icon_path = icon_path.is_rel_path() ? self_path.get_base_dir().plus_file(icon_path).simplify_path() : icon_path; if (!FileAccess::exists(abs_icon_path)) { _set_error("No class icon found at: " + abs_icon_path); return; } p_class->icon_path = icon_path; } #endif tokenizer->advance(); } else { _set_error("The optional parameter after \"class_name\" must be a string constant file path to an icon."); return; } } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT) { _set_error("The class icon must be separated by a comma."); return; } } break; case GDScriptTokenizer::TK_PR_TOOL: { if (p_class->tool) { _set_error("The \"tool\" keyword can only be present once per script."); return; } p_class->tool = true; tokenizer->advance(); } break; case GDScriptTokenizer::TK_PR_CLASS: { //class inside class :D StringName name; if (tokenizer->get_token(1) != GDScriptTokenizer::TK_IDENTIFIER) { _set_error("\"class\" syntax: \"class <Name>:\" or \"class <Name> extends <BaseClass>:\""); return; } name = tokenizer->get_token_identifier(1); tokenizer->advance(2); // Check if name is shadowing something else if (ClassDB::class_exists(name) || ClassDB::class_exists("_" + name.operator String())) { _set_error("The class \"" + String(name) + "\" shadows a native class."); return; } if (ScriptServer::is_global_class(name)) { _set_error("Can't override name of the unique global class \"" + name + "\". It already exists at: " + ScriptServer::get_global_class_path(p_class->name)); return; } ClassNode *outer_class = p_class; while (outer_class) { for (int i = 0; i < outer_class->subclasses.size(); i++) { if (outer_class->subclasses[i]->name == name) { _set_error("Another class named \"" + String(name) + "\" already exists in this scope (at line " + itos(outer_class->subclasses[i]->line) + ")."); return; } } if (outer_class->constant_expressions.has(name)) { _set_error("A constant named \"" + String(name) + "\" already exists in the outer class scope (at line" + itos(outer_class->constant_expressions[name].expression->line) + ")."); return; } for (int i = 0; i < outer_class->variables.size(); i++) { if (outer_class->variables[i].identifier == name) { _set_error("A variable named \"" + String(name) + "\" already exists in the outer class scope (at line " + itos(outer_class->variables[i].line) + ")."); return; } } outer_class = outer_class->owner; } ClassNode *newclass = alloc_node<ClassNode>(); newclass->initializer = alloc_node<BlockNode>(); newclass->initializer->parent_class = newclass; newclass->ready = alloc_node<BlockNode>(); newclass->ready->parent_class = newclass; newclass->name = name; newclass->owner = p_class; p_class->subclasses.push_back(newclass); if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_EXTENDS) { _parse_extends(newclass); if (error_set) { return; } } if (!_enter_indent_block()) { _set_error("Indented block expected."); return; } current_class = newclass; _parse_class(newclass); current_class = p_class; } break; /* this is for functions.... case GDScriptTokenizer::TK_CF_PASS: { tokenizer->advance(1); } break; */ case GDScriptTokenizer::TK_PR_STATIC: { tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { _set_error("Expected \"func\"."); return; } FALLTHROUGH; } case GDScriptTokenizer::TK_PR_FUNCTION: { bool _static = false; pending_newline = -1; if (tokenizer->get_token(-1) == GDScriptTokenizer::TK_PR_STATIC) { _static = true; } tokenizer->advance(); StringName name; if (_get_completable_identifier(COMPLETION_VIRTUAL_FUNC, name)) { } if (name == StringName()) { _set_error("Expected an identifier after \"func\" (syntax: \"func <identifier>([arguments]):\")."); return; } for (int i = 0; i < p_class->functions.size(); i++) { if (p_class->functions[i]->name == name) { _set_error("The function \"" + String(name) + "\" already exists in this class (at line " + itos(p_class->functions[i]->line) + ")."); } } for (int i = 0; i < p_class->static_functions.size(); i++) { if (p_class->static_functions[i]->name == name) { _set_error("The function \"" + String(name) + "\" already exists in this class (at line " + itos(p_class->static_functions[i]->line) + ")."); } } #ifdef DEBUG_ENABLED if (p_class->constant_expressions.has(name)) { _add_warning(GDScriptWarning::FUNCTION_CONFLICTS_CONSTANT, -1, name); } for (int i = 0; i < p_class->variables.size(); i++) { if (p_class->variables[i].identifier == name) { _add_warning(GDScriptWarning::FUNCTION_CONFLICTS_VARIABLE, -1, name); } } for (int i = 0; i < p_class->subclasses.size(); i++) { if (p_class->subclasses[i]->name == name) { _add_warning(GDScriptWarning::FUNCTION_CONFLICTS_CONSTANT, -1, name); } } #endif // DEBUG_ENABLED if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) { _set_error("Expected \"(\" after the identifier (syntax: \"func <identifier>([arguments]):\" )."); return; } tokenizer->advance(); Vector<StringName> arguments; Vector<DataType> argument_types; Vector<Node *> default_values; #ifdef DEBUG_ENABLED Vector<int> arguments_usage; #endif // DEBUG_ENABLED int fnline = tokenizer->get_token_line(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { //has arguments bool defaulting = false; while (true) { if (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) { tokenizer->advance(); continue; } if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_VAR) { tokenizer->advance(); //var before the identifier is allowed } if (!tokenizer->is_token_literal(0, true)) { _set_error("Expected an identifier for an argument."); return; } StringName argname = tokenizer->get_token_identifier(); for (int i = 0; i < arguments.size(); i++) { if (arguments[i] == argname) { _set_error("The argument name \"" + String(argname) + "\" is defined multiple times."); return; } } arguments.push_back(argname); #ifdef DEBUG_ENABLED arguments_usage.push_back(0); #endif // DEBUG_ENABLED tokenizer->advance(); DataType argtype; if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) { if (tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) { argtype.infer_type = true; tokenizer->advance(); } else if (!_parse_type(argtype)) { _set_error("Expected a type for an argument."); return; } } argument_types.push_back(argtype); if (defaulting && tokenizer->get_token() != GDScriptTokenizer::TK_OP_ASSIGN) { _set_error("Default parameter expected."); return; } //tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_ASSIGN) { defaulting = true; tokenizer->advance(1); Node *defval = _parse_and_reduce_expression(p_class, _static); if (!defval || error_set) { return; } OperatorNode *on = alloc_node<OperatorNode>(); on->op = OperatorNode::OP_ASSIGN; on->line = fnline; IdentifierNode *in = alloc_node<IdentifierNode>(); in->name = argname; in->line = fnline; on->arguments.push_back(in); on->arguments.push_back(defval); /* no .. if (defval->type!=Node::TYPE_CONSTANT) { _set_error("default argument must be constant"); } */ default_values.push_back(on); } while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) { tokenizer->advance(); } if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { tokenizer->advance(); continue; } else if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected \",\" or \")\"."); return; } break; } } tokenizer->advance(); BlockNode *block = alloc_node<BlockNode>(); block->parent_class = p_class; FunctionNode *function = alloc_node<FunctionNode>(); function->name = name; function->arguments = arguments; function->argument_types = argument_types; function->default_values = default_values; function->_static = _static; function->line = fnline; #ifdef DEBUG_ENABLED function->arguments_usage = arguments_usage; #endif // DEBUG_ENABLED function->rpc_mode = rpc_mode; rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED; if (name == "_init") { if (_static) { _set_error("The constructor cannot be static."); return; } if (p_class->extends_used) { OperatorNode *cparent = alloc_node<OperatorNode>(); cparent->op = OperatorNode::OP_PARENT_CALL; block->statements.push_back(cparent); IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = "_init"; cparent->arguments.push_back(id); if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD) { tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) { _set_error("Expected \"(\" for parent constructor arguments."); return; } tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { //has arguments parenthesis++; while (true) { current_function = function; Node *arg = _parse_and_reduce_expression(p_class, _static); if (!arg) { return; } current_function = nullptr; cparent->arguments.push_back(arg); if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { tokenizer->advance(); continue; } else if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected \",\" or \")\"."); return; } break; } parenthesis--; } tokenizer->advance(); } } else { if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD) { _set_error("Parent constructor call found for a class without inheritance."); return; } } } DataType return_type; if (tokenizer->get_token() == GDScriptTokenizer::TK_FORWARD_ARROW) { if (!_parse_type(return_type, true)) { _set_error("Expected a return type for the function."); return; } } if (!_enter_indent_block(block)) { _set_error(vformat("Indented block expected after declaration of \"%s\" function.", function->name)); return; } function->return_type = return_type; if (_static) { p_class->static_functions.push_back(function); } else { p_class->functions.push_back(function); } current_function = function; function->body = block; current_block = block; _parse_block(block, _static); current_block = nullptr; //arguments } break; case GDScriptTokenizer::TK_PR_SIGNAL: { _mark_line_as_safe(tokenizer->get_token_line()); tokenizer->advance(); if (!tokenizer->is_token_literal()) { _set_error("Expected an identifier after \"signal\"."); return; } ClassNode::Signal sig; sig.name = tokenizer->get_token_identifier(); sig.emissions = 0; sig.line = tokenizer->get_token_line(); for (int i = 0; i < current_class->_signals.size(); i++) { if (current_class->_signals[i].name == sig.name) { _set_error("The signal \"" + sig.name + "\" already exists in this class (at line: " + itos(current_class->_signals[i].line) + ")."); return; } } tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_OPEN) { tokenizer->advance(); while (true) { if (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) { tokenizer->advance(); continue; } if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { tokenizer->advance(); break; } if (!tokenizer->is_token_literal(0, true)) { _set_error("Expected an identifier in a \"signal\" argument."); return; } sig.arguments.push_back(tokenizer->get_token_identifier()); tokenizer->advance(); while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) { tokenizer->advance(); } if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { tokenizer->advance(); } else if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected \",\" or \")\" after a \"signal\" parameter identifier."); return; } } } p_class->_signals.push_back(sig); if (!_end_statement()) { _set_end_statement_error("signal"); return; } } break; case GDScriptTokenizer::TK_PR_EXPORT: { tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_OPEN) { #define _ADVANCE_AND_CONSUME_NEWLINES \ do { \ tokenizer->advance(); \ } while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) _ADVANCE_AND_CONSUME_NEWLINES; parenthesis++; String hint_prefix = ""; bool is_arrayed = false; while (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token_type() == Variant::ARRAY && tokenizer->get_token(1) == GDScriptTokenizer::TK_COMMA) { tokenizer->advance(); // Array tokenizer->advance(); // Comma if (is_arrayed) { hint_prefix += itos(Variant::ARRAY) + ":"; } else { is_arrayed = true; } } if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_TYPE) { Variant::Type type = tokenizer->get_token_type(); if (type == Variant::NIL) { _set_error("Can't export null type."); return; } if (type == Variant::OBJECT) { _set_error("Can't export raw object type."); return; } current_export.type = type; current_export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { // hint expected next! _ADVANCE_AND_CONSUME_NEWLINES; switch (type) { case Variant::INT: { if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "FLAGS") { _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { WARN_DEPRECATED_MSG("Exporting bit flags hint requires string constants."); break; } if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { _set_error("Expected \",\" in the bit flags hint."); return; } current_export.hint = PROPERTY_HINT_FLAGS; _ADVANCE_AND_CONSUME_NEWLINES; bool first = true; while (true) { if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { current_export = PropertyInfo(); _set_error("Expected a string constant in the named bit flags hint."); return; } String c = tokenizer->get_token_constant(); if (!first) { current_export.hint_string += ","; } else { first = false; } current_export.hint_string += c.xml_escape(); _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { break; } if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { current_export = PropertyInfo(); _set_error("Expected \")\" or \",\" in the named bit flags hint."); return; } _ADVANCE_AND_CONSUME_NEWLINES; } break; } if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "LAYERS_2D_RENDER") { _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected \")\" in the layers 2D render hint."); return; } current_export.hint = PROPERTY_HINT_LAYERS_2D_RENDER; break; } if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "LAYERS_2D_PHYSICS") { _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected \")\" in the layers 2D physics hint."); return; } current_export.hint = PROPERTY_HINT_LAYERS_2D_PHYSICS; break; } if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "LAYERS_3D_RENDER") { _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected \")\" in the layers 3D render hint."); return; } current_export.hint = PROPERTY_HINT_LAYERS_3D_RENDER; break; } if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "LAYERS_3D_PHYSICS") { _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected \")\" in the layers 3D physics hint."); return; } current_export.hint = PROPERTY_HINT_LAYERS_3D_PHYSICS; break; } if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING) { //enumeration current_export.hint = PROPERTY_HINT_ENUM; bool first = true; while (true) { if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { current_export = PropertyInfo(); _set_error("Expected a string constant in the enumeration hint."); return; } String c = tokenizer->get_token_constant(); if (!first) { current_export.hint_string += ","; } else { first = false; } current_export.hint_string += c.xml_escape(); _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { break; } if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { current_export = PropertyInfo(); _set_error("Expected \")\" or \",\" in the enumeration hint."); return; } _ADVANCE_AND_CONSUME_NEWLINES; } break; } FALLTHROUGH; } case Variant::REAL: { if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "EASE") { current_export.hint = PROPERTY_HINT_EXP_EASING; _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected \")\" in the hint."); return; } break; } // range if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "EXP") { current_export.hint = PROPERTY_HINT_EXP_RANGE; _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { break; } else if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { _set_error("Expected \")\" or \",\" in the exponential range hint."); return; } _ADVANCE_AND_CONSUME_NEWLINES; } else { current_export.hint = PROPERTY_HINT_RANGE; } float sign = 1.0; if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_SUB) { sign = -1; _ADVANCE_AND_CONSUME_NEWLINES; } if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { current_export = PropertyInfo(); _set_error("Expected a range in the numeric hint."); return; } current_export.hint_string = rtos(sign * double(tokenizer->get_token_constant())); _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { current_export.hint_string = "0," + current_export.hint_string; break; } if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { current_export = PropertyInfo(); _set_error("Expected \",\" or \")\" in the numeric range hint."); return; } _ADVANCE_AND_CONSUME_NEWLINES; sign = 1.0; if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_SUB) { sign = -1; _ADVANCE_AND_CONSUME_NEWLINES; } if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { current_export = PropertyInfo(); _set_error("Expected a number as upper bound in the numeric range hint."); return; } current_export.hint_string += "," + rtos(sign * double(tokenizer->get_token_constant())); _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { break; } if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { current_export = PropertyInfo(); _set_error("Expected \",\" or \")\" in the numeric range hint."); return; } _ADVANCE_AND_CONSUME_NEWLINES; sign = 1.0; if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_SUB) { sign = -1; _ADVANCE_AND_CONSUME_NEWLINES; } if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { current_export = PropertyInfo(); _set_error("Expected a number as step in the numeric range hint."); return; } current_export.hint_string += "," + rtos(sign * double(tokenizer->get_token_constant())); _ADVANCE_AND_CONSUME_NEWLINES; } break; case Variant::STRING: { if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING) { //enumeration current_export.hint = PROPERTY_HINT_ENUM; bool first = true; while (true) { if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { current_export = PropertyInfo(); _set_error("Expected a string constant in the enumeration hint."); return; } String c = tokenizer->get_token_constant(); if (!first) { current_export.hint_string += ","; } else { first = false; } current_export.hint_string += c.xml_escape(); _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { break; } if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { current_export = PropertyInfo(); _set_error("Expected \")\" or \",\" in the enumeration hint."); return; } _ADVANCE_AND_CONSUME_NEWLINES; } break; } if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "DIR") { _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { current_export.hint = PROPERTY_HINT_DIR; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() != GDScriptTokenizer::TK_IDENTIFIER || !(tokenizer->get_token_identifier() == "GLOBAL")) { _set_error("Expected \"GLOBAL\" after comma in the directory hint."); return; } if (!p_class->tool) { _set_error("Global filesystem hints may only be used in tool scripts."); return; } current_export.hint = PROPERTY_HINT_GLOBAL_DIR; _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected \")\" in the hint."); return; } } else { _set_error("Expected \")\" or \",\" in the hint."); return; } break; } if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "FILE") { current_export.hint = PROPERTY_HINT_FILE; _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "GLOBAL") { if (!p_class->tool) { _set_error("Global filesystem hints may only be used in tool scripts."); return; } current_export.hint = PROPERTY_HINT_GLOBAL_FILE; _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { break; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { _ADVANCE_AND_CONSUME_NEWLINES; } else { _set_error("Expected \")\" or \",\" in the hint."); return; } } if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { if (current_export.hint == PROPERTY_HINT_GLOBAL_FILE) { _set_error("Expected string constant with filter."); } else { _set_error("Expected \"GLOBAL\" or string constant with filter."); } return; } current_export.hint_string = tokenizer->get_token_constant(); _ADVANCE_AND_CONSUME_NEWLINES; } if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected \")\" in the hint."); return; } break; } if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "MULTILINE") { current_export.hint = PROPERTY_HINT_MULTILINE_TEXT; _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected \")\" in the hint."); return; } break; } } break; case Variant::COLOR: { if (tokenizer->get_token() != GDScriptTokenizer::TK_IDENTIFIER) { current_export = PropertyInfo(); _set_error("Color type hint expects RGB or RGBA as hints."); return; } String identifier = tokenizer->get_token_identifier(); if (identifier == "RGB") { current_export.hint = PROPERTY_HINT_COLOR_NO_ALPHA; } else if (identifier == "RGBA") { //none } else { current_export = PropertyInfo(); _set_error("Color type hint expects RGB or RGBA as hints."); return; } _ADVANCE_AND_CONSUME_NEWLINES; } break; default: { current_export = PropertyInfo(); _set_error("Type \"" + Variant::get_type_name(type) + "\" can't take hints."); return; } break; } } } else { parenthesis++; Node *subexpr = _parse_and_reduce_expression(p_class, true, true); if (!subexpr) { if (_recover_from_completion()) { break; } return; } parenthesis--; if (subexpr->type != Node::TYPE_CONSTANT) { current_export = PropertyInfo(); _set_error("Expected a constant expression."); return; } Variant constant = static_cast<ConstantNode *>(subexpr)->value; if (constant.get_type() == Variant::OBJECT) { GDScriptNativeClass *native_class = Object::cast_to<GDScriptNativeClass>(constant); if (native_class && ClassDB::is_parent_class(native_class->get_name(), "Resource")) { current_export.type = Variant::OBJECT; current_export.hint = PROPERTY_HINT_RESOURCE_TYPE; current_export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; current_export.hint_string = native_class->get_name(); current_export.class_name = native_class->get_name(); } else { current_export = PropertyInfo(); _set_error("The export hint isn't a resource type."); } } else if (constant.get_type() == Variant::DICTIONARY) { // Enumeration bool is_flags = false; if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { _ADVANCE_AND_CONSUME_NEWLINES; if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "FLAGS") { is_flags = true; _ADVANCE_AND_CONSUME_NEWLINES; } else { current_export = PropertyInfo(); _set_error("Expected \"FLAGS\" after comma."); } } current_export.type = Variant::INT; current_export.hint = is_flags ? PROPERTY_HINT_FLAGS : PROPERTY_HINT_ENUM; current_export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; Dictionary enum_values = constant; List<Variant> keys; enum_values.get_key_list(&keys); bool first = true; for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { if (enum_values[E->get()].get_type() == Variant::INT) { if (!first) { current_export.hint_string += ","; } else { first = false; } current_export.hint_string += E->get().operator String().capitalize().xml_escape(); if (!is_flags) { current_export.hint_string += ":"; current_export.hint_string += enum_values[E->get()].operator String().xml_escape(); } } } } else { current_export = PropertyInfo(); _set_error("Expected type for export."); return; } } if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { current_export = PropertyInfo(); _set_error("Expected \")\" or \",\" after the export hint."); return; } tokenizer->advance(); parenthesis--; if (is_arrayed) { hint_prefix += itos(current_export.type); if (current_export.hint) { hint_prefix += "/" + itos(current_export.hint); } current_export.hint_string = hint_prefix + ":" + current_export.hint_string; current_export.hint = PROPERTY_HINT_TYPE_STRING; current_export.type = Variant::ARRAY; } #undef _ADVANCE_AND_CONSUME_NEWLINES } if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_ONREADY && tokenizer->get_token() != GDScriptTokenizer::TK_PR_REMOTE && tokenizer->get_token() != GDScriptTokenizer::TK_PR_MASTER && tokenizer->get_token() != GDScriptTokenizer::TK_PR_PUPPET && tokenizer->get_token() != GDScriptTokenizer::TK_PR_SYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_REMOTESYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_MASTERSYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_PUPPETSYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_SLAVE) { current_export = PropertyInfo(); _set_error("Expected \"var\", \"onready\", \"remote\", \"master\", \"puppet\", \"sync\", \"remotesync\", \"mastersync\", \"puppetsync\"."); return; } continue; } break; case GDScriptTokenizer::TK_PR_ONREADY: { //may be fallthrough from export, ignore if so tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) { _set_error("Expected \"var\"."); return; } continue; } break; case GDScriptTokenizer::TK_PR_REMOTE: { //may be fallthrough from export, ignore if so tokenizer->advance(); if (current_export.type) { if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) { _set_error("Expected \"var\"."); return; } } else { if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { _set_error("Expected \"var\" or \"func\"."); return; } } rpc_mode = MultiplayerAPI::RPC_MODE_REMOTE; continue; } break; case GDScriptTokenizer::TK_PR_MASTER: { //may be fallthrough from export, ignore if so tokenizer->advance(); if (current_export.type) { if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) { _set_error("Expected \"var\"."); return; } } else { if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { _set_error("Expected \"var\" or \"func\"."); return; } } rpc_mode = MultiplayerAPI::RPC_MODE_MASTER; continue; } break; case GDScriptTokenizer::TK_PR_SLAVE: #ifdef DEBUG_ENABLED _add_warning(GDScriptWarning::DEPRECATED_KEYWORD, tokenizer->get_token_line(), "slave", "puppet"); #endif FALLTHROUGH; case GDScriptTokenizer::TK_PR_PUPPET: { //may be fallthrough from export, ignore if so tokenizer->advance(); if (current_export.type) { if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) { _set_error("Expected \"var\"."); return; } } else { if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { _set_error("Expected \"var\" or \"func\"."); return; } } rpc_mode = MultiplayerAPI::RPC_MODE_PUPPET; continue; } break; case GDScriptTokenizer::TK_PR_REMOTESYNC: case GDScriptTokenizer::TK_PR_SYNC: { //may be fallthrough from export, ignore if so tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { if (current_export.type) { _set_error("Expected \"var\"."); } else { _set_error("Expected \"var\" or \"func\"."); } return; } rpc_mode = MultiplayerAPI::RPC_MODE_REMOTESYNC; continue; } break; case GDScriptTokenizer::TK_PR_MASTERSYNC: { //may be fallthrough from export, ignore if so tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { if (current_export.type) { _set_error("Expected \"var\"."); } else { _set_error("Expected \"var\" or \"func\"."); } return; } rpc_mode = MultiplayerAPI::RPC_MODE_MASTERSYNC; continue; } break; case GDScriptTokenizer::TK_PR_PUPPETSYNC: { //may be fallthrough from export, ignore if so tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { if (current_export.type) { _set_error("Expected \"var\"."); } else { _set_error("Expected \"var\" or \"func\"."); } return; } rpc_mode = MultiplayerAPI::RPC_MODE_PUPPETSYNC; continue; } break; case GDScriptTokenizer::TK_PR_VAR: { // variable declaration and (eventual) initialization ClassNode::Member member; bool autoexport = tokenizer->get_token(-1) == GDScriptTokenizer::TK_PR_EXPORT; if (current_export.type != Variant::NIL) { member._export = current_export; current_export = PropertyInfo(); } bool onready = tokenizer->get_token(-1) == GDScriptTokenizer::TK_PR_ONREADY; tokenizer->advance(); if (!tokenizer->is_token_literal(0, true)) { _set_error("Expected an identifier for the member variable name."); return; } member.identifier = tokenizer->get_token_literal(); member.expression = nullptr; member._export.name = member.identifier; member.line = tokenizer->get_token_line(); member.usages = 0; member.rpc_mode = rpc_mode; if (current_class->constant_expressions.has(member.identifier)) { _set_error("A constant named \"" + String(member.identifier) + "\" already exists in this class (at line: " + itos(current_class->constant_expressions[member.identifier].expression->line) + ")."); return; } for (int i = 0; i < current_class->variables.size(); i++) { if (current_class->variables[i].identifier == member.identifier) { _set_error("Variable \"" + String(member.identifier) + "\" already exists in this class (at line: " + itos(current_class->variables[i].line) + ")."); return; } } for (int i = 0; i < current_class->subclasses.size(); i++) { if (current_class->subclasses[i]->name == member.identifier) { _set_error("A class named \"" + String(member.identifier) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ")."); return; } } #ifdef DEBUG_ENABLED for (int i = 0; i < current_class->functions.size(); i++) { if (current_class->functions[i]->name == member.identifier) { _add_warning(GDScriptWarning::VARIABLE_CONFLICTS_FUNCTION, member.line, member.identifier); break; } } for (int i = 0; i < current_class->static_functions.size(); i++) { if (current_class->static_functions[i]->name == member.identifier) { _add_warning(GDScriptWarning::VARIABLE_CONFLICTS_FUNCTION, member.line, member.identifier); break; } } #endif // DEBUG_ENABLED tokenizer->advance(); rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED; if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) { if (tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) { member.data_type = DataType(); member.data_type.infer_type = true; tokenizer->advance(); } else if (!_parse_type(member.data_type)) { _set_error("Expected a type for the class variable."); return; } } if (autoexport && member.data_type.has_type) { if (member.data_type.kind == DataType::BUILTIN) { member._export.type = member.data_type.builtin_type; } else if (member.data_type.kind == DataType::NATIVE) { if (ClassDB::is_parent_class(member.data_type.native_type, "Resource")) { member._export.type = Variant::OBJECT; member._export.hint = PROPERTY_HINT_RESOURCE_TYPE; member._export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; member._export.hint_string = member.data_type.native_type; member._export.class_name = member.data_type.native_type; } else { _set_error("Invalid export type. Only built-in and native resource types can be exported.", member.line); return; } } else { _set_error("Invalid export type. Only built-in and native resource types can be exported.", member.line); return; } } #ifdef TOOLS_ENABLED Variant::CallError ce; member.default_value = Variant::construct(member._export.type, nullptr, 0, ce); #endif if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_ASSIGN) { #ifdef DEBUG_ENABLED int line = tokenizer->get_token_line(); #endif tokenizer->advance(); Node *subexpr = _parse_and_reduce_expression(p_class, false, autoexport || member._export.type != Variant::NIL); if (!subexpr) { if (_recover_from_completion()) { break; } return; } //discourage common error if (!onready && subexpr->type == Node::TYPE_OPERATOR) { OperatorNode *op = static_cast<OperatorNode *>(subexpr); if (op->op == OperatorNode::OP_CALL && op->arguments[0]->type == Node::TYPE_SELF && op->arguments[1]->type == Node::TYPE_IDENTIFIER) { IdentifierNode *id = static_cast<IdentifierNode *>(op->arguments[1]); // GOBLIN ENGINE onready warning if (id->name == "get_node" || id->name == "get_child" || id->name == "get_parent") { _set_error("Use \"onready var " + String(member.identifier) + " = " + id->name + "(...)\" instead."); error_line = op->line; return; } } } member.expression = subexpr; if (autoexport && !member.data_type.has_type) { if (subexpr->type != Node::TYPE_CONSTANT) { _set_error("Type-less export needs a constant expression assigned to infer type."); return; } ConstantNode *cn = static_cast<ConstantNode *>(subexpr); if (cn->value.get_type() == Variant::NIL) { _set_error("Can't accept a null constant expression for inferring export type."); return; } if (!_reduce_export_var_type(cn->value, member.line)) { return; } member._export.type = cn->value.get_type(); member._export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; if (cn->value.get_type() == Variant::OBJECT) { Object *obj = cn->value; Resource *res = Object::cast_to<Resource>(obj); if (res == nullptr) { _set_error("The exported constant isn't a type or resource."); return; } member._export.hint = PROPERTY_HINT_RESOURCE_TYPE; member._export.hint_string = res->get_class(); } } #ifdef TOOLS_ENABLED // Warn if the default value set is not the same as the export type, since it won't be coerced and // may create wrong expectations. if (subexpr->type == Node::TYPE_CONSTANT && (member._export.type != Variant::NIL || member.data_type.has_type)) { ConstantNode *cn = static_cast<ConstantNode *>(subexpr); if (cn->value.get_type() != Variant::NIL) { if (member._export.type != Variant::NIL && cn->value.get_type() != member._export.type) { if (!Variant::can_convert(cn->value.get_type(), member._export.type)) { _set_error("Can't convert the provided value to the export type."); return; } else if (!member.data_type.has_type) { _add_warning(GDScriptWarning::EXPORT_HINT_TYPE_MISTMATCH, member.line, Variant::get_type_name(cn->value.get_type()), Variant::get_type_name(member._export.type)); } } } member.default_value = cn->value; } #endif IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = member.identifier; id->datatype = member.data_type; OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_INIT_ASSIGN; op->arguments.push_back(id); op->arguments.push_back(subexpr); #ifdef DEBUG_ENABLED NewLineNode *nl2 = alloc_node<NewLineNode>(); nl2->line = line; if (onready) { p_class->ready->statements.push_back(nl2); } else { p_class->initializer->statements.push_back(nl2); } #endif if (onready) { p_class->ready->statements.push_back(op); } else { p_class->initializer->statements.push_back(op); } member.initial_assignment = op; } else { if (autoexport && !member.data_type.has_type) { _set_error("Type-less export needs a constant expression assigned to infer type."); return; } Node *expr; if (member.data_type.has_type) { expr = _get_default_value_for_type(member.data_type); } else { DataType exported_type; exported_type.has_type = true; exported_type.kind = DataType::BUILTIN; exported_type.builtin_type = member._export.type; expr = _get_default_value_for_type(exported_type); } IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = member.identifier; id->datatype = member.data_type; OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_INIT_ASSIGN; op->arguments.push_back(id); op->arguments.push_back(expr); p_class->initializer->statements.push_back(op); member.initial_assignment = op; } if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_SETGET) { tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { //just comma means using only getter if (!tokenizer->is_token_literal()) { _set_error("Expected an identifier for the setter function after \"setget\"."); } member.setter = tokenizer->get_token_literal(); tokenizer->advance(); } if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { //there is a getter tokenizer->advance(); if (!tokenizer->is_token_literal()) { _set_error("Expected an identifier for the getter function after \",\"."); } member.getter = tokenizer->get_token_literal(); tokenizer->advance(); } } p_class->variables.push_back(member); if (!_end_statement()) { _set_end_statement_error("var"); return; } } break; case GDScriptTokenizer::TK_PR_CONST: { // constant declaration and initialization ClassNode::Constant constant; tokenizer->advance(); if (!tokenizer->is_token_literal(0, true)) { _set_error("Expected an identifier for the constant."); return; } StringName const_id = tokenizer->get_token_literal(); int line = tokenizer->get_token_line(); if (current_class->constant_expressions.has(const_id)) { _set_error("Constant \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->constant_expressions[const_id].expression->line) + ")."); return; } for (int i = 0; i < current_class->variables.size(); i++) { if (current_class->variables[i].identifier == const_id) { _set_error("A variable named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->variables[i].line) + ")."); return; } } for (int i = 0; i < current_class->subclasses.size(); i++) { if (current_class->subclasses[i]->name == const_id) { _set_error("A class named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ")."); return; } } tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) { if (tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) { constant.type = DataType(); constant.type.infer_type = true; tokenizer->advance(); } else if (!_parse_type(constant.type)) { _set_error("Expected a type for the class constant."); return; } } if (tokenizer->get_token() != GDScriptTokenizer::TK_OP_ASSIGN) { _set_error("Constants must be assigned immediately."); return; } tokenizer->advance(); Node *subexpr = _parse_and_reduce_expression(p_class, true, true); if (!subexpr) { if (_recover_from_completion()) { break; } return; } if (subexpr->type != Node::TYPE_CONSTANT) { _set_error("Expected a constant expression.", line); return; } subexpr->line = line; constant.expression = subexpr; p_class->constant_expressions.insert(const_id, constant); if (!_end_statement()) { _set_end_statement_error("const"); return; } } break; case GDScriptTokenizer::TK_PR_ENUM: { //multiple constant declarations.. int last_assign = -1; // Incremented by 1 right before the assignment. String enum_name; Dictionary enum_dict; int enum_start_line = tokenizer->get_token_line(); tokenizer->advance(); if (tokenizer->is_token_literal(0, true)) { enum_name = tokenizer->get_token_literal(); if (current_class->constant_expressions.has(enum_name)) { _set_error("A constant named \"" + String(enum_name) + "\" already exists in this class (at line " + itos(current_class->constant_expressions[enum_name].expression->line) + ")."); return; } for (int i = 0; i < current_class->variables.size(); i++) { if (current_class->variables[i].identifier == enum_name) { _set_error("A variable named \"" + String(enum_name) + "\" already exists in this class (at line " + itos(current_class->variables[i].line) + ")."); return; } } for (int i = 0; i < current_class->subclasses.size(); i++) { if (current_class->subclasses[i]->name == enum_name) { _set_error("A class named \"" + String(enum_name) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ")."); return; } } tokenizer->advance(); } if (tokenizer->get_token() != GDScriptTokenizer::TK_CURLY_BRACKET_OPEN) { _set_error("Expected \"{\" in the enum declaration."); return; } tokenizer->advance(); while (true) { if (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) { tokenizer->advance(); // Ignore newlines } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CURLY_BRACKET_CLOSE) { tokenizer->advance(); break; // End of enum } else if (!tokenizer->is_token_literal(0, true)) { if (tokenizer->get_token() == GDScriptTokenizer::TK_EOF) { _set_error("Unexpected end of file."); } else { _set_error(String("Unexpected ") + GDScriptTokenizer::get_token_name(tokenizer->get_token()) + ", expected an identifier."); } return; } else { // tokenizer->is_token_literal(0, true) StringName const_id = tokenizer->get_token_literal(); tokenizer->advance(); ConstantNode *enum_value_expr; if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_ASSIGN) { tokenizer->advance(); Node *subexpr = _parse_and_reduce_expression(p_class, true, true); if (!subexpr) { if (_recover_from_completion()) { break; } return; } if (subexpr->type != Node::TYPE_CONSTANT) { _set_error("Expected a constant expression."); return; } enum_value_expr = static_cast<ConstantNode *>(subexpr); if (enum_value_expr->value.get_type() != Variant::INT) { _set_error("Expected an integer value for \"enum\"."); return; } last_assign = enum_value_expr->value; } else { last_assign = last_assign + 1; enum_value_expr = alloc_node<ConstantNode>(); enum_value_expr->value = last_assign; enum_value_expr->datatype = _type_from_variant(enum_value_expr->value); } if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { tokenizer->advance(); } else if (tokenizer->is_token_literal(0, true)) { _set_error("Unexpected identifier."); return; } if (enum_name != "") { enum_dict[const_id] = enum_value_expr->value; } else { if (current_class->constant_expressions.has(const_id)) { _set_error("A constant named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->constant_expressions[const_id].expression->line) + ")."); return; } for (int i = 0; i < current_class->variables.size(); i++) { if (current_class->variables[i].identifier == const_id) { _set_error("A variable named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->variables[i].line) + ")."); return; } } for (int i = 0; i < current_class->subclasses.size(); i++) { if (current_class->subclasses[i]->name == const_id) { _set_error("A class named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ")."); return; } } ClassNode::Constant constant; constant.type.has_type = true; constant.type.kind = DataType::BUILTIN; constant.type.builtin_type = Variant::INT; constant.expression = enum_value_expr; p_class->constant_expressions.insert(const_id, constant); } } } if (enum_name != "") { ClassNode::Constant enum_constant; ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = enum_dict; cn->datatype = _type_from_variant(cn->value); cn->line = enum_start_line; enum_constant.expression = cn; enum_constant.type = cn->datatype; p_class->constant_expressions.insert(enum_name, enum_constant); } if (!_end_statement()) { _set_end_statement_error("enum"); return; } } break; case GDScriptTokenizer::TK_CONSTANT: { if (tokenizer->get_token_constant().get_type() == Variant::STRING) { tokenizer->advance(); // Ignore } else { _set_error(String() + "Unexpected constant of type: " + Variant::get_type_name(tokenizer->get_token_constant().get_type())); return; } } break; case GDScriptTokenizer::TK_CF_PASS: { tokenizer->advance(); } break; default: { if (token == GDScriptTokenizer::TK_IDENTIFIER) { completion_type = COMPLETION_IDENTIFIER; completion_class = current_class; completion_function = current_function; completion_line = tokenizer->get_token_line(); completion_block = current_block; completion_ident_is_call = false; completion_found = true; } _set_error(String() + "Unexpected token: " + tokenizer->get_token_name(tokenizer->get_token()) + ":" + tokenizer->get_token_identifier()); return; } break; } } } void GDScriptParser::_determine_inheritance(ClassNode *p_class, bool p_recursive) { if (p_class->base_type.has_type) { // Already determined } else if (p_class->extends_used) { //do inheritance String path = p_class->extends_file; Ref<GDScript> script; StringName native; ClassNode *base_class = nullptr; if (path != "") { //path (and optionally subclasses) if (path.is_rel_path()) { String base = base_path; if (base == "" || base.is_rel_path()) { _set_error("Couldn't resolve relative path for the parent class: " + path, p_class->line); return; } path = base.plus_file(path).simplify_path(); } script = ResourceLoader::load(path); if (script.is_null()) { _set_error("Couldn't load the base class: " + path, p_class->line); return; } if (!script->is_valid()) { _set_error("Script isn't fully loaded (cyclic preload?): " + path, p_class->line); return; } if (p_class->extends_class.size()) { for (int i = 0; i < p_class->extends_class.size(); i++) { String sub = p_class->extends_class[i]; if (script->get_subclasses().has(sub)) { Ref<Script> subclass = script->get_subclasses()[sub]; //avoid reference from disappearing script = subclass; } else { _set_error("Couldn't find the subclass: " + sub, p_class->line); return; } } } } else { if (p_class->extends_class.size() == 0) { _set_error("Parser bug: undecidable inheritance.", p_class->line); ERR_FAIL(); } //look around for the subclasses int extend_iter = 1; String base = p_class->extends_class[0]; ClassNode *p = p_class->owner; Ref<GDScript> base_script; if (ScriptServer::is_global_class(base)) { base_script = ResourceLoader::load(ScriptServer::get_global_class_path(base)); if (!base_script.is_valid()) { _set_error("The class \"" + base + "\" couldn't be fully loaded (script error or cyclic dependency).", p_class->line); return; } p = nullptr; } else { List<PropertyInfo> props; ProjectSettings::get_singleton()->get_property_list(&props); for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { String s = E->get().name; if (!s.begins_with("autoload/")) { continue; } String name = s.get_slice("/", 1); if (name == base) { String singleton_path = ProjectSettings::get_singleton()->get(s); if (singleton_path.begins_with("*")) { singleton_path = singleton_path.right(1); } if (!singleton_path.begins_with("res://")) { singleton_path = "res://" + singleton_path; } base_script = ResourceLoader::load(singleton_path); if (!base_script.is_valid()) { _set_error("Class '" + base + "' could not be fully loaded (script error or cyclic inheritance).", p_class->line); return; } p = nullptr; } } } while (p) { bool found = false; for (int i = 0; i < p->subclasses.size(); i++) { if (p->subclasses[i]->name == base) { ClassNode *test = p->subclasses[i]; while (test) { if (test == p_class) { _set_error("Cyclic inheritance.", test->line); return; } if (test->base_type.kind == DataType::CLASS) { test = test->base_type.class_type; } else { break; } } found = true; if (extend_iter < p_class->extends_class.size()) { // Keep looking at current classes if possible base = p_class->extends_class[extend_iter++]; p = p->subclasses[i]; } else { base_class = p->subclasses[i]; } break; } } if (base_class) { break; } if (found) { continue; } if (p->constant_expressions.has(base)) { if (p->constant_expressions[base].expression->type != Node::TYPE_CONSTANT) { _set_error("Couldn't resolve the constant \"" + base + "\".", p_class->line); return; } const ConstantNode *cn = static_cast<const ConstantNode *>(p->constant_expressions[base].expression); base_script = cn->value; if (base_script.is_null()) { _set_error("Constant isn't a class: " + base, p_class->line); return; } break; } p = p->owner; } if (base_script.is_valid()) { String ident = base; Ref<GDScript> find_subclass = base_script; for (int i = extend_iter; i < p_class->extends_class.size(); i++) { String subclass = p_class->extends_class[i]; ident += ("." + subclass); if (find_subclass->get_subclasses().has(subclass)) { find_subclass = find_subclass->get_subclasses()[subclass]; } else if (find_subclass->get_constants().has(subclass)) { Ref<GDScript> new_base_class = find_subclass->get_constants()[subclass]; if (new_base_class.is_null()) { _set_error("Constant isn't a class: " + ident, p_class->line); return; } find_subclass = new_base_class; } else { _set_error("Couldn't find the subclass: " + ident, p_class->line); return; } } script = find_subclass; } else if (!base_class) { if (p_class->extends_class.size() > 1) { _set_error("Invalid inheritance (unknown class + subclasses).", p_class->line); return; } //if not found, try engine classes if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) { _set_error("Unknown class: \"" + base + "\"", p_class->line); return; } native = base; } } if (base_class) { p_class->base_type.has_type = true; p_class->base_type.kind = DataType::CLASS; p_class->base_type.class_type = base_class; } else if (script.is_valid()) { p_class->base_type.has_type = true; p_class->base_type.kind = DataType::GDSCRIPT; p_class->base_type.script_type = script; p_class->base_type.native_type = script->get_instance_base_type(); } else if (native != StringName()) { p_class->base_type.has_type = true; p_class->base_type.kind = DataType::NATIVE; p_class->base_type.native_type = native; } else { _set_error("Couldn't determine inheritance.", p_class->line); return; } } else { // without extends, implicitly extend Reference p_class->base_type.has_type = true; p_class->base_type.kind = DataType::NATIVE; p_class->base_type.native_type = "Reference"; } if (p_recursive) { // Recursively determine subclasses for (int i = 0; i < p_class->subclasses.size(); i++) { _determine_inheritance(p_class->subclasses[i], p_recursive); } } } String GDScriptParser::DataType::to_string() const { if (!has_type) { return "var"; } switch (kind) { case BUILTIN: { if (builtin_type == Variant::NIL) { return "null"; } return Variant::get_type_name(builtin_type); } break; case NATIVE: { if (is_meta_type) { return "GDScriptNativeClass"; } return native_type.operator String(); } break; case GDSCRIPT: { Ref<GDScript> gds = script_type; const String &gds_class = gds->get_script_class_name(); if (!gds_class.empty()) { return gds_class; } FALLTHROUGH; } case SCRIPT: { if (is_meta_type) { return script_type->get_class_name().operator String(); } String name = script_type->get_name(); if (name != String()) { return name; } name = script_type->get_path().get_file(); if (name != String()) { return name; } return native_type.operator String(); } break; case CLASS: { ERR_FAIL_COND_V(!class_type, String()); if (is_meta_type) { return "GDScript"; } if (class_type->name == StringName()) { return "self"; } return class_type->name.operator String(); } break; case UNRESOLVED: { } break; } return "Unresolved"; } bool GDScriptParser::_parse_type(DataType &r_type, bool p_can_be_void) { tokenizer->advance(); r_type.has_type = true; bool finished = false; bool can_index = false; String full_name; if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) { completion_cursor = StringName(); completion_type = COMPLETION_TYPE_HINT; completion_class = current_class; completion_function = current_function; completion_line = tokenizer->get_token_line(); completion_argument = 0; completion_block = current_block; completion_found = true; completion_ident_is_call = p_can_be_void; tokenizer->advance(); } switch (tokenizer->get_token()) { case GDScriptTokenizer::TK_PR_VOID: { if (!p_can_be_void) { return false; } r_type.kind = DataType::BUILTIN; r_type.builtin_type = Variant::NIL; } break; case GDScriptTokenizer::TK_BUILT_IN_TYPE: { r_type.builtin_type = tokenizer->get_token_type(); if (tokenizer->get_token_type() == Variant::OBJECT) { r_type.kind = DataType::NATIVE; r_type.native_type = "Object"; } else { r_type.kind = DataType::BUILTIN; } } break; case GDScriptTokenizer::TK_IDENTIFIER: { r_type.native_type = tokenizer->get_token_identifier(); if (ClassDB::class_exists(r_type.native_type) || ClassDB::class_exists("_" + r_type.native_type.operator String())) { r_type.kind = DataType::NATIVE; } else { r_type.kind = DataType::UNRESOLVED; can_index = true; full_name = r_type.native_type; } } break; default: { return false; } } tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) { completion_cursor = r_type.native_type; completion_type = COMPLETION_TYPE_HINT; completion_class = current_class; completion_function = current_function; completion_line = tokenizer->get_token_line(); completion_argument = 0; completion_block = current_block; completion_found = true; completion_ident_is_call = p_can_be_void; tokenizer->advance(); } if (can_index) { while (!finished) { switch (tokenizer->get_token()) { case GDScriptTokenizer::TK_PERIOD: { if (!can_index) { _set_error("Unexpected \".\"."); return false; } can_index = false; tokenizer->advance(); } break; case GDScriptTokenizer::TK_CURSOR: // GOBLIN ENGINE script completion suggest members of a script case GDScriptTokenizer::TK_IDENTIFIER: { if (can_index) { _set_error("Unexpected identifier."); return false; } StringName id; bool has_completion = _get_completable_identifier(COMPLETION_TYPE_HINT_INDEX, id); if (id == StringName()) { id = "@temp"; } full_name += "." + id.operator String(); can_index = true; if (has_completion) { completion_cursor = full_name; } } break; default: { finished = true; } break; } } if (tokenizer->get_token(-1) == GDScriptTokenizer::TK_PERIOD) { _set_error("Expected a subclass identifier."); return false; } r_type.native_type = full_name; } return true; } GDScriptParser::DataType GDScriptParser::_resolve_type(const DataType &p_source, int p_line) { if (!p_source.has_type) { return p_source; } if (p_source.kind != DataType::UNRESOLVED) { return p_source; } Vector<String> full_name = p_source.native_type.operator String().split(".", false); int name_part = 0; DataType result; result.has_type = true; while (name_part < full_name.size()) { bool found = false; StringName id = full_name[name_part]; DataType base_type = result; ClassNode *p = nullptr; if (name_part == 0) { if (ScriptServer::is_global_class(id)) { String script_path = ScriptServer::get_global_class_path(id); if (script_path == self_path) { result.kind = DataType::CLASS; result.class_type = static_cast<ClassNode *>(head); } else { Ref<Script> script = ResourceLoader::load(script_path); Ref<GDScript> gds = script; if (gds.is_valid()) { if (!gds->is_valid()) { _set_error("The class \"" + id + "\" couldn't be fully loaded (script error or cyclic dependency).", p_line); return DataType(); } result.kind = DataType::GDSCRIPT; result.script_type = gds; } else if (script.is_valid()) { result.kind = DataType::SCRIPT; result.script_type = script; } else { _set_error("The class \"" + id + "\" was found in global scope, but its script couldn't be loaded.", p_line); return DataType(); } } name_part++; continue; } List<PropertyInfo> props; ProjectSettings::get_singleton()->get_property_list(&props); String singleton_path; for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { String s = E->get().name; if (!s.begins_with("autoload/")) { continue; } String name = s.get_slice("/", 1); if (name == id) { singleton_path = ProjectSettings::get_singleton()->get(s); if (singleton_path.begins_with("*")) { singleton_path = singleton_path.right(1); } if (!singleton_path.begins_with("res://")) { singleton_path = "res://" + singleton_path; } break; } } if (!singleton_path.empty()) { Ref<Script> script = ResourceLoader::load(singleton_path); Ref<GDScript> gds = script; if (gds.is_valid()) { if (!gds->is_valid()) { _set_error("Class '" + id + "' could not be fully loaded (script error or cyclic inheritance).", p_line); return DataType(); } result.kind = DataType::GDSCRIPT; result.script_type = gds; } else if (script.is_valid()) { result.kind = DataType::SCRIPT; result.script_type = script; } else { _set_error("Couldn't fully load singleton script '" + id + "' (possible cyclic reference or parse error).", p_line); return DataType(); } name_part++; continue; } p = current_class; } else if (base_type.kind == DataType::CLASS) { p = base_type.class_type; } while (p) { if (p->constant_expressions.has(id)) { if (p->constant_expressions[id].expression->type != Node::TYPE_CONSTANT) { _set_error("Parser bug: unresolved constant.", p_line); ERR_FAIL_V(result); } const ConstantNode *cn = static_cast<const ConstantNode *>(p->constant_expressions[id].expression); Ref<GDScript> gds = cn->value; if (gds.is_valid()) { result.kind = DataType::GDSCRIPT; result.script_type = gds; found = true; } else { Ref<Script> scr = cn->value; if (scr.is_valid()) { result.kind = DataType::SCRIPT; result.script_type = scr; found = true; } } break; } // Inner classes ClassNode *outer_class = p; while (outer_class) { if (outer_class->name == id) { found = true; result.kind = DataType::CLASS; result.class_type = outer_class; break; } for (int i = 0; i < outer_class->subclasses.size(); i++) { if (outer_class->subclasses[i] == p) { continue; } if (outer_class->subclasses[i]->name == id) { found = true; result.kind = DataType::CLASS; result.class_type = outer_class->subclasses[i]; break; } } if (found) { break; } outer_class = outer_class->owner; } if (!found && p->base_type.kind == DataType::CLASS) { p = p->base_type.class_type; } else { base_type = p->base_type; break; } } // Still look for class constants in parent scripts if (!found && (base_type.kind == DataType::GDSCRIPT || base_type.kind == DataType::SCRIPT)) { Ref<Script> scr = base_type.script_type; ERR_FAIL_COND_V(scr.is_null(), result); while (scr.is_valid()) { Map<StringName, Variant> constants; scr->get_constants(&constants); if (constants.has(id)) { Ref<GDScript> gds = constants[id]; if (gds.is_valid()) { result.kind = DataType::GDSCRIPT; result.script_type = gds; found = true; } else { Ref<Script> scr2 = constants[id]; if (scr2.is_valid()) { result.kind = DataType::SCRIPT; result.script_type = scr2; found = true; } } } if (found) { break; } else { scr = scr->get_base_script(); } } } if (!found && !for_completion) { String base; if (name_part == 0) { base = "self"; } else { base = result.to_string(); } _set_error("The identifier \"" + String(id) + "\" isn't a valid type (not a script or class), or couldn't be found on base \"" + base + "\".", p_line); return DataType(); } name_part++; } return result; } GDScriptParser::DataType GDScriptParser::_type_from_variant(const Variant &p_value) const { DataType result; result.has_type = true; result.is_constant = true; result.kind = DataType::BUILTIN; result.builtin_type = p_value.get_type(); if (result.builtin_type == Variant::OBJECT) { Object *obj = p_value.operator Object *(); if (!obj) { return DataType(); } result.native_type = obj->get_class_name(); Ref<Script> scr = p_value; if (scr.is_valid()) { result.is_meta_type = true; } else { result.is_meta_type = false; scr = obj->get_script(); } if (scr.is_valid()) { result.script_type = scr; Ref<GDScript> gds = scr; if (gds.is_valid()) { result.kind = DataType::GDSCRIPT; } else { result.kind = DataType::SCRIPT; } result.native_type = scr->get_instance_base_type(); } else { result.kind = DataType::NATIVE; } } return result; } GDScriptParser::DataType GDScriptParser::_type_from_property(const PropertyInfo &p_property, bool p_nil_is_variant) const { DataType ret; if (p_property.type == Variant::NIL && (p_nil_is_variant || (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT))) { // Variant return ret; } ret.has_type = true; ret.builtin_type = p_property.type; if (p_property.type == Variant::OBJECT) { ret.kind = DataType::NATIVE; ret.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name; } else { ret.kind = DataType::BUILTIN; } return ret; } GDScriptParser::DataType GDScriptParser::_type_from_gdtype(const GDScriptDataType &p_gdtype) const { DataType result; if (!p_gdtype.has_type) { return result; } result.has_type = true; result.builtin_type = p_gdtype.builtin_type; result.native_type = p_gdtype.native_type; result.script_type = Ref<Script>(p_gdtype.script_type); switch (p_gdtype.kind) { case GDScriptDataType::UNINITIALIZED: { ERR_PRINT("Uninitialized datatype. Please report a bug."); } break; case GDScriptDataType::BUILTIN: { result.kind = DataType::BUILTIN; } break; case GDScriptDataType::NATIVE: { result.kind = DataType::NATIVE; } break; case GDScriptDataType::GDSCRIPT: { result.kind = DataType::GDSCRIPT; } break; case GDScriptDataType::SCRIPT: { result.kind = DataType::SCRIPT; } break; } return result; } GDScriptParser::DataType GDScriptParser::_get_operation_type(const Variant::Operator p_op, const DataType &p_a, const DataType &p_b, bool &r_valid) const { if (!p_a.has_type || !p_b.has_type) { r_valid = true; return DataType(); } Variant::Type a_type = p_a.kind == DataType::BUILTIN ? p_a.builtin_type : Variant::OBJECT; Variant::Type b_type = p_b.kind == DataType::BUILTIN ? p_b.builtin_type : Variant::OBJECT; Variant a; REF a_ref; if (a_type == Variant::OBJECT) { a_ref.instance(); a = a_ref; } else { Variant::CallError err; a = Variant::construct(a_type, nullptr, 0, err); if (err.error != Variant::CallError::CALL_OK) { r_valid = false; return DataType(); } } Variant b; REF b_ref; if (b_type == Variant::OBJECT) { b_ref.instance(); b = b_ref; } else { Variant::CallError err; b = Variant::construct(b_type, nullptr, 0, err); if (err.error != Variant::CallError::CALL_OK) { r_valid = false; return DataType(); } } // Avoid division by zero if (a_type == Variant::INT || a_type == Variant::REAL) { Variant::evaluate(Variant::OP_ADD, a, 1, a, r_valid); } if (b_type == Variant::INT || b_type == Variant::REAL) { Variant::evaluate(Variant::OP_ADD, b, 1, b, r_valid); } if (a_type == Variant::STRING && b_type != Variant::ARRAY) { a = "%s"; // Work around for formatting operator (%) } Variant ret; Variant::evaluate(p_op, a, b, ret, r_valid); if (r_valid) { return _type_from_variant(ret); } return DataType(); } Variant::Operator GDScriptParser::_get_variant_operation(const OperatorNode::Operator &p_op) const { switch (p_op) { case OperatorNode::OP_NEG: { return Variant::OP_NEGATE; } break; case OperatorNode::OP_POS: { return Variant::OP_POSITIVE; } break; case OperatorNode::OP_NOT: { return Variant::OP_NOT; } break; case OperatorNode::OP_BIT_INVERT: { return Variant::OP_BIT_NEGATE; } break; case OperatorNode::OP_IN: { return Variant::OP_IN; } break; case OperatorNode::OP_EQUAL: { return Variant::OP_EQUAL; } break; case OperatorNode::OP_NOT_EQUAL: { return Variant::OP_NOT_EQUAL; } break; case OperatorNode::OP_LESS: { return Variant::OP_LESS; } break; case OperatorNode::OP_LESS_EQUAL: { return Variant::OP_LESS_EQUAL; } break; case OperatorNode::OP_GREATER: { return Variant::OP_GREATER; } break; case OperatorNode::OP_GREATER_EQUAL: { return Variant::OP_GREATER_EQUAL; } break; case OperatorNode::OP_AND: { return Variant::OP_AND; } break; case OperatorNode::OP_OR: { return Variant::OP_OR; } break; case OperatorNode::OP_ASSIGN_ADD: case OperatorNode::OP_ADD: { return Variant::OP_ADD; } break; case OperatorNode::OP_ASSIGN_SUB: case OperatorNode::OP_SUB: { return Variant::OP_SUBTRACT; } break; case OperatorNode::OP_ASSIGN_MUL: case OperatorNode::OP_MUL: { return Variant::OP_MULTIPLY; } break; case OperatorNode::OP_ASSIGN_DIV: case OperatorNode::OP_DIV: { return Variant::OP_DIVIDE; } break; case OperatorNode::OP_ASSIGN_MOD: case OperatorNode::OP_MOD: { return Variant::OP_MODULE; } break; case OperatorNode::OP_ASSIGN_BIT_AND: case OperatorNode::OP_BIT_AND: { return Variant::OP_BIT_AND; } break; case OperatorNode::OP_ASSIGN_BIT_OR: case OperatorNode::OP_BIT_OR: { return Variant::OP_BIT_OR; } break; case OperatorNode::OP_ASSIGN_BIT_XOR: case OperatorNode::OP_BIT_XOR: { return Variant::OP_BIT_XOR; } break; case OperatorNode::OP_ASSIGN_SHIFT_LEFT: case OperatorNode::OP_SHIFT_LEFT: { return Variant::OP_SHIFT_LEFT; } case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: case OperatorNode::OP_SHIFT_RIGHT: { return Variant::OP_SHIFT_RIGHT; } default: { return Variant::OP_MAX; } break; } } bool GDScriptParser::_is_type_compatible(const DataType &p_container, const DataType &p_expression, bool p_allow_implicit_conversion) const { // Ignore for completion if (!check_types || for_completion) { return true; } // Can't test if not all have type if (!p_container.has_type || !p_expression.has_type) { return true; } // Should never get here unresolved ERR_FAIL_COND_V(p_container.kind == DataType::UNRESOLVED, false); ERR_FAIL_COND_V(p_expression.kind == DataType::UNRESOLVED, false); if (p_container.kind == DataType::BUILTIN && p_expression.kind == DataType::BUILTIN) { bool valid = p_container.builtin_type == p_expression.builtin_type; if (p_allow_implicit_conversion) { valid = valid || Variant::can_convert_strict(p_expression.builtin_type, p_container.builtin_type); } return valid; } if (p_container.kind == DataType::BUILTIN && p_container.builtin_type == Variant::OBJECT) { // Object built-in is a special case, it's compatible with any object and with null if (p_expression.kind == DataType::BUILTIN) { return p_expression.builtin_type == Variant::NIL; } // If it's not a built-in, must be an object return true; } if (p_container.kind == DataType::BUILTIN || (p_expression.kind == DataType::BUILTIN && p_expression.builtin_type != Variant::NIL)) { // Can't mix built-ins with objects return false; } // From now on everything is objects, check polymorphism // The container must be the same class or a superclass of the expression if (p_expression.kind == DataType::BUILTIN && p_expression.builtin_type == Variant::NIL) { // Null can be assigned to object types return true; } StringName expr_native; Ref<Script> expr_script; ClassNode *expr_class = nullptr; switch (p_expression.kind) { case DataType::NATIVE: { if (p_container.kind != DataType::NATIVE) { // Non-native type can't be a superclass of a native type return false; } if (p_expression.is_meta_type) { expr_native = GDScriptNativeClass::get_class_static(); } else { expr_native = p_expression.native_type; } } break; case DataType::SCRIPT: case DataType::GDSCRIPT: { if (p_container.kind == DataType::CLASS) { // This cannot be resolved without cyclic dependencies, so just bail out return false; } if (p_expression.is_meta_type) { expr_native = p_expression.script_type->get_class_name(); } else { expr_script = p_expression.script_type; expr_native = expr_script->get_instance_base_type(); } } break; case DataType::CLASS: { if (p_expression.is_meta_type) { expr_native = GDScript::get_class_static(); } else { expr_class = p_expression.class_type; ClassNode *base = expr_class; while (base->base_type.kind == DataType::CLASS) { base = base->base_type.class_type; } expr_native = base->base_type.native_type; expr_script = base->base_type.script_type; } } break; case DataType::BUILTIN: // Already handled above case DataType::UNRESOLVED: // Not allowed, see above break; } // Some classes are prefixed with `_` internally if (!ClassDB::class_exists(expr_native)) { expr_native = "_" + expr_native; } switch (p_container.kind) { case DataType::NATIVE: { if (p_container.is_meta_type) { return ClassDB::is_parent_class(expr_native, GDScriptNativeClass::get_class_static()); } else { StringName container_native = ClassDB::class_exists(p_container.native_type) ? p_container.native_type : StringName("_" + p_container.native_type); return ClassDB::is_parent_class(expr_native, container_native); } } break; case DataType::SCRIPT: case DataType::GDSCRIPT: { if (p_container.is_meta_type) { return ClassDB::is_parent_class(expr_native, GDScript::get_class_static()); } if (expr_class == head && p_container.script_type->get_path() == self_path) { // Special case: container is self script and expression is self return true; } while (expr_script.is_valid()) { if (expr_script == p_container.script_type) { return true; } expr_script = expr_script->get_base_script(); } return false; } break; case DataType::CLASS: { if (p_container.is_meta_type) { return ClassDB::is_parent_class(expr_native, GDScript::get_class_static()); } if (p_container.class_type == head && expr_script.is_valid() && expr_script->get_path() == self_path) { // Special case: container is self and expression is self script return true; } while (expr_class) { if (expr_class == p_container.class_type) { return true; } expr_class = expr_class->base_type.class_type; } return false; } break; case DataType::BUILTIN: // Already handled above case DataType::UNRESOLVED: // Not allowed, see above break; } return false; } GDScriptParser::Node *GDScriptParser::_get_default_value_for_type(const DataType &p_type, int p_line) { Node *result; if (p_type.has_type && p_type.kind == DataType::BUILTIN && p_type.builtin_type != Variant::NIL && p_type.builtin_type != Variant::OBJECT) { if (p_type.builtin_type == Variant::ARRAY) { result = alloc_node<ArrayNode>(); } else if (p_type.builtin_type == Variant::DICTIONARY) { result = alloc_node<DictionaryNode>(); } else { ConstantNode *c = alloc_node<ConstantNode>(); Variant::CallError err; c->value = Variant::construct(p_type.builtin_type, nullptr, 0, err); result = c; } } else { ConstantNode *c = alloc_node<ConstantNode>(); c->value = Variant(); result = c; } result->line = p_line; return result; } GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { #ifdef DEBUG_ENABLED if (p_node->get_datatype().has_type && p_node->type != Node::TYPE_ARRAY && p_node->type != Node::TYPE_DICTIONARY) { #else if (p_node->get_datatype().has_type) { #endif return p_node->get_datatype(); } DataType node_type; switch (p_node->type) { case Node::TYPE_CONSTANT: { node_type = _type_from_variant(static_cast<ConstantNode *>(p_node)->value); } break; case Node::TYPE_TYPE: { TypeNode *tn = static_cast<TypeNode *>(p_node); node_type.has_type = true; node_type.is_meta_type = true; node_type.kind = DataType::BUILTIN; node_type.builtin_type = tn->vtype; } break; case Node::TYPE_ARRAY: { node_type.has_type = true; node_type.kind = DataType::BUILTIN; node_type.builtin_type = Variant::ARRAY; #ifdef DEBUG_ENABLED // Check stuff inside the array ArrayNode *an = static_cast<ArrayNode *>(p_node); for (int i = 0; i < an->elements.size(); i++) { _reduce_node_type(an->elements[i]); } #endif // DEBUG_ENABLED } break; case Node::TYPE_DICTIONARY: { node_type.has_type = true; node_type.kind = DataType::BUILTIN; node_type.builtin_type = Variant::DICTIONARY; #ifdef DEBUG_ENABLED // Check stuff inside the dictionarty DictionaryNode *dn = static_cast<DictionaryNode *>(p_node); for (int i = 0; i < dn->elements.size(); i++) { _reduce_node_type(dn->elements[i].key); _reduce_node_type(dn->elements[i].value); } #endif // DEBUG_ENABLED } break; case Node::TYPE_SELF: { node_type.has_type = true; node_type.kind = DataType::CLASS; node_type.class_type = current_class; node_type.is_constant = true; } break; case Node::TYPE_IDENTIFIER: { IdentifierNode *id = static_cast<IdentifierNode *>(p_node); if (id->declared_block) { node_type = id->declared_block->variables[id->name]->get_datatype(); id->declared_block->variables[id->name]->usages += 1; } else if (id->name == "#match_value") { // It's a special id just for the match statetement, ignore break; } else if (current_function && current_function->arguments.find(id->name) >= 0) { int idx = current_function->arguments.find(id->name); node_type = current_function->argument_types[idx]; } else { node_type = _reduce_identifier_type(nullptr, id->name, id->line, false); } } break; case Node::TYPE_CAST: { CastNode *cn = static_cast<CastNode *>(p_node); DataType source_type = _reduce_node_type(cn->source_node); cn->cast_type = _resolve_type(cn->cast_type, cn->line); if (source_type.has_type) { bool valid = false; if (check_types) { if (cn->cast_type.kind == DataType::BUILTIN && source_type.kind == DataType::BUILTIN) { valid = Variant::can_convert(source_type.builtin_type, cn->cast_type.builtin_type); } if (cn->cast_type.kind != DataType::BUILTIN && source_type.kind != DataType::BUILTIN) { valid = _is_type_compatible(cn->cast_type, source_type) || _is_type_compatible(source_type, cn->cast_type); } if (!valid) { _set_error("Invalid cast. Cannot convert from \"" + source_type.to_string() + "\" to \"" + cn->cast_type.to_string() + "\".", cn->line); return DataType(); } } } else { #ifdef DEBUG_ENABLED _add_warning(GDScriptWarning::UNSAFE_CAST, cn->line, cn->cast_type.to_string()); #endif // DEBUG_ENABLED _mark_line_as_unsafe(cn->line); } node_type = cn->cast_type; } break; case Node::TYPE_OPERATOR: { OperatorNode *op = static_cast<OperatorNode *>(p_node); switch (op->op) { case OperatorNode::OP_CALL: case OperatorNode::OP_PARENT_CALL: { node_type = _reduce_function_call_type(op); } break; case OperatorNode::OP_YIELD: { if (op->arguments.size() == 2) { DataType base_type = _reduce_node_type(op->arguments[0]); DataType signal_type = _reduce_node_type(op->arguments[1]); // TODO: Check if signal exists when it's a constant if (base_type.has_type && base_type.kind == DataType::BUILTIN && base_type.builtin_type != Variant::NIL && base_type.builtin_type != Variant::OBJECT) { _set_error("The first argument of \"yield()\" must be an object.", op->line); return DataType(); } if (signal_type.has_type && (signal_type.kind != DataType::BUILTIN || signal_type.builtin_type != Variant::STRING)) { _set_error("The second argument of \"yield()\" must be a string.", op->line); return DataType(); } } // yield can return anything node_type.has_type = false; } break; case OperatorNode::OP_IS: case OperatorNode::OP_IS_BUILTIN: { if (op->arguments.size() != 2) { _set_error("Parser bug: binary operation without 2 arguments.", op->line); ERR_FAIL_V(DataType()); } DataType value_type = _reduce_node_type(op->arguments[0]); DataType type_type = _reduce_node_type(op->arguments[1]); if (check_types && type_type.has_type) { if (!type_type.is_meta_type && (type_type.kind != DataType::NATIVE || !ClassDB::is_parent_class(type_type.native_type, "Script"))) { _set_error("Invalid \"is\" test: the right operand isn't a type (neither a native type nor a script).", op->line); return DataType(); } type_type.is_meta_type = false; // Test the actual type if (!_is_type_compatible(type_type, value_type) && !_is_type_compatible(value_type, type_type)) { if (op->op == OperatorNode::OP_IS) { _set_error("A value of type \"" + value_type.to_string() + "\" will never be an instance of \"" + type_type.to_string() + "\".", op->line); } else { _set_error("A value of type \"" + value_type.to_string() + "\" will never be of type \"" + type_type.to_string() + "\".", op->line); } return DataType(); } } node_type.has_type = true; node_type.is_constant = true; node_type.is_meta_type = false; node_type.kind = DataType::BUILTIN; node_type.builtin_type = Variant::BOOL; } break; // Unary operators case OperatorNode::OP_NEG: case OperatorNode::OP_POS: case OperatorNode::OP_NOT: case OperatorNode::OP_BIT_INVERT: { DataType argument_type = _reduce_node_type(op->arguments[0]); if (!argument_type.has_type) { break; } Variant::Operator var_op = _get_variant_operation(op->op); bool valid = false; node_type = _get_operation_type(var_op, argument_type, argument_type, valid); if (check_types && !valid) { _set_error("Invalid operand type (\"" + argument_type.to_string() + "\") to unary operator \"" + Variant::get_operator_name(var_op) + "\".", op->line, op->column); return DataType(); } } break; // Binary operators case OperatorNode::OP_IN: case OperatorNode::OP_EQUAL: case OperatorNode::OP_NOT_EQUAL: case OperatorNode::OP_LESS: case OperatorNode::OP_LESS_EQUAL: case OperatorNode::OP_GREATER: case OperatorNode::OP_GREATER_EQUAL: case OperatorNode::OP_AND: case OperatorNode::OP_OR: case OperatorNode::OP_ADD: case OperatorNode::OP_SUB: case OperatorNode::OP_MUL: case OperatorNode::OP_DIV: case OperatorNode::OP_MOD: case OperatorNode::OP_SHIFT_LEFT: case OperatorNode::OP_SHIFT_RIGHT: case OperatorNode::OP_BIT_AND: case OperatorNode::OP_BIT_OR: case OperatorNode::OP_BIT_XOR: { if (op->arguments.size() != 2) { _set_error("Parser bug: binary operation without 2 arguments.", op->line); ERR_FAIL_V(DataType()); } DataType argument_a_type = _reduce_node_type(op->arguments[0]); DataType argument_b_type = _reduce_node_type(op->arguments[1]); if (!argument_a_type.has_type || !argument_b_type.has_type) { _mark_line_as_unsafe(op->line); break; } Variant::Operator var_op = _get_variant_operation(op->op); bool valid = false; node_type = _get_operation_type(var_op, argument_a_type, argument_b_type, valid); if (check_types && !valid) { _set_error("Invalid operand types (\"" + argument_a_type.to_string() + "\" and \"" + argument_b_type.to_string() + "\") to operator \"" + Variant::get_operator_name(var_op) + "\".", op->line, op->column); return DataType(); } #ifdef DEBUG_ENABLED if (var_op == Variant::OP_DIVIDE && argument_a_type.kind == DataType::BUILTIN && argument_a_type.builtin_type == Variant::INT && argument_b_type.kind == DataType::BUILTIN && argument_b_type.builtin_type == Variant::INT) { _add_warning(GDScriptWarning::INTEGER_DIVISION, op->line); } #endif // DEBUG_ENABLED } break; // Ternary operators case OperatorNode::OP_TERNARY_IF: { if (op->arguments.size() != 3) { _set_error("Parser bug: ternary operation without 3 arguments."); ERR_FAIL_V(DataType()); } DataType true_type = _reduce_node_type(op->arguments[1]); DataType false_type = _reduce_node_type(op->arguments[2]); // Check arguments[0] errors. _reduce_node_type(op->arguments[0]); // If types are equal, then the expression is of the same type // If they are compatible, return the broader type if (true_type == false_type || _is_type_compatible(true_type, false_type)) { node_type = true_type; } else if (_is_type_compatible(false_type, true_type)) { node_type = false_type; } else { #ifdef DEBUG_ENABLED _add_warning(GDScriptWarning::INCOMPATIBLE_TERNARY, op->line); #endif // DEBUG_ENABLED } } break; // Assignment should never happen within an expression case OperatorNode::OP_ASSIGN: case OperatorNode::OP_ASSIGN_ADD: case OperatorNode::OP_ASSIGN_SUB: case OperatorNode::OP_ASSIGN_MUL: case OperatorNode::OP_ASSIGN_DIV: case OperatorNode::OP_ASSIGN_MOD: case OperatorNode::OP_ASSIGN_SHIFT_LEFT: case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: case OperatorNode::OP_ASSIGN_BIT_AND: case OperatorNode::OP_ASSIGN_BIT_OR: case OperatorNode::OP_ASSIGN_BIT_XOR: case OperatorNode::OP_INIT_ASSIGN: { _set_error("Assignment inside an expression isn't allowed (parser bug?).", op->line); return DataType(); } break; case OperatorNode::OP_INDEX_NAMED: { if (op->arguments.size() != 2) { _set_error("Parser bug: named index with invalid arguments.", op->line); ERR_FAIL_V(DataType()); } if (op->arguments[1]->type != Node::TYPE_IDENTIFIER) { _set_error("Parser bug: named index without identifier argument.", op->line); ERR_FAIL_V(DataType()); } DataType base_type = _reduce_node_type(op->arguments[0]); IdentifierNode *member_id = static_cast<IdentifierNode *>(op->arguments[1]); if (base_type.has_type) { if (check_types && base_type.kind == DataType::BUILTIN) { // Variant type, just test if it's possible DataType result; switch (base_type.builtin_type) { case Variant::NIL: case Variant::DICTIONARY: { result.has_type = false; } break; default: { Variant::CallError err; Variant temp = Variant::construct(base_type.builtin_type, nullptr, 0, err); bool valid = false; Variant res = temp.get(member_id->name.operator String(), &valid); if (valid) { result = _type_from_variant(res); } else if (check_types) { _set_error("Can't get index \"" + String(member_id->name.operator String()) + "\" on base \"" + base_type.to_string() + "\".", op->line); return DataType(); } } break; } result.is_constant = false; node_type = result; } else { node_type = _reduce_identifier_type(&base_type, member_id->name, op->line, true); #ifdef DEBUG_ENABLED if (!node_type.has_type) { _mark_line_as_unsafe(op->line); _add_warning(GDScriptWarning::UNSAFE_PROPERTY_ACCESS, op->line, member_id->name.operator String(), base_type.to_string()); } #endif // DEBUG_ENABLED } } else { _mark_line_as_unsafe(op->line); } if (error_set) { return DataType(); } } break; case OperatorNode::OP_INDEX: { if (op->arguments[1]->type == Node::TYPE_CONSTANT) { ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[1]); if (cn->value.get_type() == Variant::STRING) { // Treat this as named indexing IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = cn->value.operator StringName(); id->datatype = cn->datatype; op->op = OperatorNode::OP_INDEX_NAMED; op->arguments.write[1] = id; return _reduce_node_type(op); } } DataType base_type = _reduce_node_type(op->arguments[0]); DataType index_type = _reduce_node_type(op->arguments[1]); if (!base_type.has_type) { _mark_line_as_unsafe(op->line); break; } if (check_types && index_type.has_type) { if (base_type.kind == DataType::BUILTIN) { // Check if indexing is valid bool error = index_type.kind != DataType::BUILTIN && base_type.builtin_type != Variant::DICTIONARY; if (!error) { switch (base_type.builtin_type) { // Expect int or real as index case Variant::POOL_BYTE_ARRAY: case Variant::POOL_COLOR_ARRAY: case Variant::POOL_INT_ARRAY: case Variant::POOL_REAL_ARRAY: case Variant::POOL_STRING_ARRAY: case Variant::POOL_VECTOR2_ARRAY: case Variant::POOL_VECTOR3_ARRAY: case Variant::ARRAY: case Variant::STRING: { error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::REAL; } break; // Expect String only case Variant::RECT2: case Variant::PLANE: case Variant::QUAT: case Variant::AABB: case Variant::OBJECT: { error = index_type.builtin_type != Variant::STRING; } break; // Expect String or number case Variant::VECTOR2: case Variant::VECTOR3: case Variant::TRANSFORM2D: case Variant::BASIS: case Variant::TRANSFORM: { error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::REAL && index_type.builtin_type != Variant::STRING; } break; // Expect String or int case Variant::COLOR: { error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING; } break; default: { } } } if (error) { _set_error("Invalid index type (" + index_type.to_string() + ") for base \"" + base_type.to_string() + "\".", op->line); return DataType(); } if (op->arguments[1]->type == GDScriptParser::Node::TYPE_CONSTANT) { ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[1]); // Index is a constant, just try it if possible switch (base_type.builtin_type) { // Arrays/string have variable indexing, can't test directly case Variant::STRING: case Variant::ARRAY: case Variant::DICTIONARY: case Variant::POOL_BYTE_ARRAY: case Variant::POOL_COLOR_ARRAY: case Variant::POOL_INT_ARRAY: case Variant::POOL_REAL_ARRAY: case Variant::POOL_STRING_ARRAY: case Variant::POOL_VECTOR2_ARRAY: case Variant::POOL_VECTOR3_ARRAY: { break; } default: { Variant::CallError err; Variant temp = Variant::construct(base_type.builtin_type, nullptr, 0, err); bool valid = false; Variant res = temp.get(cn->value, &valid); if (valid) { node_type = _type_from_variant(res); node_type.is_constant = false; } else if (check_types) { _set_error("Can't get index \"" + String(cn->value) + "\" on base \"" + base_type.to_string() + "\".", op->line); return DataType(); } } break; } } else { _mark_line_as_unsafe(op->line); } } else if (!for_completion && (index_type.kind != DataType::BUILTIN || index_type.builtin_type != Variant::STRING)) { _set_error("Only strings can be used as an index in the base type \"" + base_type.to_string() + "\".", op->line); return DataType(); } } if (check_types && !node_type.has_type && base_type.kind == DataType::BUILTIN) { // Can infer indexing type for some variant types DataType result; result.has_type = true; result.kind = DataType::BUILTIN; switch (base_type.builtin_type) { // Can't index at all case Variant::NIL: case Variant::BOOL: case Variant::INT: case Variant::REAL: case Variant::NODE_PATH: case Variant::_RID: { _set_error("Can't index on a value of type \"" + base_type.to_string() + "\".", op->line); return DataType(); } break; // Return int case Variant::POOL_BYTE_ARRAY: case Variant::POOL_INT_ARRAY: { result.builtin_type = Variant::INT; } break; // Return real case Variant::POOL_REAL_ARRAY: case Variant::VECTOR2: case Variant::VECTOR3: case Variant::QUAT: { result.builtin_type = Variant::REAL; } break; // Return color case Variant::POOL_COLOR_ARRAY: { result.builtin_type = Variant::COLOR; } break; // Return string case Variant::POOL_STRING_ARRAY: case Variant::STRING: { result.builtin_type = Variant::STRING; } break; // Return Vector2 case Variant::POOL_VECTOR2_ARRAY: case Variant::TRANSFORM2D: case Variant::RECT2: { result.builtin_type = Variant::VECTOR2; } break; // Return Vector3 case Variant::POOL_VECTOR3_ARRAY: case Variant::AABB: case Variant::BASIS: { result.builtin_type = Variant::VECTOR3; } break; // Depends on the index case Variant::TRANSFORM: case Variant::PLANE: case Variant::COLOR: default: { result.has_type = false; } break; } node_type = result; } } break; default: { _set_error("Parser bug: unhandled operation.", op->line); ERR_FAIL_V(DataType()); } } } break; default: { } } node_type = _resolve_type(node_type, p_node->line); p_node->set_datatype(node_type); return node_type; } bool GDScriptParser::_get_function_signature(DataType &p_base_type, const StringName &p_function, DataType &r_return_type, List<DataType> &r_arg_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) const { r_static = false; r_default_arg_count = 0; DataType original_type = p_base_type; ClassNode *base = nullptr; FunctionNode *callee = nullptr; if (p_base_type.kind == DataType::CLASS) { base = p_base_type.class_type; } // Look up the current file (parse tree) while (!callee && base) { for (int i = 0; i < base->static_functions.size(); i++) { FunctionNode *func = base->static_functions[i]; if (p_function == func->name) { r_static = true; callee = func; break; } } if (!callee && !p_base_type.is_meta_type) { for (int i = 0; i < base->functions.size(); i++) { FunctionNode *func = base->functions[i]; if (p_function == func->name) { callee = func; break; } } } p_base_type = base->base_type; if (p_base_type.kind == DataType::CLASS) { base = p_base_type.class_type; } else { break; } } if (callee) { r_return_type = callee->get_datatype(); for (int i = 0; i < callee->argument_types.size(); i++) { r_arg_types.push_back(callee->argument_types[i]); } r_default_arg_count = callee->default_values.size(); return true; } // Nothing in current file, check parent script Ref<GDScript> base_gdscript; Ref<Script> base_script; StringName native; if (p_base_type.kind == DataType::GDSCRIPT) { base_gdscript = p_base_type.script_type; if (base_gdscript.is_null() || !base_gdscript->is_valid()) { // GDScript wasn't properly compíled, don't bother trying return false; } } else if (p_base_type.kind == DataType::SCRIPT) { base_script = p_base_type.script_type; } else if (p_base_type.kind == DataType::NATIVE) { native = p_base_type.native_type; } while (base_gdscript.is_valid()) { native = base_gdscript->get_instance_base_type(); Map<StringName, GDScriptFunction *> funcs = base_gdscript->get_member_functions(); if (funcs.has(p_function)) { GDScriptFunction *f = funcs[p_function]; r_static = f->is_static(); r_default_arg_count = f->get_default_argument_count(); r_return_type = _type_from_gdtype(f->get_return_type()); for (int i = 0; i < f->get_argument_count(); i++) { r_arg_types.push_back(_type_from_gdtype(f->get_argument_type(i))); } return true; } base_gdscript = base_gdscript->get_base_script(); } while (base_script.is_valid()) { native = base_script->get_instance_base_type(); MethodInfo mi = base_script->get_method_info(p_function); if (!(mi == MethodInfo())) { r_return_type = _type_from_property(mi.return_val, false); r_default_arg_count = mi.default_arguments.size(); for (List<PropertyInfo>::Element *E = mi.arguments.front(); E; E = E->next()) { r_arg_types.push_back(_type_from_property(E->get())); } return true; } base_script = base_script->get_base_script(); } if (native == StringName()) { // Empty native class, might happen in some Script implementations // Just ignore it return false; } // Only native remains if (!ClassDB::class_exists(native)) { native = "_" + native.operator String(); } if (!ClassDB::class_exists(native)) { if (!check_types) { return false; } ERR_FAIL_V_MSG(false, "Parser bug: Class '" + String(native) + "' not found."); } MethodBind *method = ClassDB::get_method(native, p_function); if (!method) { // Try virtual methods List<MethodInfo> virtuals; ClassDB::get_virtual_methods(native, &virtuals); for (const List<MethodInfo>::Element *E = virtuals.front(); E; E = E->next()) { const MethodInfo &mi = E->get(); if (mi.name == p_function) { r_default_arg_count = mi.default_arguments.size(); for (const List<PropertyInfo>::Element *pi = mi.arguments.front(); pi; pi = pi->next()) { r_arg_types.push_back(_type_from_property(pi->get())); } r_return_type = _type_from_property(mi.return_val, false); r_vararg = mi.flags & METHOD_FLAG_VARARG; return true; } } // If the base is a script, it might be trying to access members of the Script class itself if (original_type.is_meta_type && !(p_function == "new") && (original_type.kind == DataType::SCRIPT || original_type.kind == DataType::GDSCRIPT)) { method = ClassDB::get_method(original_type.script_type->get_class_name(), p_function); if (method) { r_static = true; } else { // Try virtual methods of the script type virtuals.clear(); ClassDB::get_virtual_methods(original_type.script_type->get_class_name(), &virtuals); for (const List<MethodInfo>::Element *E = virtuals.front(); E; E = E->next()) { const MethodInfo &mi = E->get(); if (mi.name == p_function) { r_default_arg_count = mi.default_arguments.size(); for (const List<PropertyInfo>::Element *pi = mi.arguments.front(); pi; pi = pi->next()) { r_arg_types.push_back(_type_from_property(pi->get())); } r_return_type = _type_from_property(mi.return_val, false); r_static = true; r_vararg = mi.flags & METHOD_FLAG_VARARG; return true; } } return false; } } else { return false; } } r_default_arg_count = method->get_default_argument_count(); if (method->get_name() == "get_script") { r_return_type = DataType(); // Variant for now and let runtime decide. } else { r_return_type = _type_from_property(method->get_return_info(), false); } r_vararg = method->is_vararg(); for (int i = 0; i < method->get_argument_count(); i++) { r_arg_types.push_back(_type_from_property(method->get_argument_info(i))); } return true; } GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const OperatorNode *p_call) { if (p_call->arguments.size() < 1) { _set_error("Parser bug: function call without enough arguments.", p_call->line); ERR_FAIL_V(DataType()); } DataType return_type; List<DataType> arg_types; int default_args_count = 0; String callee_name; bool is_vararg = false; #ifdef DEBUG_ENABLED int arg_count = p_call->arguments.size(); #endif switch (p_call->arguments[0]->type) { case GDScriptParser::Node::TYPE_TYPE: { // Built-in constructor, special case TypeNode *tn = static_cast<TypeNode *>(p_call->arguments[0]); Vector<DataType> par_types; par_types.resize(p_call->arguments.size() - 1); for (int i = 1; i < p_call->arguments.size(); i++) { par_types.write[i - 1] = _reduce_node_type(p_call->arguments[i]); } if (error_set) { return DataType(); } // Special case: check copy constructor. Those are defined implicitly in Variant. if (par_types.size() == 1) { if (!par_types[0].has_type || (par_types[0].kind == DataType::BUILTIN && par_types[0].builtin_type == tn->vtype)) { DataType result; result.has_type = true; result.kind = DataType::BUILTIN; result.builtin_type = tn->vtype; return result; } } bool match = false; List<MethodInfo> constructors; Variant::get_constructor_list(tn->vtype, &constructors); PropertyInfo return_type2; for (List<MethodInfo>::Element *E = constructors.front(); E; E = E->next()) { MethodInfo &mi = E->get(); if (p_call->arguments.size() - 1 < mi.arguments.size() - mi.default_arguments.size()) { continue; } if (p_call->arguments.size() - 1 > mi.arguments.size()) { continue; } bool types_match = true; for (int i = 0; i < par_types.size(); i++) { DataType arg_type; if (mi.arguments[i].type != Variant::NIL) { arg_type.has_type = true; arg_type.kind = mi.arguments[i].type == Variant::OBJECT ? DataType::NATIVE : DataType::BUILTIN; arg_type.builtin_type = mi.arguments[i].type; arg_type.native_type = mi.arguments[i].class_name; } if (!_is_type_compatible(arg_type, par_types[i], true)) { types_match = false; break; } else { #ifdef DEBUG_ENABLED if (arg_type.kind == DataType::BUILTIN && arg_type.builtin_type == Variant::INT && par_types[i].kind == DataType::BUILTIN && par_types[i].builtin_type == Variant::REAL) { _add_warning(GDScriptWarning::NARROWING_CONVERSION, p_call->line, Variant::get_type_name(tn->vtype)); } if (par_types[i].may_yield && p_call->arguments[i + 1]->type == Node::TYPE_OPERATOR) { _add_warning(GDScriptWarning::FUNCTION_MAY_YIELD, p_call->line, _find_function_name(static_cast<OperatorNode *>(p_call->arguments[i + 1]))); } #endif // DEBUG_ENABLED } } if (types_match) { match = true; return_type2 = mi.return_val; break; } } if (match) { return _type_from_property(return_type2, false); } else if (check_types) { String err = "No constructor of '"; err += Variant::get_type_name(tn->vtype); err += "' matches the signature '"; err += Variant::get_type_name(tn->vtype) + "("; for (int i = 0; i < par_types.size(); i++) { if (i > 0) { err += ", "; } err += par_types[i].to_string(); } err += ")'."; _set_error(err, p_call->line, p_call->column); return DataType(); } return DataType(); } break; case GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION: { BuiltInFunctionNode *func = static_cast<BuiltInFunctionNode *>(p_call->arguments[0]); MethodInfo mi = GDScriptFunctions::get_info(func->function); return_type = _type_from_property(mi.return_val, false); // Check all arguments beforehand to solve warnings for (int i = 1; i < p_call->arguments.size(); i++) { _reduce_node_type(p_call->arguments[i]); } // Check arguments is_vararg = mi.flags & METHOD_FLAG_VARARG; default_args_count = mi.default_arguments.size(); callee_name = mi.name; #ifdef DEBUG_ENABLED arg_count -= 1; #endif // Check each argument type for (List<PropertyInfo>::Element *E = mi.arguments.front(); E; E = E->next()) { arg_types.push_back(_type_from_property(E->get())); } } break; default: { if (p_call->op == OperatorNode::OP_CALL && p_call->arguments.size() < 2) { _set_error("Parser bug: self method call without enough arguments.", p_call->line); ERR_FAIL_V(DataType()); } int arg_id = p_call->op == OperatorNode::OP_CALL ? 1 : 0; if (p_call->arguments[arg_id]->type != Node::TYPE_IDENTIFIER) { _set_error("Parser bug: invalid function call argument.", p_call->line); ERR_FAIL_V(DataType()); } // Check all arguments beforehand to solve warnings for (int i = arg_id + 1; i < p_call->arguments.size(); i++) { _reduce_node_type(p_call->arguments[i]); } IdentifierNode *func_id = static_cast<IdentifierNode *>(p_call->arguments[arg_id]); callee_name = func_id->name; #ifdef DEBUG_ENABLED arg_count -= 1 + arg_id; #endif DataType base_type; if (p_call->op == OperatorNode::OP_PARENT_CALL) { base_type = current_class->base_type; } else { base_type = _reduce_node_type(p_call->arguments[0]); } if (!base_type.has_type || (base_type.kind == DataType::BUILTIN && base_type.builtin_type == Variant::NIL)) { _mark_line_as_unsafe(p_call->line); return DataType(); } if (base_type.kind == DataType::BUILTIN) { Variant::CallError err; Variant tmp = Variant::construct(base_type.builtin_type, nullptr, 0, err); if (check_types) { if (!tmp.has_method(callee_name)) { _set_error("The method \"" + callee_name + "\" isn't declared on base \"" + base_type.to_string() + "\".", p_call->line); return DataType(); } default_args_count = Variant::get_method_default_arguments(base_type.builtin_type, callee_name).size(); const Vector<Variant::Type> &var_arg_types = Variant::get_method_argument_types(base_type.builtin_type, callee_name); for (int i = 0; i < var_arg_types.size(); i++) { DataType argtype; if (var_arg_types[i] != Variant::NIL) { argtype.has_type = true; argtype.kind = DataType::BUILTIN; argtype.builtin_type = var_arg_types[i]; } arg_types.push_back(argtype); } } bool rets = false; return_type.has_type = true; return_type.kind = DataType::BUILTIN; return_type.builtin_type = Variant::get_method_return_type(base_type.builtin_type, callee_name, &rets); // If the method returns, but it might return any type, (Variant::NIL), pretend we don't know the type. // At least make sure we know that it returns if (rets && return_type.builtin_type == Variant::NIL) { return_type.has_type = false; } break; } DataType original_type = base_type; bool is_initializer = callee_name == "new"; bool is_get_script = p_call->arguments[0]->type == Node::TYPE_SELF && callee_name == "get_script"; bool is_static = false; bool valid = false; if (is_initializer && original_type.is_meta_type) { // Try to check it as initializer base_type = original_type; callee_name = "_init"; base_type.is_meta_type = false; valid = _get_function_signature(base_type, callee_name, return_type, arg_types, default_args_count, is_static, is_vararg); return_type = original_type; return_type.is_meta_type = false; valid = true; // There's always an initializer, we can assume this is true } if (is_get_script) { // get_script() can be considered a meta-type. return_type.kind = DataType::CLASS; return_type.class_type = static_cast<ClassNode *>(head); return_type.is_meta_type = true; valid = true; } if (!valid) { base_type = original_type; return_type = DataType(); valid = _get_function_signature(base_type, callee_name, return_type, arg_types, default_args_count, is_static, is_vararg); } if (!valid) { #ifdef DEBUG_ENABLED if (p_call->arguments[0]->type == Node::TYPE_SELF) { _set_error("The method \"" + callee_name + "\" isn't declared in the current class.", p_call->line); return DataType(); } DataType tmp_type; valid = _get_member_type(original_type, func_id->name, tmp_type); if (valid) { if (tmp_type.is_constant) { _add_warning(GDScriptWarning::CONSTANT_USED_AS_FUNCTION, p_call->line, callee_name, original_type.to_string()); } else { _add_warning(GDScriptWarning::PROPERTY_USED_AS_FUNCTION, p_call->line, callee_name, original_type.to_string()); } } _add_warning(GDScriptWarning::UNSAFE_METHOD_ACCESS, p_call->line, callee_name, original_type.to_string()); _mark_line_as_unsafe(p_call->line); #endif // DEBUG_ENABLED return DataType(); } #ifdef DEBUG_ENABLED if (current_function && !for_completion && !is_static && p_call->arguments[0]->type == Node::TYPE_SELF && current_function->_static) { _set_error("Can't call non-static function from a static function.", p_call->line); return DataType(); } if (check_types && !is_static && !is_initializer && base_type.is_meta_type) { _set_error("Non-static function \"" + String(callee_name) + "\" can only be called from an instance.", p_call->line); return DataType(); } // Check signal emission for warnings if (callee_name == "emit_signal" && p_call->op == OperatorNode::OP_CALL && p_call->arguments[0]->type == Node::TYPE_SELF && p_call->arguments.size() >= 3 && p_call->arguments[2]->type == Node::TYPE_CONSTANT) { ConstantNode *sig = static_cast<ConstantNode *>(p_call->arguments[2]); String emitted = sig->value.get_type() == Variant::STRING ? sig->value.operator String() : ""; for (int i = 0; i < current_class->_signals.size(); i++) { if (current_class->_signals[i].name == emitted) { current_class->_signals.write[i].emissions += 1; break; } } } #endif // DEBUG_ENABLED } break; } #ifdef DEBUG_ENABLED if (!check_types) { return return_type; } if (arg_count < arg_types.size() - default_args_count) { _set_error("Too few arguments for \"" + callee_name + "()\" call. Expected at least " + itos(arg_types.size() - default_args_count) + ".", p_call->line); return return_type; } if (!is_vararg && arg_count > arg_types.size()) { _set_error("Too many arguments for \"" + callee_name + "()\" call. Expected at most " + itos(arg_types.size()) + ".", p_call->line); return return_type; } int arg_diff = p_call->arguments.size() - arg_count; for (int i = arg_diff; i < p_call->arguments.size(); i++) { DataType par_type = _reduce_node_type(p_call->arguments[i]); if ((i - arg_diff) >= arg_types.size()) { continue; } DataType arg_type = arg_types[i - arg_diff]; if (!par_type.has_type) { _mark_line_as_unsafe(p_call->line); if (par_type.may_yield && p_call->arguments[i]->type == Node::TYPE_OPERATOR) { _add_warning(GDScriptWarning::FUNCTION_MAY_YIELD, p_call->line, _find_function_name(static_cast<OperatorNode *>(p_call->arguments[i]))); } } else if (!_is_type_compatible(arg_types[i - arg_diff], par_type, true)) { // Supertypes are acceptable for dynamic compliance if (!_is_type_compatible(par_type, arg_types[i - arg_diff])) { _set_error("At \"" + callee_name + "()\" call, argument " + itos(i - arg_diff + 1) + ". The passed argument's type (" + par_type.to_string() + ") doesn't match the function's expected argument type (" + arg_types[i - arg_diff].to_string() + ").", p_call->line); return DataType(); } else { _mark_line_as_unsafe(p_call->line); } } else { if (arg_type.kind == DataType::BUILTIN && arg_type.builtin_type == Variant::INT && par_type.kind == DataType::BUILTIN && par_type.builtin_type == Variant::REAL) { _add_warning(GDScriptWarning::NARROWING_CONVERSION, p_call->line, callee_name); } } } #endif // DEBUG_ENABLED return return_type; } bool GDScriptParser::_get_member_type(const DataType &p_base_type, const StringName &p_member, DataType &r_member_type, bool *r_is_const) const { DataType base_type = p_base_type; // Check classes in current file ClassNode *base = nullptr; if (base_type.kind == DataType::CLASS) { base = base_type.class_type; } while (base) { if (base->constant_expressions.has(p_member)) { if (r_is_const) { *r_is_const = true; } r_member_type = base->constant_expressions[p_member].expression->get_datatype(); return true; } if (!base_type.is_meta_type) { for (int i = 0; i < base->variables.size(); i++) { if (base->variables[i].identifier == p_member) { r_member_type = base->variables[i].data_type; base->variables.write[i].usages += 1; return true; } } } else { for (int i = 0; i < base->subclasses.size(); i++) { ClassNode *c = base->subclasses[i]; if (c->name == p_member) { DataType class_type; class_type.has_type = true; class_type.is_constant = true; class_type.is_meta_type = true; class_type.kind = DataType::CLASS; class_type.class_type = c; r_member_type = class_type; return true; } } } base_type = base->base_type; if (base_type.kind == DataType::CLASS) { base = base_type.class_type; } else { break; } } Ref<GDScript> gds; if (base_type.kind == DataType::GDSCRIPT) { gds = base_type.script_type; if (gds.is_null() || !gds->is_valid()) { // GDScript wasn't properly compíled, don't bother trying return false; } } Ref<Script> scr; if (base_type.kind == DataType::SCRIPT) { scr = base_type.script_type; } StringName native; if (base_type.kind == DataType::NATIVE) { native = base_type.native_type; } // Check GDScripts while (gds.is_valid()) { if (gds->get_constants().has(p_member)) { Variant c = gds->get_constants()[p_member]; r_member_type = _type_from_variant(c); return true; } if (!base_type.is_meta_type) { if (gds->get_members().has(p_member)) { r_member_type = _type_from_gdtype(gds->get_member_type(p_member)); return true; } } native = gds->get_instance_base_type(); if (gds->get_base_script().is_valid()) { gds = gds->get_base_script(); scr = gds->get_base_script(); bool is_meta = base_type.is_meta_type; base_type = _type_from_variant(scr.operator Variant()); base_type.is_meta_type = is_meta; } else { break; } } #define IS_USAGE_MEMBER(m_usage) (!(m_usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_CATEGORY))) // Check other script types while (scr.is_valid()) { Map<StringName, Variant> constants; scr->get_constants(&constants); if (constants.has(p_member)) { r_member_type = _type_from_variant(constants[p_member]); return true; } List<PropertyInfo> properties; scr->get_script_property_list(&properties); for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { if (E->get().name == p_member && IS_USAGE_MEMBER(E->get().usage)) { r_member_type = _type_from_property(E->get()); return true; } } base_type = _type_from_variant(scr.operator Variant()); native = scr->get_instance_base_type(); scr = scr->get_base_script(); } if (native == StringName()) { // Empty native class, might happen in some Script implementations // Just ignore it return false; } // Check ClassDB if (!ClassDB::class_exists(native)) { native = "_" + native.operator String(); } if (!ClassDB::class_exists(native)) { if (!check_types) { return false; } ERR_FAIL_V_MSG(false, "Parser bug: Class \"" + String(native) + "\" not found."); } bool valid = false; ClassDB::get_integer_constant(native, p_member, &valid); if (valid) { DataType ct; ct.has_type = true; ct.is_constant = true; ct.kind = DataType::BUILTIN; ct.builtin_type = Variant::INT; r_member_type = ct; return true; } if (!base_type.is_meta_type) { List<PropertyInfo> properties; ClassDB::get_property_list(native, &properties); for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { if (E->get().name == p_member && IS_USAGE_MEMBER(E->get().usage)) { // Check if a getter exists StringName getter_name = ClassDB::get_property_getter(native, p_member); if (getter_name != StringName()) { // Use the getter return type MethodBind *getter_method = ClassDB::get_method(native, getter_name); if (getter_method) { r_member_type = _type_from_property(getter_method->get_return_info()); } else { r_member_type = DataType(); } } else { r_member_type = _type_from_property(E->get()); } return true; } } } // If the base is a script, it might be trying to access members of the Script class itself if (p_base_type.is_meta_type && (p_base_type.kind == DataType::SCRIPT || p_base_type.kind == DataType::GDSCRIPT)) { native = p_base_type.script_type->get_class_name(); ClassDB::get_integer_constant(native, p_member, &valid); if (valid) { DataType ct; ct.has_type = true; ct.is_constant = true; ct.kind = DataType::BUILTIN; ct.builtin_type = Variant::INT; r_member_type = ct; return true; } List<PropertyInfo> properties; ClassDB::get_property_list(native, &properties); for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { if (E->get().name == p_member && IS_USAGE_MEMBER(E->get().usage)) { // Check if a getter exists StringName getter_name = ClassDB::get_property_getter(native, p_member); if (getter_name != StringName()) { // Use the getter return type MethodBind *getter_method = ClassDB::get_method(native, getter_name); if (getter_method) { r_member_type = _type_from_property(getter_method->get_return_info()); } else { r_member_type = DataType(); } } else { r_member_type = _type_from_property(E->get()); } return true; } } } #undef IS_USAGE_MEMBER return false; } GDScriptParser::DataType GDScriptParser::_reduce_identifier_type(const DataType *p_base_type, const StringName &p_identifier, int p_line, bool p_is_indexing) { if (p_base_type && !p_base_type->has_type) { return DataType(); } DataType base_type; DataType member_type; if (!p_base_type) { base_type.has_type = true; base_type.is_constant = true; base_type.kind = DataType::CLASS; base_type.class_type = current_class; } else { base_type = DataType(*p_base_type); } bool is_const = false; if (_get_member_type(base_type, p_identifier, member_type, &is_const)) { if (!p_base_type && current_function && current_function->_static && !is_const) { _set_error("Can't access member variable (\"" + p_identifier.operator String() + "\") from a static function.", p_line); return DataType(); } return member_type; } if (p_is_indexing) { // Don't look for globals since this is an indexed identifier return DataType(); } if (!p_base_type) { // Possibly this is a global, check before failing if (ClassDB::class_exists(p_identifier) || ClassDB::class_exists("_" + p_identifier.operator String())) { DataType result; result.has_type = true; result.is_constant = true; result.is_meta_type = true; if (Engine::get_singleton()->has_singleton(p_identifier) || Engine::get_singleton()->has_singleton("_" + p_identifier.operator String())) { result.is_meta_type = false; } result.kind = DataType::NATIVE; result.native_type = p_identifier; return result; } ClassNode *outer_class = current_class; while (outer_class) { if (outer_class->name == p_identifier) { DataType result; result.has_type = true; result.is_constant = true; result.is_meta_type = true; result.kind = DataType::CLASS; result.class_type = outer_class; return result; } if (outer_class->constant_expressions.has(p_identifier)) { return outer_class->constant_expressions[p_identifier].type; } for (int i = 0; i < outer_class->subclasses.size(); i++) { if (outer_class->subclasses[i] == current_class) { continue; } if (outer_class->subclasses[i]->name == p_identifier) { DataType result; result.has_type = true; result.is_constant = true; result.is_meta_type = true; result.kind = DataType::CLASS; result.class_type = outer_class->subclasses[i]; return result; } } outer_class = outer_class->owner; } if (ScriptServer::is_global_class(p_identifier)) { Ref<Script> scr = ResourceLoader::load(ScriptServer::get_global_class_path(p_identifier)); if (scr.is_valid()) { DataType result; result.has_type = true; result.script_type = scr; result.is_constant = true; result.is_meta_type = true; Ref<GDScript> gds = scr; if (gds.is_valid()) { if (!gds->is_valid()) { _set_error("The class \"" + p_identifier + "\" couldn't be fully loaded (script error or cyclic dependency)."); return DataType(); } result.kind = DataType::GDSCRIPT; } else { result.kind = DataType::SCRIPT; } return result; } _set_error("The class \"" + p_identifier + "\" was found in global scope, but its script couldn't be loaded."); return DataType(); } if (GDScriptLanguage::get_singleton()->get_global_map().has(p_identifier)) { int idx = GDScriptLanguage::get_singleton()->get_global_map()[p_identifier]; Variant g = GDScriptLanguage::get_singleton()->get_global_array()[idx]; return _type_from_variant(g); } if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(p_identifier)) { Variant g = GDScriptLanguage::get_singleton()->get_named_globals_map()[p_identifier]; return _type_from_variant(g); } // Non-tool singletons aren't loaded, check project settings List<PropertyInfo> props; ProjectSettings::get_singleton()->get_property_list(&props); for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { String s = E->get().name; if (!s.begins_with("autoload/")) { continue; } String name = s.get_slice("/", 1); if (name == p_identifier) { String script = ProjectSettings::get_singleton()->get(s); if (script.begins_with("*")) { script = script.right(1); } if (!script.begins_with("res://")) { script = "res://" + script; } Ref<Script> singleton = ResourceLoader::load(script); if (singleton.is_valid()) { DataType result; result.has_type = true; result.is_constant = true; result.script_type = singleton; Ref<GDScript> gds = singleton; if (gds.is_valid()) { if (!gds->is_valid()) { _set_error("Couldn't fully load the singleton script \"" + p_identifier + "\" (possible cyclic reference or parse error).", p_line); return DataType(); } result.kind = DataType::GDSCRIPT; } else { result.kind = DataType::SCRIPT; } } } } // This means looking in the current class, which type is always known _set_error("The identifier \"" + p_identifier.operator String() + "\" isn't declared in the current scope.", p_line); } #ifdef DEBUG_ENABLED { DataType tmp_type; List<DataType> arg_types; int argcount; bool _static; bool vararg; if (_get_function_signature(base_type, p_identifier, tmp_type, arg_types, argcount, _static, vararg)) { _add_warning(GDScriptWarning::FUNCTION_USED_AS_PROPERTY, p_line, p_identifier.operator String(), base_type.to_string()); } } #endif // DEBUG_ENABLED _mark_line_as_unsafe(p_line); return DataType(); } void GDScriptParser::_check_class_level_types(ClassNode *p_class) { // Names of internal object properties that we check to avoid overriding them. // "__meta__" could also be in here, but since it doesn't really affect object metadata, // it is okay to override it on script. StringName script_name = CoreStringNames::get_singleton()->_script; _mark_line_as_safe(p_class->line); // Constants for (Map<StringName, ClassNode::Constant>::Element *E = p_class->constant_expressions.front(); E; E = E->next()) { ClassNode::Constant &c = E->get(); _mark_line_as_safe(c.expression->line); DataType cont = _resolve_type(c.type, c.expression->line); DataType expr = _resolve_type(c.expression->get_datatype(), c.expression->line); if (check_types && !_is_type_compatible(cont, expr)) { _set_error("The constant value type (" + expr.to_string() + ") isn't compatible with declared type (" + cont.to_string() + ").", c.expression->line); return; } expr.is_constant = true; c.type = expr; c.expression->set_datatype(expr); DataType tmp; const StringName &constant_name = E->key(); if (constant_name == script_name || _get_member_type(p_class->base_type, constant_name, tmp)) { _set_error("The member \"" + String(constant_name) + "\" already exists in a parent class.", c.expression->line); return; } } // Function declarations for (int i = 0; i < p_class->static_functions.size(); i++) { _check_function_types(p_class->static_functions[i]); if (error_set) { return; } } for (int i = 0; i < p_class->functions.size(); i++) { _check_function_types(p_class->functions[i]); if (error_set) { return; } } // Class variables for (int i = 0; i < p_class->variables.size(); i++) { ClassNode::Member &v = p_class->variables.write[i]; DataType tmp; if (v.identifier == script_name || _get_member_type(p_class->base_type, v.identifier, tmp)) { _set_error("The member \"" + String(v.identifier) + "\" already exists in a parent class.", v.line); return; } _mark_line_as_safe(v.line); v.data_type = _resolve_type(v.data_type, v.line); v.initial_assignment->arguments[0]->set_datatype(v.data_type); if (v.expression) { DataType expr_type = _reduce_node_type(v.expression); if (check_types && !_is_type_compatible(v.data_type, expr_type)) { // Try supertype test if (_is_type_compatible(expr_type, v.data_type)) { _mark_line_as_unsafe(v.line); } else { // Try with implicit conversion if (v.data_type.kind != DataType::BUILTIN || !_is_type_compatible(v.data_type, expr_type, true)) { _set_error("The assigned expression's type (" + expr_type.to_string() + ") doesn't match the variable's type (" + v.data_type.to_string() + ").", v.line); return; } // Replace assignment with implicit conversion BuiltInFunctionNode *convert = alloc_node<BuiltInFunctionNode>(); convert->line = v.line; convert->function = GDScriptFunctions::TYPE_CONVERT; ConstantNode *tgt_type = alloc_node<ConstantNode>(); tgt_type->line = v.line; tgt_type->value = (int)v.data_type.builtin_type; OperatorNode *convert_call = alloc_node<OperatorNode>(); convert_call->line = v.line; convert_call->op = OperatorNode::OP_CALL; convert_call->arguments.push_back(convert); convert_call->arguments.push_back(v.expression); convert_call->arguments.push_back(tgt_type); v.expression = convert_call; v.initial_assignment->arguments.write[1] = convert_call; } } if (v.data_type.infer_type) { if (!expr_type.has_type) { _set_error("The assigned value doesn't have a set type; the variable type can't be inferred.", v.line); return; } if (expr_type.kind == DataType::BUILTIN && expr_type.builtin_type == Variant::NIL) { _set_error("The variable type cannot be inferred because its value is \"null\".", v.line); return; } v.data_type = expr_type; v.data_type.is_constant = false; } } // Check export hint if (v.data_type.has_type && v._export.type != Variant::NIL) { DataType export_type = _type_from_property(v._export); if (!_is_type_compatible(v.data_type, export_type, true)) { _set_error("The export hint's type (" + export_type.to_string() + ") doesn't match the variable's type (" + v.data_type.to_string() + ").", v.line); return; } } // Setter and getter if (v.setter == StringName() && v.getter == StringName()) { continue; } bool found_getter = false; bool found_setter = false; for (int j = 0; j < p_class->functions.size(); j++) { if (v.setter == p_class->functions[j]->name) { found_setter = true; FunctionNode *setter = p_class->functions[j]; if (setter->get_required_argument_count() != 1 && !(setter->get_required_argument_count() == 0 && setter->default_values.size() > 0)) { _set_error("The setter function needs to receive exactly 1 argument. See \"" + setter->name + "()\" definition at line " + itos(setter->line) + ".", v.line); return; } if (!_is_type_compatible(v.data_type, setter->argument_types[0])) { _set_error("The setter argument's type (" + setter->argument_types[0].to_string() + ") doesn't match the variable's type (" + v.data_type.to_string() + "). See \"" + setter->name + "()\" definition at line " + itos(setter->line) + ".", v.line); return; } continue; } if (v.getter == p_class->functions[j]->name) { found_getter = true; FunctionNode *getter = p_class->functions[j]; if (getter->get_required_argument_count() != 0) { _set_error("The getter function can't receive arguments. See \"" + getter->name + "()\" definition at line " + itos(getter->line) + ".", v.line); return; } if (!_is_type_compatible(v.data_type, getter->get_datatype())) { _set_error("The getter return type (" + getter->get_datatype().to_string() + ") doesn't match the variable's type (" + v.data_type.to_string() + "). See \"" + getter->name + "()\" definition at line " + itos(getter->line) + ".", v.line); return; } } if (found_getter && found_setter) { break; } } if ((found_getter || v.getter == StringName()) && (found_setter || v.setter == StringName())) { continue; } // Check for static functions for (int j = 0; j < p_class->static_functions.size(); j++) { if (v.setter == p_class->static_functions[j]->name) { FunctionNode *setter = p_class->static_functions[j]; _set_error("The setter can't be a static function. See \"" + setter->name + "()\" definition at line " + itos(setter->line) + ".", v.line); return; } if (v.getter == p_class->static_functions[j]->name) { FunctionNode *getter = p_class->static_functions[j]; _set_error("The getter can't be a static function. See \"" + getter->name + "()\" definition at line " + itos(getter->line) + ".", v.line); return; } } if (!found_setter && v.setter != StringName()) { _set_error("The setter function isn't defined.", v.line); return; } if (!found_getter && v.getter != StringName()) { _set_error("The getter function isn't defined.", v.line); return; } } // Signals DataType base = p_class->base_type; while (base.kind == DataType::CLASS) { ClassNode *base_class = base.class_type; for (int i = 0; i < p_class->_signals.size(); i++) { for (int j = 0; j < base_class->_signals.size(); j++) { if (p_class->_signals[i].name == base_class->_signals[j].name) { _set_error("The signal \"" + p_class->_signals[i].name + "\" already exists in a parent class.", p_class->_signals[i].line); return; } } } base = base_class->base_type; } StringName native; if (base.kind == DataType::GDSCRIPT || base.kind == DataType::SCRIPT) { Ref<Script> scr = base.script_type; if (scr.is_valid() && scr->is_valid()) { native = scr->get_instance_base_type(); for (int i = 0; i < p_class->_signals.size(); i++) { if (scr->has_script_signal(p_class->_signals[i].name)) { _set_error("The signal \"" + p_class->_signals[i].name + "\" already exists in a parent class.", p_class->_signals[i].line); return; } } } } else if (base.kind == DataType::NATIVE) { native = base.native_type; } if (native != StringName()) { for (int i = 0; i < p_class->_signals.size(); i++) { if (ClassDB::has_signal(native, p_class->_signals[i].name)) { _set_error("The signal \"" + p_class->_signals[i].name + "\" already exists in a parent class.", p_class->_signals[i].line); return; } } } // Inner classes for (int i = 0; i < p_class->subclasses.size(); i++) { current_class = p_class->subclasses[i]; _check_class_level_types(current_class); if (error_set) { return; } current_class = p_class; } } void GDScriptParser::_check_function_types(FunctionNode *p_function) { p_function->return_type = _resolve_type(p_function->return_type, p_function->line); // Arguments int defaults_ofs = p_function->arguments.size() - p_function->default_values.size(); for (int i = 0; i < p_function->arguments.size(); i++) { if (i < defaults_ofs) { p_function->argument_types.write[i] = _resolve_type(p_function->argument_types[i], p_function->line); } else { if (p_function->default_values[i - defaults_ofs]->type != Node::TYPE_OPERATOR) { _set_error("Parser bug: invalid argument default value.", p_function->line, p_function->column); return; } OperatorNode *op = static_cast<OperatorNode *>(p_function->default_values[i - defaults_ofs]); if (op->op != OperatorNode::OP_ASSIGN || op->arguments.size() != 2) { _set_error("Parser bug: invalid argument default value operation.", p_function->line); return; } DataType def_type = _reduce_node_type(op->arguments[1]); if (p_function->argument_types[i].infer_type) { def_type.is_constant = false; p_function->argument_types.write[i] = def_type; } else { p_function->argument_types.write[i] = _resolve_type(p_function->argument_types[i], p_function->line); if (!_is_type_compatible(p_function->argument_types[i], def_type, true)) { String arg_name = p_function->arguments[i]; _set_error("Value type (" + def_type.to_string() + ") doesn't match the type of argument '" + arg_name + "' (" + p_function->argument_types[i].to_string() + ").", p_function->line); } } } #ifdef DEBUG_ENABLED if (p_function->arguments_usage[i] == 0 && !p_function->arguments[i].operator String().begins_with("_")) { _add_warning(GDScriptWarning::UNUSED_ARGUMENT, p_function->line, p_function->name, p_function->arguments[i].operator String()); } for (int j = 0; j < current_class->variables.size(); j++) { if (current_class->variables[j].identifier == p_function->arguments[i]) { _add_warning(GDScriptWarning::SHADOWED_VARIABLE, p_function->line, p_function->arguments[i], itos(current_class->variables[j].line)); } } #endif // DEBUG_ENABLED } if (!(p_function->name == "_init")) { // Signature for the initializer may vary #ifdef DEBUG_ENABLED DataType return_type; List<DataType> arg_types; int default_arg_count = 0; bool _static = false; bool vararg = false; DataType base_type = current_class->base_type; if (_get_function_signature(base_type, p_function->name, return_type, arg_types, default_arg_count, _static, vararg)) { bool valid = _static == p_function->_static; valid = valid && return_type == p_function->return_type; int argsize_diff = p_function->arguments.size() - arg_types.size(); valid = valid && argsize_diff >= 0; valid = valid && p_function->default_values.size() >= default_arg_count + argsize_diff; int i = 0; for (List<DataType>::Element *E = arg_types.front(); valid && E; E = E->next()) { valid = valid && E->get() == p_function->argument_types[i++]; } if (!valid) { String parent_signature = return_type.has_type ? return_type.to_string() : "Variant"; if (parent_signature == "null") { parent_signature = "void"; } parent_signature += " " + p_function->name + "("; if (arg_types.size()) { int j = 0; for (List<DataType>::Element *E = arg_types.front(); E; E = E->next()) { if (E != arg_types.front()) { parent_signature += ", "; } String arg = E->get().to_string(); if (arg == "null" || arg == "var") { arg = "Variant"; } parent_signature += arg; if (j == arg_types.size() - default_arg_count) { parent_signature += "=default"; } j++; } } parent_signature += ")"; _set_error("The function signature doesn't match the parent. Parent signature is: \"" + parent_signature + "\".", p_function->line); return; } } #endif // DEBUG_ENABLED } else { if (p_function->return_type.has_type && (p_function->return_type.kind != DataType::BUILTIN || p_function->return_type.builtin_type != Variant::NIL)) { _set_error("The constructor can't return a value.", p_function->line); return; } } if (p_function->return_type.has_type && (p_function->return_type.kind != DataType::BUILTIN || p_function->return_type.builtin_type != Variant::NIL)) { if (!p_function->body->has_return) { _set_error("A non-void function must return a value in all possible paths.", p_function->line); return; } } if (p_function->has_yield) { // yield() will make the function return a GDScriptFunctionState, so the type is ambiguous p_function->return_type.has_type = false; p_function->return_type.may_yield = true; } } void GDScriptParser::_check_class_blocks_types(ClassNode *p_class) { // Function blocks for (int i = 0; i < p_class->static_functions.size(); i++) { current_function = p_class->static_functions[i]; current_block = current_function->body; _mark_line_as_safe(current_function->line); _check_block_types(current_block); current_block = nullptr; current_function = nullptr; if (error_set) { return; } } for (int i = 0; i < p_class->functions.size(); i++) { current_function = p_class->functions[i]; current_block = current_function->body; _mark_line_as_safe(current_function->line); _check_block_types(current_block); current_block = nullptr; current_function = nullptr; if (error_set) { return; } } #ifdef DEBUG_ENABLED // Warnings for (int i = 0; i < p_class->variables.size(); i++) { if (p_class->variables[i].usages == 0) { _add_warning(GDScriptWarning::UNUSED_CLASS_VARIABLE, p_class->variables[i].line, p_class->variables[i].identifier); } } for (int i = 0; i < p_class->_signals.size(); i++) { if (p_class->_signals[i].emissions == 0) { _add_warning(GDScriptWarning::UNUSED_SIGNAL, p_class->_signals[i].line, p_class->_signals[i].name); } } #endif // DEBUG_ENABLED // Inner classes for (int i = 0; i < p_class->subclasses.size(); i++) { current_class = p_class->subclasses[i]; _check_class_blocks_types(current_class); if (error_set) { return; } current_class = p_class; } } #ifdef DEBUG_ENABLED static String _find_function_name(const GDScriptParser::OperatorNode *p_call) { switch (p_call->arguments[0]->type) { case GDScriptParser::Node::TYPE_TYPE: { return Variant::get_type_name(static_cast<GDScriptParser::TypeNode *>(p_call->arguments[0])->vtype); } break; case GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION: { return GDScriptFunctions::get_func_name(static_cast<GDScriptParser::BuiltInFunctionNode *>(p_call->arguments[0])->function); } break; default: { int id_index = p_call->op == GDScriptParser::OperatorNode::OP_PARENT_CALL ? 0 : 1; if (p_call->arguments.size() > id_index && p_call->arguments[id_index]->type == GDScriptParser::Node::TYPE_IDENTIFIER) { return static_cast<GDScriptParser::IdentifierNode *>(p_call->arguments[id_index])->name; } } break; } return String(); } #endif // DEBUG_ENABLED void GDScriptParser::_check_block_types(BlockNode *p_block) { Node *last_var_assign = nullptr; // Check each statement for (int z = 0; z < p_block->statements.size(); z++) { Node *statement = p_block->statements[z]; switch (statement->type) { case Node::TYPE_NEWLINE: case Node::TYPE_BREAKPOINT: { // Nothing to do } break; case Node::TYPE_ASSERT: { AssertNode *an = static_cast<AssertNode *>(statement); _mark_line_as_safe(an->line); _reduce_node_type(an->condition); _reduce_node_type(an->message); } break; case Node::TYPE_LOCAL_VAR: { LocalVarNode *lv = static_cast<LocalVarNode *>(statement); lv->datatype = _resolve_type(lv->datatype, lv->line); _mark_line_as_safe(lv->line); last_var_assign = lv->assign; if (lv->assign) { lv->assign_op->arguments[0]->set_datatype(lv->datatype); DataType assign_type = _reduce_node_type(lv->assign); #ifdef DEBUG_ENABLED if (assign_type.has_type && assign_type.kind == DataType::BUILTIN && assign_type.builtin_type == Variant::NIL) { if (lv->assign->type == Node::TYPE_OPERATOR) { OperatorNode *call = static_cast<OperatorNode *>(lv->assign); if (call->op == OperatorNode::OP_CALL || call->op == OperatorNode::OP_PARENT_CALL) { _add_warning(GDScriptWarning::VOID_ASSIGNMENT, lv->line, _find_function_name(call)); } } } if (lv->datatype.has_type && assign_type.may_yield && lv->assign->type == Node::TYPE_OPERATOR) { _add_warning(GDScriptWarning::FUNCTION_MAY_YIELD, lv->line, _find_function_name(static_cast<OperatorNode *>(lv->assign))); } for (int i = 0; i < current_class->variables.size(); i++) { if (current_class->variables[i].identifier == lv->name) { _add_warning(GDScriptWarning::SHADOWED_VARIABLE, lv->line, lv->name, itos(current_class->variables[i].line)); } } #endif // DEBUG_ENABLED if (!_is_type_compatible(lv->datatype, assign_type)) { // Try supertype test if (_is_type_compatible(assign_type, lv->datatype)) { _mark_line_as_unsafe(lv->line); } else { // Try implicit conversion if (lv->datatype.kind != DataType::BUILTIN || !_is_type_compatible(lv->datatype, assign_type, true)) { _set_error("The assigned value type (" + assign_type.to_string() + ") doesn't match the variable's type (" + lv->datatype.to_string() + ").", lv->line); return; } // Replace assignment with implicit conversion BuiltInFunctionNode *convert = alloc_node<BuiltInFunctionNode>(); convert->line = lv->line; convert->function = GDScriptFunctions::TYPE_CONVERT; ConstantNode *tgt_type = alloc_node<ConstantNode>(); tgt_type->line = lv->line; tgt_type->value = (int)lv->datatype.builtin_type; OperatorNode *convert_call = alloc_node<OperatorNode>(); convert_call->line = lv->line; convert_call->op = OperatorNode::OP_CALL; convert_call->arguments.push_back(convert); convert_call->arguments.push_back(lv->assign); convert_call->arguments.push_back(tgt_type); lv->assign = convert_call; lv->assign_op->arguments.write[1] = convert_call; #ifdef DEBUG_ENABLED if (lv->datatype.builtin_type == Variant::INT && assign_type.builtin_type == Variant::REAL) { _add_warning(GDScriptWarning::NARROWING_CONVERSION, lv->line); } #endif // DEBUG_ENABLED } } if (lv->datatype.infer_type) { if (!assign_type.has_type) { _set_error("The assigned value doesn't have a set type; the variable type can't be inferred.", lv->line); return; } if (assign_type.kind == DataType::BUILTIN && assign_type.builtin_type == Variant::NIL) { _set_error("The variable type cannot be inferred because its value is \"null\".", lv->line); return; } lv->datatype = assign_type; lv->datatype.is_constant = false; } if (lv->datatype.has_type && !assign_type.has_type) { _mark_line_as_unsafe(lv->line); } } } break; case Node::TYPE_OPERATOR: { OperatorNode *op = static_cast<OperatorNode *>(statement); switch (op->op) { case OperatorNode::OP_ASSIGN: case OperatorNode::OP_ASSIGN_ADD: case OperatorNode::OP_ASSIGN_SUB: case OperatorNode::OP_ASSIGN_MUL: case OperatorNode::OP_ASSIGN_DIV: case OperatorNode::OP_ASSIGN_MOD: case OperatorNode::OP_ASSIGN_SHIFT_LEFT: case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: case OperatorNode::OP_ASSIGN_BIT_AND: case OperatorNode::OP_ASSIGN_BIT_OR: case OperatorNode::OP_ASSIGN_BIT_XOR: { if (op->arguments.size() < 2) { _set_error("Parser bug: operation without enough arguments.", op->line, op->column); return; } if (op->arguments[1] == last_var_assign) { // Assignment was already checked break; } _mark_line_as_safe(op->line); DataType lh_type = _reduce_node_type(op->arguments[0]); if (error_set) { return; } if (check_types) { if (!lh_type.has_type) { if (op->arguments[0]->type == Node::TYPE_OPERATOR) { _mark_line_as_unsafe(op->line); } } if (lh_type.is_constant) { _set_error("Can't assign a new value to a constant.", op->line); return; } } DataType rh_type; if (op->op != OperatorNode::OP_ASSIGN) { // Validate operation DataType arg_type = _reduce_node_type(op->arguments[1]); if (!arg_type.has_type) { _mark_line_as_unsafe(op->line); break; } Variant::Operator oper = _get_variant_operation(op->op); bool valid = false; rh_type = _get_operation_type(oper, lh_type, arg_type, valid); if (check_types && !valid) { _set_error("Invalid operand types (\"" + lh_type.to_string() + "\" and \"" + arg_type.to_string() + "\") to assignment operator \"" + Variant::get_operator_name(oper) + "\".", op->line); return; } } else { rh_type = _reduce_node_type(op->arguments[1]); } #ifdef DEBUG_ENABLED if (rh_type.has_type && rh_type.kind == DataType::BUILTIN && rh_type.builtin_type == Variant::NIL) { if (op->arguments[1]->type == Node::TYPE_OPERATOR) { OperatorNode *call = static_cast<OperatorNode *>(op->arguments[1]); if (call->op == OperatorNode::OP_CALL || call->op == OperatorNode::OP_PARENT_CALL) { _add_warning(GDScriptWarning::VOID_ASSIGNMENT, op->line, _find_function_name(call)); } } } if (lh_type.has_type && rh_type.may_yield && op->arguments[1]->type == Node::TYPE_OPERATOR) { _add_warning(GDScriptWarning::FUNCTION_MAY_YIELD, op->line, _find_function_name(static_cast<OperatorNode *>(op->arguments[1]))); } #endif // DEBUG_ENABLED bool type_match = lh_type.has_type && rh_type.has_type; if (check_types && !_is_type_compatible(lh_type, rh_type)) { type_match = false; // Try supertype test if (_is_type_compatible(rh_type, lh_type)) { _mark_line_as_unsafe(op->line); } else { // Try implicit conversion if (lh_type.kind != DataType::BUILTIN || !_is_type_compatible(lh_type, rh_type, true)) { _set_error("The assigned value's type (" + rh_type.to_string() + ") doesn't match the variable's type (" + lh_type.to_string() + ").", op->line); return; } if (op->op == OperatorNode::OP_ASSIGN) { // Replace assignment with implicit conversion BuiltInFunctionNode *convert = alloc_node<BuiltInFunctionNode>(); convert->line = op->line; convert->function = GDScriptFunctions::TYPE_CONVERT; ConstantNode *tgt_type = alloc_node<ConstantNode>(); tgt_type->line = op->line; tgt_type->value = (int)lh_type.builtin_type; OperatorNode *convert_call = alloc_node<OperatorNode>(); convert_call->line = op->line; convert_call->op = OperatorNode::OP_CALL; convert_call->arguments.push_back(convert); convert_call->arguments.push_back(op->arguments[1]); convert_call->arguments.push_back(tgt_type); op->arguments.write[1] = convert_call; type_match = true; // Since we are converting, the type is matching } #ifdef DEBUG_ENABLED if (lh_type.builtin_type == Variant::INT && rh_type.builtin_type == Variant::REAL) { _add_warning(GDScriptWarning::NARROWING_CONVERSION, op->line); } #endif // DEBUG_ENABLED } } #ifdef DEBUG_ENABLED if (!rh_type.has_type && (op->op != OperatorNode::OP_ASSIGN || lh_type.has_type || op->arguments[0]->type == Node::TYPE_OPERATOR)) { _mark_line_as_unsafe(op->line); } #endif // DEBUG_ENABLED op->datatype.has_type = type_match; } break; case OperatorNode::OP_CALL: case OperatorNode::OP_PARENT_CALL: { _mark_line_as_safe(op->line); DataType func_type = _reduce_function_call_type(op); #ifdef DEBUG_ENABLED if (func_type.has_type && (func_type.kind != DataType::BUILTIN || func_type.builtin_type != Variant::NIL)) { // Figure out function name for warning String func_name = _find_function_name(op); if (func_name.empty()) { func_name = "<undetected name>"; } _add_warning(GDScriptWarning::RETURN_VALUE_DISCARDED, op->line, func_name); } #endif // DEBUG_ENABLED if (error_set) { return; } } break; case OperatorNode::OP_YIELD: { _mark_line_as_safe(op->line); _reduce_node_type(op); } break; default: { _mark_line_as_safe(op->line); _reduce_node_type(op); // Test for safety anyway #ifdef DEBUG_ENABLED if (op->op == OperatorNode::OP_TERNARY_IF) { _add_warning(GDScriptWarning::STANDALONE_TERNARY, statement->line); } else { _add_warning(GDScriptWarning::STANDALONE_EXPRESSION, statement->line); } #endif // DEBUG_ENABLED } } } break; case Node::TYPE_CONTROL_FLOW: { ControlFlowNode *cf = static_cast<ControlFlowNode *>(statement); _mark_line_as_safe(cf->line); switch (cf->cf_type) { case ControlFlowNode::CF_RETURN: { DataType function_type = current_function->get_datatype(); DataType ret_type; if (cf->arguments.size() > 0) { ret_type = _reduce_node_type(cf->arguments[0]); if (error_set) { return; } } if (!function_type.has_type) { break; } if (function_type.kind == DataType::BUILTIN && function_type.builtin_type == Variant::NIL) { // Return void, should not have arguments if (cf->arguments.size() > 0) { _set_error("A void function cannot return a value.", cf->line, cf->column); return; } } else { // Return something, cannot be empty if (cf->arguments.size() == 0) { _set_error("A non-void function must return a value.", cf->line, cf->column); return; } if (!_is_type_compatible(function_type, ret_type)) { _set_error("The returned value type (" + ret_type.to_string() + ") doesn't match the function return type (" + function_type.to_string() + ").", cf->line, cf->column); return; } } } break; case ControlFlowNode::CF_MATCH: { MatchNode *match_node = cf->match; _transform_match_statment(match_node); } break; default: { if (cf->body_else) { _mark_line_as_safe(cf->body_else->line); } for (int i = 0; i < cf->arguments.size(); i++) { _reduce_node_type(cf->arguments[i]); } } break; } } break; case Node::TYPE_CONSTANT: { ConstantNode *cn = static_cast<ConstantNode *>(statement); // Strings are fine since they can be multiline comments if (cn->value.get_type() == Variant::STRING) { break; } FALLTHROUGH; } default: { _mark_line_as_safe(statement->line); _reduce_node_type(statement); // Test for safety anyway #ifdef DEBUG_ENABLED _add_warning(GDScriptWarning::STANDALONE_EXPRESSION, statement->line); #endif // DEBUG_ENABLED } } } // Parse sub blocks for (int i = 0; i < p_block->sub_blocks.size(); i++) { current_block = p_block->sub_blocks[i]; _check_block_types(current_block); current_block = p_block; if (error_set) { return; } } #ifdef DEBUG_ENABLED // Warnings check for (Map<StringName, LocalVarNode *>::Element *E = p_block->variables.front(); E; E = E->next()) { LocalVarNode *lv = E->get(); if (!lv->name.operator String().begins_with("_")) { if (lv->usages == 0) { _add_warning(GDScriptWarning::UNUSED_VARIABLE, lv->line, lv->name); } else if (lv->assignments == 0) { _add_warning(GDScriptWarning::UNASSIGNED_VARIABLE, lv->line, lv->name); } } } #endif // DEBUG_ENABLED } void GDScriptParser::_set_error(const String &p_error, int p_line, int p_column) { if (error_set) { return; //allow no further errors } error = p_error; error_line = p_line < 0 ? tokenizer->get_token_line() : p_line; error_column = p_column < 0 ? tokenizer->get_token_column() : p_column; error_set = true; } #ifdef DEBUG_ENABLED void GDScriptParser::_add_warning(int p_code, int p_line, const String &p_symbol1, const String &p_symbol2, const String &p_symbol3, const String &p_symbol4) { Vector<String> symbols; if (!p_symbol1.empty()) { symbols.push_back(p_symbol1); } if (!p_symbol2.empty()) { symbols.push_back(p_symbol2); } if (!p_symbol3.empty()) { symbols.push_back(p_symbol3); } if (!p_symbol4.empty()) { symbols.push_back(p_symbol4); } _add_warning(p_code, p_line, symbols); } void GDScriptParser::_add_warning(int p_code, int p_line, const Vector<String> &p_symbols) { if (GLOBAL_GET("debug/gdscript/warnings/exclude_addons").booleanize() && base_path.begins_with("res://addons/")) { return; } if (tokenizer->is_ignoring_warnings() || !GLOBAL_GET("debug/gdscript/warnings/enable").booleanize()) { return; } String warn_name = GDScriptWarning::get_name_from_code((GDScriptWarning::Code)p_code).to_lower(); if (tokenizer->get_warning_global_skips().has(warn_name)) { return; } if (!GLOBAL_GET("debug/gdscript/warnings/" + warn_name)) { return; } GDScriptWarning warn; warn.code = (GDScriptWarning::Code)p_code; warn.symbols = p_symbols; warn.line = p_line == -1 ? tokenizer->get_token_line() : p_line; List<GDScriptWarning>::Element *before = nullptr; for (List<GDScriptWarning>::Element *E = warnings.front(); E; E = E->next()) { if (E->get().line > warn.line) { break; } before = E; } if (before) { warnings.insert_after(before, warn); } else { warnings.push_front(warn); } } #endif // DEBUG_ENABLED String GDScriptParser::get_error() const { return error; } int GDScriptParser::get_error_line() const { return error_line; } int GDScriptParser::get_error_column() const { return error_column; } bool GDScriptParser::has_error() const { return error_set; } Error GDScriptParser::_parse(const String &p_base_path) { base_path = p_base_path; //assume class ClassNode *main_class = alloc_node<ClassNode>(); main_class->initializer = alloc_node<BlockNode>(); main_class->initializer->parent_class = main_class; main_class->ready = alloc_node<BlockNode>(); main_class->ready->parent_class = main_class; current_class = main_class; _parse_class(main_class); if (tokenizer->get_token() == GDScriptTokenizer::TK_ERROR) { error_set = false; _set_error("Parse error: " + tokenizer->get_token_error()); } bool for_completion_error_set = false; if (error_set && for_completion) { for_completion_error_set = true; error_set = false; } if (error_set) { return ERR_PARSE_ERROR; } if (dependencies_only) { return OK; } _determine_inheritance(main_class); if (error_set) { return ERR_PARSE_ERROR; } current_class = main_class; current_function = nullptr; current_block = nullptr; if (for_completion) { check_types = false; } // Resolve all class-level stuff before getting into function blocks _check_class_level_types(main_class); if (error_set) { return ERR_PARSE_ERROR; } // Resolve the function blocks _check_class_blocks_types(main_class); if (for_completion_error_set) { error_set = true; } if (error_set) { return ERR_PARSE_ERROR; } #ifdef DEBUG_ENABLED // Resolve warning ignores Vector<Pair<int, String>> warning_skips = tokenizer->get_warning_skips(); bool warning_is_error = GLOBAL_GET("debug/gdscript/warnings/treat_warnings_as_errors").booleanize(); for (List<GDScriptWarning>::Element *E = warnings.front(); E;) { GDScriptWarning &w = E->get(); int skip_index = -1; for (int i = 0; i < warning_skips.size(); i++) { if (warning_skips[i].first > w.line) { break; } skip_index = i; } List<GDScriptWarning>::Element *next = E->next(); bool erase = false; if (skip_index != -1) { if (warning_skips[skip_index].second == GDScriptWarning::get_name_from_code(w.code).to_lower()) { erase = true; } warning_skips.remove(skip_index); } if (erase) { warnings.erase(E); } else if (warning_is_error) { _set_error(w.get_message() + " (warning treated as error)", w.line); return ERR_PARSE_ERROR; } E = next; } #endif // DEBUG_ENABLED return OK; } Error GDScriptParser::parse_bytecode(const Vector<uint8_t> &p_bytecode, const String &p_base_path, const String &p_self_path) { clear(); self_path = p_self_path; GDScriptTokenizerBuffer *tb = memnew(GDScriptTokenizerBuffer); tb->set_code_buffer(p_bytecode); tokenizer = tb; Error ret = _parse(p_base_path); memdelete(tb); tokenizer = nullptr; return ret; } Error GDScriptParser::parse(const String &p_code, const String &p_base_path, bool p_just_validate, const String &p_self_path, bool p_for_completion, Set<int> *r_safe_lines, bool p_dependencies_only) { clear(); self_path = p_self_path; GDScriptTokenizerText *tt = memnew(GDScriptTokenizerText); tt->set_code(p_code); validating = p_just_validate; for_completion = p_for_completion; dependencies_only = p_dependencies_only; #ifdef DEBUG_ENABLED safe_lines = r_safe_lines; #endif // DEBUG_ENABLED tokenizer = tt; Error ret = _parse(p_base_path); memdelete(tt); tokenizer = nullptr; return ret; } bool GDScriptParser::is_tool_script() const { return (head && head->type == Node::TYPE_CLASS && static_cast<const ClassNode *>(head)->tool); } const GDScriptParser::Node *GDScriptParser::get_parse_tree() const { return head; } void GDScriptParser::clear() { while (list) { Node *l = list; list = list->next; memdelete(l); } head = nullptr; list = nullptr; completion_type = COMPLETION_NONE; completion_node = nullptr; completion_class = nullptr; completion_function = nullptr; completion_block = nullptr; current_block = nullptr; current_class = nullptr; completion_found = false; rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED; current_function = nullptr; validating = false; for_completion = false; error_set = false; indent_level.clear(); indent_level.push_back(IndentLevel(0, 0)); error_line = 0; error_column = 0; pending_newline = -1; parenthesis = 0; current_export.type = Variant::NIL; check_types = true; dependencies_only = false; dependencies.clear(); error = ""; #ifdef DEBUG_ENABLED safe_lines = nullptr; #endif // DEBUG_ENABLED } GDScriptParser::CompletionType GDScriptParser::get_completion_type() { return completion_type; } StringName GDScriptParser::get_completion_cursor() { return completion_cursor; } int GDScriptParser::get_completion_line() { return completion_line; } Variant::Type GDScriptParser::get_completion_built_in_constant() { return completion_built_in_constant; } GDScriptParser::Node *GDScriptParser::get_completion_node() { return completion_node; } GDScriptParser::BlockNode *GDScriptParser::get_completion_block() { return completion_block; } GDScriptParser::ClassNode *GDScriptParser::get_completion_class() { return completion_class; } GDScriptParser::FunctionNode *GDScriptParser::get_completion_function() { return completion_function; } int GDScriptParser::get_completion_argument_index() { return completion_argument; } int GDScriptParser::get_completion_identifier_is_function() { return completion_ident_is_call; } GDScriptParser::GDScriptParser() { head = nullptr; list = nullptr; tokenizer = nullptr; pending_newline = -1; clear(); } GDScriptParser::~GDScriptParser() { clear(); }
32.121746
624
0.646256
[ "render", "object", "vector", "transform", "3d" ]
33b876cd4f2580a8c90a97941753798bc4d132a0
10,262
cpp
C++
mp/src/game/shared/neo/neo_predicted_viewmodel.cpp
NotHosomi/neo
8c8eae467d82bd0f6562201d7aa7ff42e3924126
[ "Unlicense" ]
null
null
null
mp/src/game/shared/neo/neo_predicted_viewmodel.cpp
NotHosomi/neo
8c8eae467d82bd0f6562201d7aa7ff42e3924126
[ "Unlicense" ]
null
null
null
mp/src/game/shared/neo/neo_predicted_viewmodel.cpp
NotHosomi/neo
8c8eae467d82bd0f6562201d7aa7ff42e3924126
[ "Unlicense" ]
null
null
null
#include "cbase.h" #include "neo_predicted_viewmodel.h" #include "in_buttons.h" #include "neo_gamerules.h" #ifdef CLIENT_DLL #include "c_neo_player.h" #include "prediction.h" #include "iinput.h" #include "engine/ivdebugoverlay.h" #include "viewrender.h" #else #include "neo_player.h" #endif #ifdef CLIENT_DLL #include "model_types.h" #endif #include "weapon_hl2mpbase.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" LINK_ENTITY_TO_CLASS(neo_predicted_viewmodel, CNEOPredictedViewModel); IMPLEMENT_NETWORKCLASS_ALIASED( NEOPredictedViewModel, DT_NEOPredictedViewModel ) BEGIN_NETWORK_TABLE( CNEOPredictedViewModel, DT_NEOPredictedViewModel ) END_NETWORK_TABLE() CNEOPredictedViewModel::CNEOPredictedViewModel() { #ifdef CLIENT_DLL #ifdef DEBUG IMaterial *pass = materials->FindMaterial("dev/toc_cloakpass", TEXTURE_GROUP_CLIENT_EFFECTS); Assert(pass && pass->IsPrecached()); #endif AddToInterpolationList(); #endif m_flYPrevious = 0; m_flLastLeanTime = 0; } CNEOPredictedViewModel::~CNEOPredictedViewModel() { #ifdef CLIENT_DLL RemoveFromInterpolationList(); #endif } #ifdef CLIENT_DLL inline void CNEOPredictedViewModel::DrawRenderToTextureDebugInfo(IClientRenderable* pRenderable, const Vector& mins, const Vector& maxs, const Vector &rgbColor, const char *message, const Vector &vecOrigin) { // Get the object's basis Vector vec[3]; AngleVectors( pRenderable->GetRenderAngles(), &vec[0], &vec[1], &vec[2] ); vec[1] *= -1.0f; Vector vecSize; VectorSubtract( maxs, mins, vecSize ); //Vector vecOrigin = pRenderable->GetRenderOrigin() + renderOffset; Vector start, end, end2; VectorMA( vecOrigin, mins.x, vec[0], start ); VectorMA( start, mins.y, vec[1], start ); VectorMA( start, mins.z, vec[2], start ); VectorMA( start, vecSize.x, vec[0], end ); VectorMA( end, vecSize.z, vec[2], end2 ); debugoverlay->AddLineOverlay( start, end, rgbColor[0], rgbColor[1], rgbColor[2], true, 0.01 ); debugoverlay->AddLineOverlay( end2, end, rgbColor[0], rgbColor[1], rgbColor[2], true, 0.01 ); VectorMA( start, vecSize.y, vec[1], end ); VectorMA( end, vecSize.z, vec[2], end2 ); debugoverlay->AddLineOverlay( start, end, rgbColor[0], rgbColor[1], rgbColor[2], true, 0.01 ); debugoverlay->AddLineOverlay( end2, end, rgbColor[0], rgbColor[1], rgbColor[2], true, 0.01 ); VectorMA( start, vecSize.z, vec[2], end ); debugoverlay->AddLineOverlay( start, end, rgbColor[0], rgbColor[1], rgbColor[2], true, 0.01 ); start = end; VectorMA( start, vecSize.x, vec[0], end ); debugoverlay->AddLineOverlay( start, end, rgbColor[0], rgbColor[1], rgbColor[2], true, 0.01 ); VectorMA( start, vecSize.y, vec[1], end ); debugoverlay->AddLineOverlay( start, end, rgbColor[0], rgbColor[1], rgbColor[2], true, 0.01 ); VectorMA( end, vecSize.x, vec[0], start ); VectorMA( start, -vecSize.x, vec[0], end ); debugoverlay->AddLineOverlay( start, end, rgbColor[0], rgbColor[1], rgbColor[2], true, 0.01 ); VectorMA( start, -vecSize.y, vec[1], end ); debugoverlay->AddLineOverlay( start, end, rgbColor[0], rgbColor[1], rgbColor[2], true, 0.01 ); VectorMA( start, -vecSize.z, vec[2], end ); debugoverlay->AddLineOverlay( start, end, rgbColor[0], rgbColor[1], rgbColor[2], true, 0.01 ); start = end; VectorMA( start, -vecSize.x, vec[0], end ); debugoverlay->AddLineOverlay( start, end, rgbColor[0], rgbColor[1], rgbColor[2], true, 0.01 ); VectorMA( start, -vecSize.y, vec[1], end ); debugoverlay->AddLineOverlay( start, end, rgbColor[0], rgbColor[1], rgbColor[2], true, 0.01 ); C_BaseEntity *pEnt = pRenderable->GetIClientUnknown()->GetBaseEntity(); int lineOffset = V_stristr("end", message) ? 1 : 0; if ( pEnt ) { debugoverlay->AddTextOverlay( vecOrigin, lineOffset, "%s -- %d", message, pEnt->entindex() ); } else { debugoverlay->AddTextOverlay( vecOrigin, lineOffset, "%s -- %X", message, (size_t)pRenderable ); } } #endif ConVar neo_lean_debug_draw_hull("neo_lean_debug_draw_hull", "0", FCVAR_CHEAT | FCVAR_REPLICATED); ConVar neo_lean_speed("neo_lean_speed", "120", FCVAR_REPLICATED | FCVAR_CHEAT, "Lean speed (units/second)", true, 0.0, false, 2.0); // Original Neotokyo with the latest leftlean fix uses 7 for leftlean and 15 for rightlean yaw slide. ConVar neo_lean_yaw_peek_left_amount("neo_lean_yaw_peek_left_amount", "7.0", FCVAR_REPLICATED | FCVAR_CHEAT, "How far sideways will a full left lean view reach.", true, 0.0, false, 0); ConVar neo_lean_yaw_peek_right_amount("neo_lean_yaw_peek_right_amount", "15.0", FCVAR_REPLICATED | FCVAR_CHEAT, "How far sideways will a full right lean view reach.", true, 0.0, false, 0); ConVar neo_lean_angle_percentage("neo_lean_angle_percentage", "0.75", FCVAR_REPLICATED | FCVAR_CHEAT, "for adjusting the actual angle of lean to a percentage of lean.", true, 0.0, true, 1.0); float CNEOPredictedViewModel::freeRoomForLean(float leanAmount, CNEO_Player *player){ const Vector playerDefaultViewPos = player->GetAbsOrigin(); Vector deltaPlayerViewPos(0, leanAmount, 0); VectorYawRotate(deltaPlayerViewPos, player->LocalEyeAngles().y, deltaPlayerViewPos); const Vector leanEndPos = playerDefaultViewPos + deltaPlayerViewPos; // We can only lean through stuff that isn't solid for us CTraceFilterNoNPCsOrPlayer filter(player, COLLISION_GROUP_PLAYER_MOVEMENT); Vector hullMins, hullMaxs; //sets player hull size //ducking Vector groundClearance(0, 0, 30); if (player->m_nButtons & IN_DUCK){ hullMins = NEORules()->GetViewVectors()->m_vDuckHullMin + groundClearance; hullMaxs = NEORules()->GetViewVectors()->m_vDuckHullMax; } //standing else{ hullMins = NEORules()->GetViewVectors()->m_vHullMin + groundClearance; hullMaxs = NEORules()->GetViewVectors()->m_vHullMax; } trace_t trace; UTIL_TraceHull(playerDefaultViewPos, leanEndPos, hullMins, hullMaxs, player->PhysicsSolidMaskForEntity(), &filter, &trace); #ifdef CLIENT_DLL if (neo_lean_debug_draw_hull.GetBool()){ // Z offset to avoid text overlap; DrawRenderToTextureDebugInfo will also want to print text around similar area. const Vector debugOffset = Vector(playerDefaultViewPos) + Vector(0, 0, -4); debugoverlay->AddTextOverlay(debugOffset, 0.0001, "x: %f\n y: %f\n z:%f\n", playerDefaultViewPos.x, playerDefaultViewPos.y, playerDefaultViewPos.z); const Vector colorBlue(0, 0, 255), colorGreen(0, 255, 0), colorRed(255, 0, 0); player->GetNEOViewModel()->DrawRenderToTextureDebugInfo(player, hullMins, hullMaxs, colorBlue, "startLeanPos", player->GetAbsOrigin()); } #endif return roundf(trace.startpos.DistTo(trace.endpos) * 100) / 100; } #ifdef CLIENT_DLL int CNEOPredictedViewModel::DrawModel(int flags) { auto pPlayer = static_cast<C_NEO_Player*>(GetOwner()); Assert(pPlayer); if (pPlayer) { if (pPlayer->IsCloaked()) { IMaterial *pass = materials->FindMaterial("dev/toc_vm", TEXTURE_GROUP_VIEW_MODEL); Assert(pass && !pass->IsErrorMaterial()); if (pass && !pass->IsErrorMaterial()) { if (!pass->IsPrecached()) { PrecacheMaterial(pass->GetName()); Assert(pass->IsPrecached()); } //modelrender->SuppressEngineLighting(true); modelrender->ForcedMaterialOverride(pass); int ret = BaseClass::DrawModel(flags /*| STUDIO_RENDER | STUDIO_DRAWTRANSLUCENTSUBMODELS | STUDIO_TRANSPARENCY*/); //modelrender->SuppressEngineLighting(false); modelrender->ForcedMaterialOverride(NULL); return ret; } return 0; } } return BaseClass::DrawModel(flags); } #endif static inline float calculateLeanAngle(float freeRoom, CNEO_Player *player){ #define HIP_TO_HEAD_HEIGHT 41.0f return -RAD2DEG(atan2(freeRoom, HIP_TO_HEAD_HEIGHT)) * neo_lean_angle_percentage.GetFloat(); } void CNEOPredictedViewModel::lean(CNEO_Player *player){ Assert(player); #ifdef CLIENT_DLL input->ExtraMouseSample(gpGlobals->frametime, 1); #endif QAngle viewAng = player->LocalEyeAngles(); float Ycurrent = m_flYPrevious; float Yfinal = 0; if (player->IsAlive()) { auto leanButtons = player->m_nButtons; if (leanButtons & (IN_LEAN_LEFT | IN_LEAN_RIGHT)) { if (leanButtons & IN_LEAN_LEFT & IN_LEAN_RIGHT) { //leaning both ways } else if (leanButtons & IN_LEAN_LEFT) { //leaning left Yfinal = freeRoomForLean(neo_lean_yaw_peek_left_amount.GetFloat(), player); } else { //leaning right Yfinal = -freeRoomForLean(-neo_lean_yaw_peek_right_amount.GetFloat(), player); } } else { //not leaning... move towards zero } } float dY = Yfinal - Ycurrent; float thisTime = gpGlobals->curtime; const float dTime = thisTime - m_flLastLeanTime; m_flLastLeanTime = thisTime; float Ymoved = dTime * neo_lean_speed.GetFloat(); if (dY != 0){ if (dY > 0){ Ycurrent += Ymoved; if (Ycurrent >= Yfinal - 0.05f){ Ycurrent = Yfinal; } } else{ Ycurrent -= Ymoved; if (Ycurrent <= Yfinal + 0.05f){ Ycurrent = Yfinal; } } } Vector viewOffset(0, 0, player->GetViewOffset().z); viewOffset.y = Ycurrent; m_flYPrevious = Ycurrent; VectorYawRotate(viewOffset, viewAng.y, viewOffset); player->SetViewOffset(viewOffset); float leanAngle = calculateLeanAngle(Ycurrent, player); viewAng.z = leanAngle; #ifdef CLIENT_DLL engine->SetViewAngles(viewAng); #endif } void CNEOPredictedViewModel::CalcViewModelView(CBasePlayer *pOwner, const Vector& eyePosition, const QAngle& eyeAngles) { // Is there a nicer way to do this? auto weapon = static_cast<CWeaponHL2MPBase*>(GetOwningWeapon()); if (!weapon) { return; } CHL2MPSWeaponInfo data = weapon->GetHL2MPWpnData(); Vector vForward, vRight, vUp, newPos, vOffset; QAngle newAng, angOffset; newAng = eyeAngles; newPos = eyePosition; AngleVectors(newAng, &vForward, &vRight, &vUp); vOffset = data.m_vecVMPosOffset; angOffset = data.m_angVMAngOffset; newPos += vForward * vOffset.x; newPos += vRight * vOffset.y; newPos += vUp * vOffset.z; newAng += angOffset; BaseClass::CalcViewModelView(pOwner, newPos, newAng); } #ifdef CLIENT_DLL RenderGroup_t CNEOPredictedViewModel::GetRenderGroup() { auto pPlayer = static_cast<C_NEO_Player*>(GetOwner()); Assert(pPlayer); if (pPlayer) { return pPlayer->IsCloaked() ? RENDER_GROUP_VIEW_MODEL_TRANSLUCENT : RENDER_GROUP_VIEW_MODEL_OPAQUE; } return BaseClass::GetRenderGroup(); } #endif
31.382263
191
0.72939
[ "object", "vector", "solid" ]
33b8f62859bc7aa04186588ed583c6243f26a496
228
cpp
C++
33-search-in-rotated-sorted-array/33-search-in-rotated-sorted-array.cpp
KondaSidhartha/Leetcode
d493550a3574c671f7ff5ac0fc265bfdb612747a
[ "MIT" ]
null
null
null
33-search-in-rotated-sorted-array/33-search-in-rotated-sorted-array.cpp
KondaSidhartha/Leetcode
d493550a3574c671f7ff5ac0fc265bfdb612747a
[ "MIT" ]
null
null
null
33-search-in-rotated-sorted-array/33-search-in-rotated-sorted-array.cpp
KondaSidhartha/Leetcode
d493550a3574c671f7ff5ac0fc265bfdb612747a
[ "MIT" ]
null
null
null
class Solution { public: int search(vector<int>& nums, int target) { for(int i=0;i<nums.size();i++){ if(nums[i]==target){ return i; } } return -1; } };
19
47
0.416667
[ "vector" ]
33bb1953a2d0d3164f88219154da2e4ec1fb6b0a
6,986
cpp
C++
message_handler.cpp
openbmc/phosphor-net-ipmid
af23add2a2cf73226cdc72af4793fde6357e8932
[ "Apache-2.0" ]
12
2017-12-01T19:14:38.000Z
2021-08-20T06:07:07.000Z
message_handler.cpp
openbmc/phosphor-net-ipmid
af23add2a2cf73226cdc72af4793fde6357e8932
[ "Apache-2.0" ]
19
2019-02-02T11:50:05.000Z
2021-08-17T19:05:49.000Z
message_handler.cpp
openbmc/phosphor-net-ipmid
af23add2a2cf73226cdc72af4793fde6357e8932
[ "Apache-2.0" ]
11
2016-12-21T00:37:49.000Z
2019-10-21T02:28:58.000Z
#include "message_handler.hpp" #include "command_table.hpp" #include "main.hpp" #include "message.hpp" #include "message_parsers.hpp" #include "sessions_manager.hpp" #include <sys/socket.h> #include <memory> #include <phosphor-logging/log.hpp> #include <string> #include <vector> using namespace phosphor::logging; namespace message { using namespace phosphor::logging; bool Handler::receive() { std::vector<uint8_t> packet; auto readStatus = 0; // Read the packet std::tie(readStatus, packet) = channel->read(); // Read of the packet failed if (readStatus < 0) { log<level::ERR>("Error in Read", entry("STATUS=%x", readStatus)); return false; } // Unflatten the packet std::tie(inMessage, sessionHeader) = parser::unflatten(packet); return true; } void Handler::updSessionData(std::shared_ptr<Message>& inMessage) { auto session = session::Manager::get().getSession(inMessage->bmcSessionID); sessionID = inMessage->bmcSessionID; inMessage->rcSessionID = session->getRCSessionID(); session->updateLastTransactionTime(); session->channelPtr = channel; session->remotePort(channel->getPort()); uint32_t ipAddr = 0; channel->getRemoteAddress(ipAddr); session->remoteIPAddr(ipAddr); } Handler::~Handler() { try { #ifdef RMCP_PING if (ClassOfMsg::ASF == inMessage->rmcpMsgClass) { sendASF(); } else #endif // RMCP_PING { if (outPayload) { std::shared_ptr<Message> outMessage = inMessage->createResponse(*outPayload); if (!outMessage) { return; } send(outMessage); } } } catch (const std::exception& e) { // send failed, most likely due to a session closure log<level::INFO>("Async RMCP+ reply failed", entry("EXCEPTION=%s", e.what())); } } void Handler::processIncoming() { // Read the incoming IPMI packet if (!receive()) { return; } #ifdef RMCP_PING // Execute the Command, possibly asynchronously if (ClassOfMsg::ASF != inMessage->rmcpMsgClass) #endif // RMCP_PING { updSessionData(inMessage); executeCommand(); } // send happens during the destructor if a payload was set } void Handler::executeCommand() { // Get the CommandID to map into the command table auto command = inMessage->getCommand(); if (inMessage->payloadType == PayloadType::IPMI) { auto session = session::Manager::get().getSession(sessionID); // Process PayloadType::IPMI only if ipmi is enabled or for sessionless // or for session establisbment command if (this->sessionID == session::sessionZero || session->sessionUserPrivAccess.ipmiEnabled) { if (inMessage->payload.size() < (sizeof(LAN::header::Request) + sizeof(LAN::trailer::Request))) { return; } auto start = inMessage->payload.begin() + sizeof(LAN::header::Request); auto end = inMessage->payload.end() - sizeof(LAN::trailer::Request); std::vector<uint8_t> inPayload(start, end); command::Table::get().executeCommand(command, inPayload, shared_from_this()); } else { std::vector<uint8_t> payload{IPMI_CC_INSUFFICIENT_PRIVILEGE}; outPayload = std::move(payload); } } else { command::Table::get().executeCommand(command, inMessage->payload, shared_from_this()); } } void Handler::writeData(const std::vector<uint8_t>& packet) { auto writeStatus = channel->write(packet); if (writeStatus < 0) { throw std::runtime_error("Error in writing to socket"); } } #ifdef RMCP_PING void Handler::sendASF() { // Flatten the packet auto packet = asfparser::flatten(inMessage->asfMsgTag); // Write the packet writeData(packet); } #endif // RMCP_PING void Handler::send(std::shared_ptr<Message> outMessage) { auto session = session::Manager::get().getSession(sessionID); // Flatten the packet auto packet = parser::flatten(outMessage, sessionHeader, session); // Write the packet writeData(packet); } void Handler::setChannelInSession() const { auto session = session::Manager::get().getSession(sessionID); session->channelPtr = channel; } void Handler::sendSOLPayload(const std::vector<uint8_t>& input) { auto session = session::Manager::get().getSession(sessionID); auto outMessage = std::make_shared<Message>(); outMessage->payloadType = PayloadType::SOL; outMessage->payload = input; outMessage->isPacketEncrypted = session->isCryptAlgoEnabled(); outMessage->isPacketAuthenticated = session->isIntegrityAlgoEnabled(); outMessage->rcSessionID = session->getRCSessionID(); outMessage->bmcSessionID = sessionID; send(outMessage); } void Handler::sendUnsolicitedIPMIPayload(uint8_t netfn, uint8_t cmd, const std::vector<uint8_t>& output) { auto session = session::Manager::get().getSession(sessionID); auto outMessage = std::make_shared<Message>(); outMessage->payloadType = PayloadType::IPMI; outMessage->isPacketEncrypted = session->isCryptAlgoEnabled(); outMessage->isPacketAuthenticated = session->isIntegrityAlgoEnabled(); outMessage->rcSessionID = session->getRCSessionID(); outMessage->bmcSessionID = sessionID; outMessage->payload.resize(sizeof(LAN::header::Request) + output.size() + sizeof(LAN::trailer::Request)); auto respHeader = reinterpret_cast<LAN::header::Request*>(outMessage->payload.data()); // Add IPMI LAN Message Request Header respHeader->rsaddr = LAN::requesterBMCAddress; respHeader->netfn = (netfn << 0x02); respHeader->cs = crc8bit(&(respHeader->rsaddr), 2); respHeader->rqaddr = LAN::responderBMCAddress; respHeader->rqseq = 0; respHeader->cmd = cmd; auto assembledSize = sizeof(LAN::header::Request); // Copy the output by the execution of the command std::copy(output.begin(), output.end(), outMessage->payload.begin() + assembledSize); assembledSize += output.size(); // Add the IPMI LAN Message Trailer auto trailer = reinterpret_cast<LAN::trailer::Request*>( outMessage->payload.data() + assembledSize); // Calculate the checksum for the field rqaddr in the header to the // command data, 3 corresponds to size of the fields before rqaddr( rsaddr, // netfn, cs). trailer->checksum = crc8bit(&respHeader->rqaddr, assembledSize - 3); send(outMessage); } } // namespace message
28.283401
80
0.626682
[ "vector" ]
33bbe5d4c7fa7196b0e6d9f51d7626d2a8befb90
8,422
cpp
C++
libraries/disp3D/engine/model/materials/gpuinterpolationmaterial.cpp
gabrielbmotta/mne-cpp
f3e68a4d2e33369dfe637591c055e34000c73a46
[ "BSD-3-Clause" ]
null
null
null
libraries/disp3D/engine/model/materials/gpuinterpolationmaterial.cpp
gabrielbmotta/mne-cpp
f3e68a4d2e33369dfe637591c055e34000c73a46
[ "BSD-3-Clause" ]
null
null
null
libraries/disp3D/engine/model/materials/gpuinterpolationmaterial.cpp
gabrielbmotta/mne-cpp
f3e68a4d2e33369dfe637591c055e34000c73a46
[ "BSD-3-Clause" ]
null
null
null
//============================================================================================================= /** * @file gpuinterpolationmaterial.cpp * @author Lars Debor <Lars.Debor@tu-ilmenau.de>; * Lorenz Esch <lesch@mgh.harvard.edu> * @version dev * @date October, 2017 * * @section LICENSE * * Copyright (C) 2017, Lars Debor, Lorenz Esch. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors 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. * * * @brief GpuInterpolationMaterial class definition. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "gpuinterpolationmaterial.h" //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <Qt3DRender/QEffect> #include <Qt3DRender/QParameter> #include <Qt3DRender/QRenderPass> #include <Qt3DRender/QFilterKey> #include <Qt3DRender/QTechnique> #include <Qt3DRender/QShaderProgram> #include <Qt3DRender/QGraphicsApiFilter> #include <QUrl> //============================================================================================================= // EIGEN INCLUDES //============================================================================================================= //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace DISP3DLIB; using namespace Qt3DRender; //============================================================================================================= // DEFINE GLOBAL METHODS //============================================================================================================= //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= GpuInterpolationMaterial::GpuInterpolationMaterial(bool bUseSortPolicy, Qt3DCore::QNode *parent) : AbstractPhongAlphaMaterial(bUseSortPolicy, parent) , m_pComputeShader(new QShaderProgram) , m_pComputeRenderPass(new QRenderPass) , m_pComputeFilterKey(new QFilterKey) , m_pComputeTechnique(new QTechnique) , m_pDrawShader(new QShaderProgram) , m_pDrawRenderPass(new QRenderPass) , m_pDrawTechnique(new QTechnique) , m_pSignalDataParameter(new QParameter) , m_pColsParameter(new QParameter) , m_pRowsParameter(new QParameter) , m_pInterpolationMatParameter(new QParameter) , m_pOutputColorParameter(new QParameter) , m_pThresholdXParameter(new QParameter(QStringLiteral("fThresholdX"), 1e-10f)) , m_pThresholdZParameter(new QParameter(QStringLiteral("fThresholdZ"), 6e-6f)) , m_pColormapParameter(new QParameter(QStringLiteral("ColormapType"), 3)) { init(); setShaderCode(); } //============================================================================================================= void GpuInterpolationMaterial::init() { //Compute part //Set OpenGL version m_pComputeTechnique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGL); m_pComputeTechnique->graphicsApiFilter()->setMajorVersion(4); m_pComputeTechnique->graphicsApiFilter()->setMinorVersion(3); m_pComputeTechnique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::CoreProfile); //Set filter Keys m_pComputeFilterKey->setName(QStringLiteral("renderingStyle")); m_pComputeFilterKey->setValue(QStringLiteral("compute")); //Add to technique m_pComputeTechnique->addFilterKey(m_pComputeFilterKey); m_pComputeTechnique->addRenderPass(m_pComputeRenderPass); //Set default Interpolation matrix parameters m_pColsParameter->setName(QStringLiteral("cols")); m_pColsParameter->setValue(1); m_pRowsParameter->setName(QStringLiteral("rows")); m_pRowsParameter->setValue(1); m_pInterpolationMatParameter->setName(QStringLiteral("InterpolationMat")); //Set default output m_pOutputColorParameter->setName(QStringLiteral("OutputColor")); //Set default input m_pSignalDataParameter->setName(QStringLiteral("InputVec")); //Add compute Parameter m_pComputeRenderPass->addParameter(m_pColsParameter); m_pComputeRenderPass->addParameter(m_pRowsParameter); m_pComputeRenderPass->addParameter(m_pOutputColorParameter); m_pComputeRenderPass->addParameter(m_pInterpolationMatParameter); m_pComputeRenderPass->addParameter(m_pSignalDataParameter); //Add Threshold parameter m_pComputeRenderPass->addParameter(m_pThresholdXParameter); m_pComputeRenderPass->addParameter(m_pThresholdZParameter); //Add ColormapType m_pComputeRenderPass->addParameter(m_pColormapParameter); //Draw part //Add Phongalpha parameter m_pDrawRenderPass->addParameter(m_pDiffuseParameter); m_pDrawRenderPass->addParameter(m_pSpecularParameter); m_pDrawRenderPass->addParameter(m_pShininessParameter); m_pDrawRenderPass->addParameter(m_pAlphaParameter); //Set OpenGL version m_pDrawTechnique->graphicsApiFilter()->setApi(QGraphicsApiFilter::OpenGL); m_pDrawTechnique->graphicsApiFilter()->setMajorVersion(4); m_pDrawTechnique->graphicsApiFilter()->setMinorVersion(3); m_pDrawTechnique->graphicsApiFilter()->setProfile(QGraphicsApiFilter::CoreProfile); //Add to technique m_pDrawTechnique->addFilterKey(m_pDrawFilterKey); m_pDrawTechnique->addRenderPass(m_pDrawRenderPass); //Effect //Link shader and uniforms m_pEffect->addTechnique(m_pComputeTechnique); m_pEffect->addTechnique(m_pDrawTechnique); //Add to material this->setEffect(m_pEffect); } //============================================================================================================= void GpuInterpolationMaterial::setShaderCode() { m_pComputeShader->setComputeShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/engine/model/materials/shaders/compute/interpolation.csh")))); m_pComputeRenderPass->setShaderProgram(m_pComputeShader); m_pDrawShader->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/engine/model/materials/shaders/compute/interpolation.vert")))); m_pDrawShader->setFragmentShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/engine/model/materials/shaders/compute/interpolation.frag")))); m_pDrawRenderPass->setShaderProgram(m_pDrawShader); } //=============================================================================================================
46.274725
158
0.607813
[ "model" ]
33bc320a50b55f0be6de20e24f060f0fd37f4529
14,056
cpp
C++
src/base/snake.cpp
huckiyang/Snake-AI
6b379b102a05b0ab27ef88d073b30d0b9cb754dc
[ "MIT" ]
null
null
null
src/base/snake.cpp
huckiyang/Snake-AI
6b379b102a05b0ab27ef88d073b30d0b9cb754dc
[ "MIT" ]
null
null
null
src/base/snake.cpp
huckiyang/Snake-AI
6b379b102a05b0ab27ef88d073b30d0b9cb754dc
[ "MIT" ]
null
null
null
#include "base/snake.h" #include "util/util.h" #include <queue> #include <algorithm> #include <stdexcept> using std::vector; using std::list; using std::queue; using util::Random; Snake::Snake() {} Snake::~Snake() {} void Snake::setDirection(const Direction &d) { direc = d; } void Snake::setMap(Map *const m) { map = m; } Direction Snake::getDirection() const { return direc; } bool Snake::isDead() const { return dead; } void Snake::testMinPath(const Pos &from, const Pos &to, std::list<Direction> &path) { map->setTestEnabled(true); findMinPath(from, to, path); map->showTestPath(from, path); map->setTestEnabled(false); } void Snake::testMaxPath(const Pos &from, const Pos &to, std::list<Direction> &path) { map->setTestEnabled(true); findMaxPath(from, to, path); Pos cur = from; for (const Direction d : path) { map->getPoint(cur).setDist(Point::EMPTY_DIST); cur = cur.getAdj(d); } map->getPoint(from).setDist(0); map->getPoint(to).setDist(1); map->showTestPath(from, path); map->setTestEnabled(false); } void Snake::testHamilton() { map->setTestEnabled(true); enableHamilton(); SizeType row = map->getRowCount(), col = map->getColCount(); for (SizeType i = 1; i < row - 1; ++i) { for (SizeType j = 1; j < col - 1; ++j) { Pos pos = Pos(i, j); Point &point = map->getPoint(pos); point.setDist(point.getIdx()); map->showTestPos(pos); } } } void Snake::addBody(const Pos &p) { if (bodies.size() == 0) { // Insert a head map->getPoint(p).setType(Point::Type::SNAKE_HEAD); } else { // Insert a body if (bodies.size() > 1) { const Pos &oldTail = getTail(); map->getPoint(oldTail).setType(Point::Type::SNAKE_BODY); } map->getPoint(p).setType(Point::Type::SNAKE_TAIL); } bodies.push_back(p); } void Snake::move() { if (isDead() || direc == NONE) { return; } map->getPoint(getHead()).setType(Point::Type::SNAKE_BODY); Pos newHead = getHead().getAdj(direc); bodies.push_front(newHead); if (!map->isSafe(newHead)) { dead = true; } else { if (map->getPoint(newHead).getType() != Point::Type::FOOD) { removeTail(); } else { map->removeFood(); } } map->getPoint(newHead).setType(Point::Type::SNAKE_HEAD); } void Snake::move(const std::list<Direction> &path) { for (const Direction &d : path) { setDirection(d); move(); } } void Snake::enableHamilton() { if (map->getRowCount() % 2 == 1 && map->getColCount() % 2 == 1) { throw std::range_error("Snake.enableHamilton(): require even amount of rows or columns."); } hamiltonEnabled = true; buildHamilton(); } void Snake::decideNext() { if (isDead()) { return; } else if (!map->hasFood()) { direc = NONE; return; } if (hamiltonEnabled) { // AI based on the Hamiltonian cycle SizeType size = map->getSize(); Pos head = getHead(), tail = getTail(); Point::ValueType tailIndex = map->getPoint(tail).getIdx(); Point::ValueType headIndex = map->getPoint(head).getIdx(); // Try to take shortcuts when the snake is not long enough if (bodies.size() < size * 3 / 4) { list<Direction> minPath; findMinPathToFood(minPath); if (!minPath.empty()) { Direction nextDirec = *minPath.begin(); Pos nextPos = head.getAdj(nextDirec); Point::ValueType nextIndex = map->getPoint(nextPos).getIdx(); Point::ValueType foodIndex = map->getPoint(map->getFood()).getIdx(); headIndex = util::getDistance(tailIndex, headIndex, (Point::ValueType)size); nextIndex = util::getDistance(tailIndex, nextIndex, (Point::ValueType)size); foodIndex = util::getDistance(tailIndex, foodIndex, (Point::ValueType)size); if (nextIndex > headIndex && nextIndex <= foodIndex) { direc = nextDirec; return; } } } // Move along the hamitonian cycle headIndex = map->getPoint(head).getIdx(); vector<Pos> adjPositions = head.getAllAdj(); for (const Pos &adjPos : adjPositions) { const Point &adjPoint = map->getPoint(adjPos); Point::ValueType adjIndex = adjPoint.getIdx(); if (adjIndex == (headIndex + 1) % size) { direc = head.getDirectionTo(adjPos); } } } else { // AI based on graph search list<Direction> pathToFood, pathToTail; // Create a virtual snake Map tmpMap = *map; Snake tmpSnake(*this); tmpSnake.setMap(&tmpMap); // Step 1 tmpSnake.findMinPathToFood(pathToFood); if (!pathToFood.empty()) { // Step 2 tmpSnake.move(pathToFood); if (tmpMap.isAllBody()) { this->setDirection(*(pathToFood.begin())); return; } else { // Step 3 tmpSnake.findMaxPathToTail(pathToTail); if (pathToTail.size() > 1) { this->setDirection(*(pathToFood.begin())); return; } } } // Step 4 this->findMaxPathToTail(pathToTail); if (pathToTail.size() > 1) { this->setDirection(*(pathToTail.begin())); return; } // Step 5 direc = Direction::DOWN; // A default direction SizeType max = 0; Pos head = getHead(); vector<Pos> adjPositions = head.getAllAdj(); for (const Pos &adjPos : adjPositions) { if (map->isSafe(adjPos)) { SizeType dist = Map::distance(adjPos, map->getFood()); if (dist >= max) { max = dist; direc = head.getDirectionTo(adjPos); } } } } } const Pos& Snake::getHead() const { return *bodies.begin(); } const Pos& Snake::getTail() const { return *bodies.rbegin(); } void Snake::removeTail() { map->getPoint(getTail()).setType(Point::Type::EMPTY); bodies.pop_back(); if (bodies.size() > 1) { map->getPoint(getTail()).setType(Point::Type::SNAKE_TAIL); } } void Snake::findMinPathToFood(list<Direction> &path) { findPathTo(0, map->getFood(), path); } void Snake::findMaxPathToTail(list<Direction> &path) { findPathTo(1, getTail(), path); } void Snake::findPathTo(const int pathType, const Pos &goal, list<Direction> &path) { Point::Type oriType = map->getPoint(goal).getType(); map->getPoint(goal).setType(Point::Type::EMPTY); if (pathType == 0) { findMinPath(getHead(), goal, path); } else if (pathType == 1) { findMaxPath(getHead(), goal, path); } map->getPoint(goal).setType(oriType); // Retore point type } void Snake::findMinPath(const Pos &from, const Pos &to, list<Direction> &path) { // Init SizeType row = map->getRowCount(), col = map->getColCount(); for (SizeType i = 1; i < row - 1; ++i) { for (SizeType j = 1; j < col - 1; ++j) { map->getPoint(Pos(i, j)).setDist(Point::MAX_VALUE); } } path.clear(); map->getPoint(from).setDist(0); queue<Pos> openList; openList.push(from); // BFS while (!openList.empty()) { Pos curPos = openList.front(); const Point &curPoint = map->getPoint(curPos); openList.pop(); map->showTestPos(curPos); if (curPos == to) { buildPath(from, to, path); break; } vector<Pos> adjPositions = curPos.getAllAdj(); Random<>::getInstance()->shuffle(adjPositions.begin(), adjPositions.end()); // Arrange the order of traversing to make the result path as straight as possible Direction bestDirec = (curPos == from ? direc : curPoint.getParent().getDirectionTo(curPos)); for (SizeType i = 0; i < adjPositions.size(); ++i) { if (bestDirec == curPos.getDirectionTo(adjPositions[i])) { util::swap(adjPositions[0], adjPositions[i]); break; } } // Traverse the adjacent positions for (const Pos &adjPos : adjPositions) { Point &adjPoint = map->getPoint(adjPos); if (map->isEmpty(adjPos) && adjPoint.getDist() == Point::MAX_VALUE) { adjPoint.setParent(curPos); adjPoint.setDist(curPoint.getDist() + 1); openList.push(adjPos); } } } } void Snake::findMaxPath(const Pos &from, const Pos &to, list<Direction> &path) { // Get the shortest path bool oriEnabled = map->isTestEnabled(); map->setTestEnabled(false); findMinPath(from, to, path); map->setTestEnabled(oriEnabled); // Init SizeType row = map->getRowCount(), col = map->getColCount(); for (SizeType i = 1; i < row - 1; ++i) { for (SizeType j = 1; j < col - 1; ++j) { map->getPoint(Pos(i, j)).setVisit(false); } } // Make all points on the path visited Pos cur = from; for (const Direction d : path) { map->getPoint(cur).setVisit(true); cur = cur.getAdj(d); } map->getPoint(cur).setVisit(true); // Extend the path between each pair of the points for (auto it = path.begin(); it != path.end();) { if (it == path.begin()) { cur = from; } bool extended = false; Direction curDirec = *it; Pos next = cur.getAdj(curDirec); switch (curDirec) { case LEFT: case RIGHT: { Pos curUp = cur.getAdj(UP); Pos nextUp = next.getAdj(UP); // Check two points above if (map->isEmptyNotVisit(curUp) && map->isEmptyNotVisit(nextUp)) { map->getPoint(curUp).setVisit(true); map->getPoint(nextUp).setVisit(true); it = path.erase(it); it = path.insert(it, DOWN); it = path.insert(it, curDirec); it = path.insert(it, UP); it = path.begin(); extended = true; } else { Pos curDown = cur.getAdj(DOWN); Pos nextDown = next.getAdj(DOWN); // Check two points below if (map->isEmptyNotVisit(curDown) && map->isEmptyNotVisit(nextDown)) { map->getPoint(curDown).setVisit(true); map->getPoint(nextDown).setVisit(true); it = path.erase(it); it = path.insert(it, UP); it = path.insert(it, curDirec); it = path.insert(it, DOWN); it = path.begin(); extended = true; } } break; } case UP: case DOWN: { Pos curLeft = cur.getAdj(LEFT); Pos nextLeft = next.getAdj(LEFT); // Check two points on the left if (map->isEmptyNotVisit(curLeft) && map->isEmptyNotVisit(nextLeft)) { map->getPoint(curLeft).setVisit(true); map->getPoint(nextLeft).setVisit(true); it = path.erase(it); it = path.insert(it, RIGHT); it = path.insert(it, curDirec); it = path.insert(it, LEFT); it = path.begin(); extended = true; } else { Pos curRight = cur.getAdj(RIGHT); Pos nextRight = next.getAdj(RIGHT); // Check two points on the right if (map->isEmptyNotVisit(curRight) && map->isEmptyNotVisit(nextRight)) { map->getPoint(curRight).setVisit(true); map->getPoint(nextRight).setVisit(true); it = path.erase(it); it = path.insert(it, LEFT); it = path.insert(it, curDirec); it = path.insert(it, RIGHT); it = path.begin(); extended = true; } } break; } default: break; } if (!extended) { ++it; cur = next; } } } void Snake::buildPath(const Pos &from, const Pos &to, list<Direction> &path) const { Pos tmp = to, parent; while (tmp != from) { parent = map->getPoint(tmp).getParent(); path.push_front(parent.getDirectionTo(tmp)); tmp = parent; } } void Snake::buildHamilton() { // Change the initial body to a wall temporarily Pos bodyPos = *(++bodies.begin()); Point &bodyPoint = map->getPoint(bodyPos); map->getPoint(*(++bodies.begin())).setType(Point::Type::WALL); // Get the longest path bool oriEnabled = map->isTestEnabled(); map->setTestEnabled(false); list<Direction> maxPath; findMaxPathToTail(maxPath); map->setTestEnabled(oriEnabled); bodyPoint.setType(Point::Type::SNAKE_BODY); // Initialize the first three incides of the cycle Point::ValueType idx = 0; for (auto it = bodies.crbegin(); it != bodies.crend(); ++it) { map->getPoint(*it).setIdx(idx++); } // Build remaining cycle SizeType size = map->getSize(); Pos cur = getHead(); for (const Direction d : maxPath) { Pos next = cur.getAdj(d); map->getPoint(next).setIdx((map->getPoint(cur).getIdx() + 1) % size); cur = next; } }
33.466667
101
0.527177
[ "vector" ]
33bce643f3dedf2f0394df1086391d2abb29302b
20,798
hpp
C++
include/System/IO/TextWriter_SyncTextWriter.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/System/IO/TextWriter_SyncTextWriter.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/System/IO/TextWriter_SyncTextWriter.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include <initializer_list> #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: System.IO.TextWriter #include "System/IO/TextWriter.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Text namespace System::Text { // Forward declaring type: Encoding class Encoding; } // Forward declaring namespace: System namespace System { // Forward declaring type: IFormatProvider class IFormatProvider; } // Completed forward declares // Type namespace: System.IO namespace System::IO { // Size: 0x30 #pragma pack(push, 1) // Autogenerated type: System.IO.TextWriter/System.IO.SyncTextWriter // [TokenAttribute] Offset: FFFFFFFF class TextWriter::SyncTextWriter : public System::IO::TextWriter { public: // private System.IO.TextWriter _out // Size: 0x8 // Offset: 0x28 System::IO::TextWriter* out; // Field size check static_assert(sizeof(System::IO::TextWriter*) == 0x8); // Creating value type constructor for type: SyncTextWriter SyncTextWriter(System::IO::TextWriter* out_ = {}) noexcept : out{out_} {} // Get instance field reference: private System.IO.TextWriter _out System::IO::TextWriter*& dyn__out(); // System.Void .ctor(System.IO.TextWriter t) // Offset: 0x1834370 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static TextWriter::SyncTextWriter* New_ctor(System::IO::TextWriter* t) { static auto ___internal__logger = ::Logger::get().WithContext("System::IO::TextWriter::SyncTextWriter::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<TextWriter::SyncTextWriter*, creationType>(t))); } // public override System.Text.Encoding get_Encoding() // Offset: 0x1835270 // Implemented from: System.IO.TextWriter // Base method: System.Text.Encoding TextWriter::get_Encoding() System::Text::Encoding* get_Encoding(); // public override System.IFormatProvider get_FormatProvider() // Offset: 0x1835290 // Implemented from: System.IO.TextWriter // Base method: System.IFormatProvider TextWriter::get_FormatProvider() System::IFormatProvider* get_FormatProvider(); // public override System.Void Close() // Offset: 0x18352B0 // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::Close() void Close(); // protected override System.Void Dispose(System.Boolean disposing) // Offset: 0x18352D0 // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::Dispose(System.Boolean disposing) void Dispose(bool disposing); // public override System.Void Flush() // Offset: 0x18353A0 // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::Flush() void Flush(); // public override System.Void Write(System.Char value) // Offset: 0x18353C0 // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::Write(System.Char value) void Write(::Il2CppChar value); // public override System.Void Write(System.Char[] buffer) // Offset: 0x18353E0 // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::Write(System.Char[] buffer) void Write(::Array<::Il2CppChar>* buffer); // public override System.Void Write(System.Char[] buffer, System.Int32 index, System.Int32 count) // Offset: 0x1835404 // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::Write(System.Char[] buffer, System.Int32 index, System.Int32 count) void Write(::Array<::Il2CppChar>* buffer, int index, int count); // public override System.Void Write(System.String value) // Offset: 0x1835428 // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::Write(System.String value) void Write(::Il2CppString* value); // public override System.Void Write(System.String format, System.Object arg0) // Offset: 0x183544C // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::Write(System.String format, System.Object arg0) void Write(::Il2CppString* format, ::Il2CppObject* arg0); // public override System.Void Write(System.String format, System.Object arg0, System.Object arg1, System.Object arg2) // Offset: 0x1835470 // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::Write(System.String format, System.Object arg0, System.Object arg1, System.Object arg2) void Write(::Il2CppString* format, ::Il2CppObject* arg0, ::Il2CppObject* arg1, ::Il2CppObject* arg2); // public override System.Void WriteLine() // Offset: 0x1835494 // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::WriteLine() void WriteLine(); // public override System.Void WriteLine(System.Char value) // Offset: 0x18354B8 // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::WriteLine(System.Char value) void WriteLine(::Il2CppChar value); // public override System.Void WriteLine(System.Char[] buffer, System.Int32 index, System.Int32 count) // Offset: 0x18354DC // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::WriteLine(System.Char[] buffer, System.Int32 index, System.Int32 count) void WriteLine(::Array<::Il2CppChar>* buffer, int index, int count); // public override System.Void WriteLine(System.String value) // Offset: 0x1835500 // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::WriteLine(System.String value) void WriteLine(::Il2CppString* value); // public override System.Void WriteLine(System.String format, System.Object arg0) // Offset: 0x1835524 // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::WriteLine(System.String format, System.Object arg0) void WriteLine(::Il2CppString* format, ::Il2CppObject* arg0); // public override System.Void WriteLine(System.String format, System.Object arg0, System.Object arg1) // Offset: 0x1835548 // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::WriteLine(System.String format, System.Object arg0, System.Object arg1) void WriteLine(::Il2CppString* format, ::Il2CppObject* arg0, ::Il2CppObject* arg1); // public override System.Void WriteLine(System.String format, params System.Object[] arg) // Offset: 0x183556C // Implemented from: System.IO.TextWriter // Base method: System.Void TextWriter::WriteLine(System.String format, params System.Object[] arg) void WriteLine(::Il2CppString* format, ::Array<::Il2CppObject*>* arg); // Creating initializer_list -> params proxy for: System.Void WriteLine(System.String format, params System.Object[] arg) void WriteLine(::Il2CppString* format, std::initializer_list<::Il2CppObject*> arg); // Creating TArgs -> initializer_list proxy for: System.Void WriteLine(System.String format, params System.Object[] arg) template<class ...TParams> void WriteLine(::Il2CppString* format, TParams&&... arg) { WriteLine(format, {arg...}); } }; // System.IO.TextWriter/System.IO.SyncTextWriter #pragma pack(pop) static check_size<sizeof(TextWriter::SyncTextWriter), 40 + sizeof(System::IO::TextWriter*)> __System_IO_TextWriter_SyncTextWriterSizeCheck; static_assert(sizeof(TextWriter::SyncTextWriter) == 0x30); } DEFINE_IL2CPP_ARG_TYPE(System::IO::TextWriter::SyncTextWriter*, "System.IO", "TextWriter/SyncTextWriter"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::get_Encoding // Il2CppName: get_Encoding template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Text::Encoding* (System::IO::TextWriter::SyncTextWriter::*)()>(&System::IO::TextWriter::SyncTextWriter::get_Encoding)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "get_Encoding", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::get_FormatProvider // Il2CppName: get_FormatProvider template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IFormatProvider* (System::IO::TextWriter::SyncTextWriter::*)()>(&System::IO::TextWriter::SyncTextWriter::get_FormatProvider)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "get_FormatProvider", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::Close // Il2CppName: Close template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)()>(&System::IO::TextWriter::SyncTextWriter::Close)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "Close", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::Dispose // Il2CppName: Dispose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)(bool)>(&System::IO::TextWriter::SyncTextWriter::Dispose)> { static const MethodInfo* get() { static auto* disposing = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "Dispose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{disposing}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::Flush // Il2CppName: Flush template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)()>(&System::IO::TextWriter::SyncTextWriter::Flush)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "Flush", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::Write // Il2CppName: Write template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)(::Il2CppChar)>(&System::IO::TextWriter::SyncTextWriter::Write)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Char")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "Write", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::Write // Il2CppName: Write template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)(::Array<::Il2CppChar>*)>(&System::IO::TextWriter::SyncTextWriter::Write)> { static const MethodInfo* get() { static auto* buffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Char"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "Write", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{buffer}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::Write // Il2CppName: Write template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)(::Array<::Il2CppChar>*, int, int)>(&System::IO::TextWriter::SyncTextWriter::Write)> { static const MethodInfo* get() { static auto* buffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Char"), 1)->byval_arg; static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "Write", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{buffer, index, count}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::Write // Il2CppName: Write template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)(::Il2CppString*)>(&System::IO::TextWriter::SyncTextWriter::Write)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "Write", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::Write // Il2CppName: Write template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)(::Il2CppString*, ::Il2CppObject*)>(&System::IO::TextWriter::SyncTextWriter::Write)> { static const MethodInfo* get() { static auto* format = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* arg0 = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "Write", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{format, arg0}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::Write // Il2CppName: Write template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)(::Il2CppString*, ::Il2CppObject*, ::Il2CppObject*, ::Il2CppObject*)>(&System::IO::TextWriter::SyncTextWriter::Write)> { static const MethodInfo* get() { static auto* format = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* arg0 = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; static auto* arg1 = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; static auto* arg2 = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "Write", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{format, arg0, arg1, arg2}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::WriteLine // Il2CppName: WriteLine template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)()>(&System::IO::TextWriter::SyncTextWriter::WriteLine)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "WriteLine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::WriteLine // Il2CppName: WriteLine template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)(::Il2CppChar)>(&System::IO::TextWriter::SyncTextWriter::WriteLine)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Char")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "WriteLine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::WriteLine // Il2CppName: WriteLine template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)(::Array<::Il2CppChar>*, int, int)>(&System::IO::TextWriter::SyncTextWriter::WriteLine)> { static const MethodInfo* get() { static auto* buffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Char"), 1)->byval_arg; static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "WriteLine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{buffer, index, count}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::WriteLine // Il2CppName: WriteLine template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)(::Il2CppString*)>(&System::IO::TextWriter::SyncTextWriter::WriteLine)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "WriteLine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::WriteLine // Il2CppName: WriteLine template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)(::Il2CppString*, ::Il2CppObject*)>(&System::IO::TextWriter::SyncTextWriter::WriteLine)> { static const MethodInfo* get() { static auto* format = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* arg0 = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "WriteLine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{format, arg0}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::WriteLine // Il2CppName: WriteLine template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)(::Il2CppString*, ::Il2CppObject*, ::Il2CppObject*)>(&System::IO::TextWriter::SyncTextWriter::WriteLine)> { static const MethodInfo* get() { static auto* format = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* arg0 = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; static auto* arg1 = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "WriteLine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{format, arg0, arg1}); } }; // Writing MetadataGetter for method: System::IO::TextWriter::SyncTextWriter::WriteLine // Il2CppName: WriteLine template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::TextWriter::SyncTextWriter::*)(::Il2CppString*, ::Array<::Il2CppObject*>*)>(&System::IO::TextWriter::SyncTextWriter::WriteLine)> { static const MethodInfo* get() { static auto* format = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* arg = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Object"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IO::TextWriter::SyncTextWriter*), "WriteLine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{format, arg}); } };
63.024242
238
0.71906
[ "object", "vector" ]
33c071b0ed6dea6ec752d8a009e29320eb340dac
15,031
cxx
C++
Rendering/RayTracing/Testing/Cxx/TestOSPRayRenderMesh.cxx
txwhhny/vtk
854d9aa87b944bc9079510515996406b98b86f7c
[ "BSD-3-Clause" ]
1,755
2015-01-03T06:55:00.000Z
2022-03-29T05:23:26.000Z
Rendering/RayTracing/Testing/Cxx/TestOSPRayRenderMesh.cxx
txwhhny/vtk
854d9aa87b944bc9079510515996406b98b86f7c
[ "BSD-3-Clause" ]
29
2015-04-23T20:58:30.000Z
2022-03-02T16:16:42.000Z
Rendering/RayTracing/Testing/Cxx/TestOSPRayRenderMesh.cxx
txwhhny/vtk
854d9aa87b944bc9079510515996406b98b86f7c
[ "BSD-3-Clause" ]
1,044
2015-01-05T22:48:27.000Z
2022-03-31T02:38:26.000Z
/*========================================================================= Program: Visualization Toolkit Module: TestOSPRayRenderMesh.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // This test verifies that we can do simple mesh rendering with ospray // and that VTK's many standard rendering modes (points, lines, surface, with // a variety of color controls (actor, point, cell, texture) etc work as // they should. // // The command line arguments are: // -I => run in interactive mode; unless this is used, the program will // not allow interaction and exit. // In interactive mode it responds to the keys listed // vtkOSPRayTestInteractor.h // -GL => users OpenGL instead of OSPRay to render // -type N => where N is one of 0,1,2, or 3 makes meshes consisting of // points, wireframes, triangles (=the default) or triangle strips // -rep N => where N is one of 0,1 or 2 draws the meshes as points, lines // or surfaces #include "vtkActor.h" #include "vtkActorCollection.h" #include "vtkCamera.h" #include "vtkCellData.h" #include "vtkDoubleArray.h" #include "vtkExtractEdges.h" #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkLight.h" #include "vtkLightCollection.h" #include "vtkOSPRayActorNode.h" #include "vtkOSPRayPass.h" #include "vtkOSPRayRendererNode.h" #include "vtkOpenGLRenderer.h" #include "vtkPiecewiseFunction.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkPolyDataNormals.h" #include "vtkProperty.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkSmartPointer.h" #include "vtkSphereSource.h" #include "vtkStripper.h" #include "vtkTexture.h" #include "vtkTextureMapToSphere.h" #include "vtkTransformTextureCoords.h" #include "vtkUnsignedCharArray.h" #include "vtkVertexGlyphFilter.h" #include <string> #include <vector> #include "vtkOSPRayTestInteractor.h" class renderable { public: vtkSphereSource* s; vtkPolyDataMapper* m; vtkActor* a; ~renderable() { s->Delete(); m->Delete(); a->Delete(); } }; renderable* MakeSphereAt(double x, double y, double z, int res, int type, int rep, const char* name) { vtkOSPRayTestInteractor::AddName(name); renderable* ret = new renderable; ret->s = vtkSphereSource::New(); ret->s->SetEndTheta(180); // half spheres better show variation and f and back ret->s->SetStartPhi(30); ret->s->SetEndPhi(150); ret->s->SetPhiResolution(res); ret->s->SetThetaResolution(res); ret->s->SetCenter(x, y, z); // make texture coordinate vtkSmartPointer<vtkTextureMapToSphere> tc = vtkSmartPointer<vtkTextureMapToSphere>::New(); tc->SetCenter(x, y, z); tc->PreventSeamOn(); tc->AutomaticSphereGenerationOff(); tc->SetInputConnection(ret->s->GetOutputPort()); vtkSmartPointer<vtkTransformTextureCoords> tt = vtkSmartPointer<vtkTransformTextureCoords>::New(); tt->SetInputConnection(tc->GetOutputPort()); // tt->SetScale(1,0.5,1); // make normals vtkSmartPointer<vtkPolyDataNormals> nl = vtkSmartPointer<vtkPolyDataNormals>::New(); nl->SetInputConnection(tt->GetOutputPort()); nl->Update(); // make more attribute arrays vtkPolyData* pd = nl->GetOutput(); // point aligned vtkSmartPointer<vtkDoubleArray> da = vtkSmartPointer<vtkDoubleArray>::New(); da->SetName("testarray1"); da->SetNumberOfComponents(1); pd->GetPointData()->AddArray(da); int np = pd->GetNumberOfPoints(); int nc = pd->GetNumberOfCells(); for (int i = 0; i < np; i++) { da->InsertNextValue((double)i / (double)np); } da = vtkSmartPointer<vtkDoubleArray>::New(); da->SetName("testarray2"); da->SetNumberOfComponents(3); pd->GetPointData()->AddArray(da); for (int i = 0; i < np; i++) { double vals[3] = { (double)i / (double)np, (double)(i * 4) / (double)np - 2.0, 42.0 }; da->InsertNextTuple3(vals[0], vals[1], vals[2]); } vtkSmartPointer<vtkUnsignedCharArray> pac = vtkSmartPointer<vtkUnsignedCharArray>::New(); pac->SetName("testarrayc1"); pac->SetNumberOfComponents(3); pd->GetPointData()->AddArray(pac); for (int i = 0; i < np; i++) { unsigned char vals[3] = { static_cast<unsigned char>(255 * ((double)i / (double)np)), static_cast<unsigned char>(255 * ((double)(i * 4) / (double)np - 2.0)), 42 }; pac->InsertNextTuple3(vals[0], vals[1], vals[2]); } vtkSmartPointer<vtkUnsignedCharArray> ca = vtkSmartPointer<vtkUnsignedCharArray>::New(); ca->SetName("testarray3"); ca->SetNumberOfComponents(3); pd->GetPointData()->AddArray(ca); for (int i = 0; i < np; i++) { unsigned char vals[3] = { static_cast<unsigned char>((double)i / (double)np * 255), static_cast<unsigned char>((double)(1 - i) / (double)np), 42 }; ca->InsertNextTuple3(vals[0], vals[1], vals[2]); } // cell aligned da = vtkSmartPointer<vtkDoubleArray>::New(); da->SetName("testarray4"); da->SetNumberOfComponents(1); pd->GetCellData()->AddArray(da); for (int i = 0; i < pd->GetNumberOfCells(); i++) { da->InsertNextValue((double)i / (double)pd->GetNumberOfCells()); } da = vtkSmartPointer<vtkDoubleArray>::New(); da->SetName("testarray5"); da->SetNumberOfComponents(3); pd->GetCellData()->AddArray(da); for (int i = 0; i < nc; i++) { double vals[3] = { (double)i / (double)nc, (double)(i * 2) / (double)nc, 42.0 }; da->InsertNextTuple3(vals[0], vals[1], vals[2]); } ca = vtkSmartPointer<vtkUnsignedCharArray>::New(); ca->SetName("testarray6"); ca->SetNumberOfComponents(3); pd->GetCellData()->AddArray(ca); for (int i = 0; i < nc; i++) { unsigned char vals[3] = { static_cast<unsigned char>((double)i / (double)np * 255), static_cast<unsigned char>((double)(1 - i) / (double)np), 42 }; ca->InsertNextTuple3(vals[0], vals[1], vals[2]); } ret->m = vtkPolyDataMapper::New(); ret->m->SetInputData(pd); switch (type) { case 0: // points { vtkSmartPointer<vtkVertexGlyphFilter> filter = vtkSmartPointer<vtkVertexGlyphFilter>::New(); filter->SetInputData(pd); filter->Update(); ret->m->SetInputData(filter->GetOutput()); break; } case 1: // lines { vtkSmartPointer<vtkExtractEdges> filter = vtkSmartPointer<vtkExtractEdges>::New(); filter->SetInputData(pd); filter->Update(); ret->m->SetInputData(filter->GetOutput()); break; } case 2: // polys break; case 3: // strips { vtkSmartPointer<vtkStripper> filter = vtkSmartPointer<vtkStripper>::New(); filter->SetInputData(pd); filter->Update(); ret->m->SetInputData(filter->GetOutput()); break; } } ret->a = vtkActor::New(); ret->a->SetMapper(ret->m); ret->a->GetProperty()->SetPointSize(20); ret->a->GetProperty()->SetLineWidth(10); if (rep != -1) { ret->a->GetProperty()->SetRepresentation(rep); } return ret; } int TestOSPRayRenderMesh(int argc, char* argv[]) { bool useGL = false; int type = 2; int rep = -1; for (int i = 0; i < argc; i++) { if (!strcmp(argv[i], "-GL")) { useGL = true; } if (!strcmp(argv[i], "-type")) { type = atoi(argv[i + 1]); } if (!strcmp(argv[i], "-rep")) { rep = atoi(argv[i + 1]); } } vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New(); iren->SetRenderWindow(renWin); vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); renWin->AddRenderer(renderer); renderer->AutomaticLightCreationOn(); renderer->SetBackground(0.75, 0.75, 0.75); renderer->SetEnvironmentalBG(0.75, 0.75, 0.75); renWin->SetSize(600, 550); vtkSmartPointer<vtkCamera> camera = vtkSmartPointer<vtkCamera>::New(); camera->SetPosition(2.5, 11, -3); camera->SetFocalPoint(2.5, 0, -3); camera->SetViewUp(0, 0, 1); renderer->SetActiveCamera(camera); renWin->Render(); vtkSmartPointer<vtkOSPRayPass> ospray = vtkSmartPointer<vtkOSPRayPass>::New(); if (!useGL) { renderer->SetPass(ospray); for (int i = 0; i < argc; ++i) { if (!strcmp(argv[i], "--OSPRayPT")) { vtkOSPRayRendererNode::SetRendererType("OSPRay pathtracer", renderer); break; } if (!strcmp(argv[i], "--OptiX")) { vtkOSPRayRendererNode::SetRendererType("optix pathtracer", renderer); break; } } } // Now, vary most of the many parameters that rendering can vary by. renderable* ren; // representations points, wireframe, surface ren = MakeSphereAt(5, 0, -5, 10, type, rep, "points"); ren->a->GetProperty()->SetRepresentationToPoints(); renderer->AddActor(ren->a); delete (ren); ren = MakeSphereAt(5, 0, -4, 10, type, rep, "wireframe"); ren->a->GetProperty()->SetRepresentationToWireframe(); renderer->AddActor(ren->a); delete (ren); ren = MakeSphereAt(5, 0, -3, 10, type, rep, "surface"); ren->a->GetProperty()->SetRepresentationToSurface(); renderer->AddActor(ren->a); delete (ren); // actor color ren = MakeSphereAt(4, 0, -5, 10, type, rep, "actor_color"); ren->a->GetProperty()->SetColor(0, 1, 0); renderer->AddActor(ren->a); delete (ren); // ambient, diffuse, and specular components ren = MakeSphereAt(4, 0, -4, 7, type, rep, "amb/diff/spec"); ren->a->GetProperty()->SetAmbient(0.5); ren->a->GetProperty()->SetAmbientColor(0.1, 0.1, 0.3); ren->a->GetProperty()->SetDiffuse(0.4); ren->a->GetProperty()->SetDiffuseColor(0.5, 0.1, 0.1); ren->a->GetProperty()->SetSpecular(0.2); ren->a->GetProperty()->SetSpecularColor(1, 1, 1); ren->a->GetProperty()->SetSpecularPower(100); ren->a->GetProperty()->SetInterpolationToPhong(); renderer->AddActor(ren->a); delete (ren); // opacity ren = MakeSphereAt(4, 0, -3, 10, type, rep, "opacity"); ren->a->GetProperty()->SetOpacity(0.2); renderer->AddActor(ren->a); delete (ren); // color map cell values ren = MakeSphereAt(3, 0, -5, 10, type, rep, "cell_value"); ren->m->SetScalarModeToUseCellFieldData(); ren->m->SelectColorArray(0); renderer->AddActor(ren->a); delete (ren); // default color component ren = MakeSphereAt(3, 0, -4, 10, type, rep, "cell_default_comp"); ren->m->SetScalarModeToUseCellFieldData(); ren->m->SelectColorArray(1); renderer->AddActor(ren->a); delete (ren); // choose color component ren = MakeSphereAt(3, 0, -3, 10, type, rep, "cell_comp_1"); ren->m->SetScalarModeToUseCellFieldData(); ren->m->SelectColorArray(1); ren->m->ColorByArrayComponent(1, 1); // todo, use lut since this is deprecated renderer->AddActor(ren->a); delete (ren); // RGB direct ren = MakeSphereAt(3, 0, -2, 10, type, rep, "cell_rgb"); ren->m->SetScalarModeToUseCellFieldData(); ren->m->SelectColorArray(2); renderer->AddActor(ren->a); delete (ren); // RGB through LUT ren = MakeSphereAt(3, 0, -1, 10, type, rep, "cell_rgb_through_LUT"); ren->m->SetScalarModeToUseCellFieldData(); ren->m->SelectColorArray(2); ren->m->SetColorModeToMapScalars(); renderer->AddActor(ren->a); delete (ren); // color map point values ren = MakeSphereAt(2, 0, -5, 6, type, rep, "point_value"); ren->m->SetScalarModeToUsePointFieldData(); ren->m->SelectColorArray("testarray1"); renderer->AddActor(ren->a); delete (ren); // interpolate scalars before mapping ren = MakeSphereAt(2, 0, -4, 6, type, rep, "point_interp"); ren->m->SetScalarModeToUsePointFieldData(); ren->m->SelectColorArray("testarray1"); ren->m->InterpolateScalarsBeforeMappingOn(); renderer->AddActor(ren->a); delete (ren); // RGB direct ren = MakeSphereAt(2, 0, -3, 10, type, rep, "point_rgb"); ren->m->SetScalarModeToUsePointFieldData(); ren->m->SetColorModeToDefault(); ren->m->SelectColorArray("testarrayc1"); renderer->AddActor(ren->a); delete (ren); // RGB mapped ren = MakeSphereAt(2, 0, -2, 10, type, rep, "point_rgb_through_LUT"); ren->m->SetScalarModeToUsePointFieldData(); ren->m->SetColorModeToMapScalars(); ren->m->SelectColorArray("testarrayc1"); renderer->AddActor(ren->a); delete (ren); // unlit, flat, and gouraud lighting ren = MakeSphereAt(1, 0, -5, 7, type, rep, "not_lit"); ren->a->GetProperty()->LightingOff(); renderer->AddActor(ren->a); delete (ren); ren = MakeSphereAt(1, 0, -4, 7, type, rep, "flat"); ren->a->GetProperty()->SetInterpolationToFlat(); renderer->AddActor(ren->a); delete (ren); ren = MakeSphereAt(1, 0, -3, 7, type, rep, "gouraud"); ren->a->GetProperty()->SetInterpolationToGouraud(); renderer->AddActor(ren->a); delete (ren); // texture int maxi = 100; int maxj = 100; vtkSmartPointer<vtkImageData> texin = vtkSmartPointer<vtkImageData>::New(); texin->SetExtent(0, maxi, 0, maxj, 0, 0); texin->AllocateScalars(VTK_UNSIGNED_CHAR, 3); vtkUnsignedCharArray* aa = vtkArrayDownCast<vtkUnsignedCharArray>(texin->GetPointData()->GetScalars()); int idx = 0; for (int i = 0; i <= maxi; i++) { for (int j = 0; j <= maxj; j++) { bool ival = (i / 10) % 2 == 1; bool jval = (j / 10) % 2 == 1; unsigned char val = (ival ^ jval) ? 255 : 0; aa->SetTuple3(idx, val, val, val); if (j <= 3 || j >= maxj - 3) { aa->SetTuple3(idx, 255, 255, 0); } if (i <= 20 || i >= maxi - 20) { aa->SetTuple3(idx, 255, 0, 0); } idx = idx + 1; } } ren = MakeSphereAt(0, 0, -5, 20, type, rep, "texture"); renderer->AddActor(ren->a); vtkSmartPointer<vtkTexture> texture = vtkSmartPointer<vtkTexture>::New(); texture->SetInputData(texin); ren->a->SetTexture(texture); delete (ren); // imagespace positional transformations ren = MakeSphereAt(0, 0, -4, 10, type, rep, "transform"); ren->a->SetScale(1.2, 1.0, 0.87); renderer->AddActor(ren->a); delete (ren); // TODO: lut manipulation and range effects // TODO: NaN colors // TODO: mapper clipping planes // TODO: hierarchical actors renWin->Render(); vtkLight* light = vtkLight::SafeDownCast(renderer->GetLights()->GetItemAsObject(0)); double lColor[3]; light->GetDiffuseColor(lColor); light->SetPosition(2, 15, -2); light->SetFocalPoint(2, 0, -2); light->PositionalOff(); vtkSmartPointer<vtkOSPRayTestInteractor> style = vtkSmartPointer<vtkOSPRayTestInteractor>::New(); style->SetPipelineControlPoints(renderer, ospray, nullptr); iren->SetInteractorStyle(style); style->SetCurrentRenderer(renderer); iren->Start(); return 0; }
31.980851
100
0.651986
[ "mesh", "render", "vector", "transform" ]
33c4328854a91395546c10bafa22d2273166b3a8
11,625
hpp
C++
glfw3_app/gameemu/gameemu.hpp
hirakuni45/glfw3_app
d9ceeef6d398229fda4849afe27f8b48d1597fcf
[ "BSD-3-Clause" ]
9
2015-09-22T21:36:57.000Z
2021-04-01T09:16:53.000Z
glfw3_app/gameemu/gameemu.hpp
hirakuni45/glfw3_app
d9ceeef6d398229fda4849afe27f8b48d1597fcf
[ "BSD-3-Clause" ]
null
null
null
glfw3_app/gameemu/gameemu.hpp
hirakuni45/glfw3_app
d9ceeef6d398229fda4849afe27f8b48d1597fcf
[ "BSD-3-Clause" ]
2
2019-02-21T04:22:13.000Z
2021-03-02T17:24:32.000Z
#pragma once //=====================================================================// /*! @file @brief GAME Emulator クラス @n Copyright 2019 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "main.hpp" #include "utils/i_scene.hpp" #include "utils/director.hpp" #include "widgets/widget.hpp" #include "widgets/widget_frame.hpp" #include "widgets/widget_terminal.hpp" #include "widgets/widget_filer.hpp" #include "widgets/widget_dialog.hpp" #include "widgets/widget_spinbox.hpp" #include "widgets/widget_button.hpp" #include "widgets/widget_slider.hpp" #include "gl_fw/gltexfb.hpp" #include "snd_io/pcm.hpp" #include "utils/fifo.hpp" #include "utils/input.hpp" // #include "includes/rallyx.h" namespace app { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief nesemu シーン・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class gameemu : public utils::i_scene { utils::director<core>& director_; gui::widget_frame* terminal_frame_; gui::widget_terminal* terminal_core_; bool terminal_; gui::widget_filer* filer_; gui::widget_frame* menu_frame_; gui::widget_dialog* dialog_; gl::texfb texfb_; static const int game_width_ = 288; static const int game_height_ = 256; static const int sample_rate_ = 44100; static const int audio_len_ = sample_rate_ / 60; uint8_t fb_[game_width_ * game_height_ * 4]; void pad_() { gl::core& core = gl::core::get_instance(); const gl::device& dev = core.get_device(); // inp_[0].data = 0; // inp_[1].data = 0; // A if(dev.get_level(gl::device::key::Z)) { // inp_[0].data |= INP_PAD_A; } if(dev.get_level(gl::device::key::GAME_0)) { // inp_[0].data |= INP_PAD_A; } // B if(dev.get_level(gl::device::key::X)) { // inp_[0].data |= INP_PAD_B; } if(dev.get_level(gl::device::key::GAME_1)) { // inp_[0].data |= INP_PAD_B; } // SELECT if(dev.get_level(gl::device::key::_1)) { // inp_[0].data |= INP_PAD_SELECT; } if(dev.get_level(gl::device::key::GAME_2)) { // inp_[0].data |= INP_PAD_SELECT; } // START if(dev.get_level(gl::device::key::_2)) { // inp_[0].data |= INP_PAD_START; } if(dev.get_level(gl::device::key::GAME_3)) { // inp_[0].data |= INP_PAD_START; } if(dev.get_level(gl::device::key::LEFT)) { // inp_[0].data |= INP_PAD_LEFT; } if(dev.get_level(gl::device::key::GAME_LEFT)) { // inp_[0].data |= INP_PAD_LEFT; } if(dev.get_level(gl::device::key::RIGHT)) { // inp_[0].data |= INP_PAD_RIGHT; } if(dev.get_level(gl::device::key::GAME_RIGHT)) { // inp_[0].data |= INP_PAD_RIGHT; } if(dev.get_level(gl::device::key::UP)) { // inp_[0].data |= INP_PAD_UP; } if(dev.get_level(gl::device::key::GAME_UP)) { // inp_[0].data |= INP_PAD_UP; } if(dev.get_level(gl::device::key::DOWN)) { // inp_[0].data |= INP_PAD_DOWN; } if(dev.get_level(gl::device::key::GAME_DOWN)) { // inp_[0].data |= INP_PAD_DOWN; } } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// gameemu(utils::director<core>& d) : director_(d), terminal_frame_(nullptr), terminal_core_(nullptr), terminal_(false), menu_frame_(nullptr), dialog_(nullptr) { } //-----------------------------------------------------------------// /*! @brief デストラクター */ //-----------------------------------------------------------------// virtual ~gameemu() { } //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void initialize() { gl::core& core = gl::core::get_instance(); using namespace gui; widget_director& wd = director_.at().widget_director_; { // ターミナル { widget::param wp(vtx::irect(10, 10, 200, 200)); widget_frame::param wp_; wp_.plate_param_.set_caption(15); terminal_frame_ = wd.add_widget<widget_frame>(wp, wp_); terminal_frame_->enable(terminal_); } { widget::param wp(vtx::irect(0), terminal_frame_); widget_terminal::param wp_; wp_.enter_func_ = [=] (const utils::lstring& inp) { /// auto s = utils::utf32_to_utf8(inp); /// tools_.command(s); }; terminal_core_ = wd.add_widget<widget_terminal>(wp, wp_); /// emu::tools::set_terminal(terminal_core_); } } { // ファイラー widget::param wp(vtx::irect(10, 10, 200, 200)); widget_filer::param wp_(core.get_current_path(), ""); wp_.select_file_func_ = [=](const std::string& fn) { }; filer_ = wd.add_widget<widget_filer>(wp, wp_); filer_->enable(false); } #if 0 { { // メニュー widget::param wp(vtx::irect(20, 20, 210, 200)); widget_frame::param wp_; wp_.plate_param_.set_caption(15); menu_frame_ = wd.add_widget<widget_frame>(wp, wp_); menu_frame_->enable(false); menu_frame_->at_param().state_.set(widget::state::SIZE_LOCK); } { // スピン・ボックス widget::param wp(vtx::irect(10, 35, 90, 30), menu_frame_); widget_spinbox::param wp_(0, 0, 9); wp_.select_func_ = [=] (widget_spinbox::state st, int before, int newpos) { return (boost::format("%d") % newpos).str(); }; state_slot_ = wd.add_widget<widget_spinbox>(wp, wp_); } { // ステート・セーブ widget::param wp(vtx::irect(110, 35+40*0, 90, 30), menu_frame_); widget_button::param wp_("Save"); state_save_ = wd.add_widget<widget_button>(wp, wp_); state_save_->at_local_param().select_func_ = [=](int id) { state_setslot(get_state_no_()); if(state_save() != 0) { dialog_->set_text("Save state error"); dialog_->enable(); } else { if(filer_ != nullptr) filer_->rescan_center(); } }; } { // ステート・ロード widget::param wp(vtx::irect(110, 35+40*1, 90, 30), menu_frame_); widget_button::param wp_("Load"); state_load_ = wd.add_widget<widget_button>(wp, wp_); state_load_->at_local_param().select_func_ = [=](int id) { state_setslot(get_state_no_()); if(!nes_play_) { dialog_->set_text("Load state error: 'NES file not load'"); dialog_->enable(); } else if(state_load() != 0) { dialog_->set_text("Load state error"); dialog_->enable(); } }; } { // NES リセット widget::param wp(vtx::irect(10, 35+40*2, 90, 30), menu_frame_); widget_button::param wp_("Reset"); nes_reset_ = wd.add_widget<widget_button>(wp, wp_); nes_reset_->at_local_param().select_func_ = [=](int id) { nes_reset(HARD_RESET); }; } { // ボリューム widget::param wp(vtx::irect(10, 35+40*3, 190, 20), menu_frame_); widget_slider::param wp_(0.5f); volume_ = wd.add_widget<widget_slider>(wp, wp_); } } #endif { // Daialog widget::param wp(vtx::irect(70, 70, 300, 150)); widget_dialog::param wp_; wp_.style_ = widget_dialog::style::OK; dialog_ = wd.add_widget<widget_dialog>(wp, wp_); dialog_->enable(false); } texfb_.initialize(game_width_, game_height_, 32); #if 0 // regist input inp_[0].type = INP_JOYPAD0; inp_[0].data = 0; input_register(&inp_[0]); inp_[1].type = INP_JOYPAD1; inp_[1].data = 0; input_register(&inp_[1]); // ツール・セット初期化 tools_.init(); #endif // プリファレンスの取得 sys::preference& pre = director_.at().preference_; if(filer_ != nullptr) { filer_->load(pre); } if(terminal_frame_ != nullptr) { terminal_frame_->load(pre); } // if(menu_frame_ != nullptr) { // menu_frame_->load(pre, false, false); // } // if(volume_ != nullptr) { // volume_->load(pre); // } } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update() { gl::core& core = gl::core::get_instance(); const gl::device& dev = core.get_device(); #if 0 if(dev.get_negative(gl::device::key::F1)) { filer_->enable(!filer_->get_enable()); } if(dev.get_negative(gl::device::key::F5)) { terminal_ = !terminal_; terminal_frame_->enable(terminal_); } if(dev.get_positive(gl::device::key::ESCAPE)) { nes_pause_ ^= 1; // nes_pause(nes_pause_); } if(dev.get_positive(gl::device::key::F2)) { menu_ = !menu_; menu_frame_->enable(menu_); } if(nes_play_ || nsf_play_) { if(nes_play_) { if(!terminal_ && !menu_) { pad_(); } nes_emulate(1); } if(nsf_play_) { } // copy sound emulation al::sound& sound = director_.at().sound_; uint32_t len = audio_len_; uint32_t mod = 16; if(sound.get_queue_audio_length() < mod) { len += mod; } al::sound::waves16 tmp; tmp.resize(len); apu_process(&tmp[0], len); sound.queue_audio(tmp); // copy video if(nes_play_) { auto nes = nes_getcontext(); bitmap_t* v = nes->vidbuf; const rgb_t* lut = get_palette(); if(v != nullptr && lut != nullptr) { for(int h = 0; h < nes_height_; ++h) { const uint8_t* src = &v->data[h * v->pitch]; uint8_t* dst = &fb_[h * nes_width_ * 4]; for(int w = 0; w < nes_width_; ++w) { auto idx = *src++; idx &= 63; *dst++ = lut[idx].r; // R *dst++ = lut[idx].g; // G *dst++ = lut[idx].b; // B *dst++ = 255; // alpha } } texfb_.rendering(gl::texfb::image::RGBA, (const char*)&fb_[0]); } texfb_.flip(); } // ストリームのゲイン(volume)を設定 if(volume_ != nullptr) { auto vol = volume_->get_slider_param().position_; al::sound& sound = director_.at().sound_; sound.set_gain_stream(vol); } } tools_.service(); #endif gui::widget_director& wd = director_.at().widget_director_; wd.update(); } //-----------------------------------------------------------------// /*! @brief レンダリング */ //-----------------------------------------------------------------// void render() { gl::core& core = gl::core::get_instance(); const vtx::spos& siz = core.get_rect().size; texfb_.setup_matrix(0, 0, siz.x, siz.y); float scale = 1.0f; float ofsx = 0.0f; float ofsy = 0.0f; if(siz.x < siz.y) { scale = static_cast<float>(siz.x) / static_cast<float>(game_width_); float h = static_cast<float>(game_height_); ofsy = (static_cast<float>(siz.y) - h * scale) * 0.5f; } else { scale = static_cast<float>(siz.y) / static_cast<float>(game_height_); float w = static_cast<float>(game_width_); ofsx = (static_cast<float>(siz.x) - w * scale) * 0.5f; } gl::glTranslate(ofsx, ofsy); gl::glScale(scale); texfb_.draw(); director_.at().widget_director_.service(); director_.at().widget_director_.render(); } //-----------------------------------------------------------------// /*! @brief 廃棄 */ //-----------------------------------------------------------------// void destroy() { /// emu::tools::set_terminal(nullptr); sys::preference& pre = director_.at().preference_; if(filer_ != nullptr) { filer_->save(pre); } if(terminal_frame_ != nullptr) { terminal_frame_->save(pre); } #if 0 if(menu_frame_ != nullptr) { menu_frame_->save(pre); } if(volume_ != nullptr) { volume_->save(pre); } #endif } }; }
26.601831
80
0.537892
[ "render" ]
33c43eae525d3d44f92be0a9b3a8b0aa2370e3c2
42,783
cpp
C++
aten/src/ATen/test/vulkan_api_test.cpp
vladap2013/pytorch
30367773056de95e006107d82ddaa3db5eeaa05a
[ "Intel" ]
1
2021-06-17T13:02:45.000Z
2021-06-17T13:02:45.000Z
aten/src/ATen/test/vulkan_api_test.cpp
vladap2013/pytorch
30367773056de95e006107d82ddaa3db5eeaa05a
[ "Intel" ]
null
null
null
aten/src/ATen/test/vulkan_api_test.cpp
vladap2013/pytorch
30367773056de95e006107d82ddaa3db5eeaa05a
[ "Intel" ]
null
null
null
#ifdef USE_VULKAN_API #include <gtest/gtest.h> #include <ATen/ATen.h> // TODO: These functions should move to a common place. namespace { bool checkRtol(const at::Tensor& diff, const std::vector<at::Tensor>& inputs) { float maxValue = 0.0f; for (const auto& tensor : inputs) { maxValue = fmax(tensor.abs().max().item<float>(), maxValue); } #ifdef USE_VULKAN_FP16_INFERENCE constexpr float tolerance = 1e-2; #else constexpr float tolerance = 1e-5; #endif return diff.abs().max().item<float>() < (tolerance * maxValue); } bool almostEqual(const at::Tensor& a, const at::Tensor& b) { return checkRtol(a - b, {a, b}); } bool exactlyEqual(const at::Tensor& a, const at::Tensor& b) { return (a - b).abs().max().item<float>() == 0.0f; } void showRtol(const at::Tensor& a, const at::Tensor& b) { const auto diff = (a - b).abs(); float maxValue = a.abs().max().item<float>(); maxValue = fmax(b.abs().max().item<float>(), maxValue); #ifdef USE_VULKAN_FP16_INFERENCE constexpr float tolerance = 1e-2; #else constexpr float tolerance = 1e-5; #endif const float maxDiff = maxValue * tolerance; std::cout << "Max Diff allowed: " << maxDiff << std::endl; if (diff.sizes().size() == 2) { for (int y = 0; y < diff.sizes()[0]; y++) { std::cout << y << ":"; for (int x = 0; x < diff.sizes()[1]; x++) { float diff_xy = diff[y][x].item<float>(); if (diff_xy > maxDiff) { std::cout << std::setw(5) << x; } else { std::cout << std::setw(5) << " "; } } std::cout << std::endl; } } } } // namespace namespace { TEST(VulkanAPITest, adaptive_avg_pool2d) { if (!at::is_vulkan_available()) { return; } at::AutoNonVariableTypeMode nonVarTypeModeGuard(true); const auto in_cpu = at::rand({5, 7, 47, 31}, at::TensorOptions(at::kCPU).dtype(at::kFloat)); const auto out_cpu = at::adaptive_avg_pool2d(in_cpu, {3, 3}); const auto out_vulkan = at::adaptive_avg_pool2d(in_cpu.vulkan(), {3, 3}); const auto check = almostEqual(out_cpu, out_vulkan.cpu()); if (!check) { showRtol(out_cpu, out_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, add) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({11, 7, 139, 109}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({11, 7, 139, 109}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::add(a_cpu, b_cpu, 2.1f); const auto c_vulkan = at::add(a_vulkan, b_vulkan, 2.1f); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, add_broadcast0) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({3, 5, 179, 221}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({3, 5, 1, 1}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::add(a_cpu, b_cpu, 1.8f); const auto c_vulkan = at::add(a_vulkan, b_vulkan, 1.8f); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, add_broadcast1) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({3, 5, 179, 221}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({3, 5, 1, 221}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::add(a_cpu, b_cpu, 1.8f); const auto c_vulkan = at::add(a_vulkan, b_vulkan, 1.8f); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, add_broadcast2) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({3, 4, 179, 221}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({4, 1, 1}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::add(a_cpu, b_cpu, 2.5f); const auto c_vulkan = at::add(a_vulkan, b_vulkan, 2.5f); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, add_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({61, 17, 29, 83}, at::device(at::kCPU).dtype(at::kFloat)); auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({61, 17, 29, 83}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); a_cpu.add_(b_cpu, 2.1f); a_vulkan.add_(b_vulkan, 2.1f); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(b_cpu, b_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, add_broadcast0_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({16, 17, 29, 83}, at::device(at::kCPU).dtype(at::kFloat)); auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({16, 17, 29, 1}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); a_cpu.add_(b_cpu, 2.1f); a_vulkan.add_(b_vulkan, 2.1f); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(b_cpu, b_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, add_broadcast1_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({3, 8, 29, 83}, at::device(at::kCPU).dtype(at::kFloat)); auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({3, 8, 1, 1}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); a_cpu.add_(b_cpu, 2.1f); a_vulkan.add_(b_vulkan, 2.1f); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(b_cpu, b_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, add_scalar) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({13, 23, 59, 73}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const float b_scalar = 3.1415f; const auto c_cpu = at::add(a_cpu, b_scalar, 2.1f); const auto c_vulkan = at::add(a_vulkan, b_scalar, 2.1f); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, add_scalar_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({47, 2, 23, 97}, at::device(at::kCPU).dtype(at::kFloat)); auto a_vulkan = a_cpu.vulkan(); const float b_scalar = 3.1415f; a_cpu.add_(b_scalar, 2.1f); a_vulkan.add_(b_scalar, 2.1f); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(a_cpu, a_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, addmm) { if (!at::is_vulkan_available()) { return; } constexpr float alpha = 2.1f; constexpr float beta = 103.24; const auto bias_cpu = at::rand({179, 163}, at::device(at::kCPU).dtype(at::kFloat)); const auto m1_cpu = at::rand({179, 67}, at::device(at::kCPU).dtype(at::kFloat)); const auto m2_cpu = at::rand({67, 163}, at::device(at::kCPU).dtype(at::kFloat)); const auto out_cpu = at::addmm(bias_cpu, m1_cpu, m2_cpu, beta, alpha); const auto m1_vulkan = m1_cpu.vulkan(); const auto out_vulkan = at::addmm(bias_cpu, m1_vulkan, m2_cpu, beta, alpha); const auto check = almostEqual(out_cpu, out_vulkan.cpu()); if (!check) { showRtol(out_cpu, out_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, addmm_expand) { if (!at::is_vulkan_available()) { return; } constexpr float alpha = 2.1f; constexpr float beta = 103.24; const auto bias_cpu = at::rand({1000}, at::device(at::kCPU).dtype(at::kFloat)); const auto m1_cpu = at::rand({1, 1280}, at::device(at::kCPU).dtype(at::kFloat)); const auto m2_cpu = at::rand({1280, 1000}, at::device(at::kCPU).dtype(at::kFloat)); const auto out_cpu = at::addmm(bias_cpu, m1_cpu, m2_cpu, beta, alpha); const auto m1_vulkan = m1_cpu.vulkan(); const auto out_vulkan = at::addmm(bias_cpu, m1_vulkan, m2_cpu, beta, alpha); const auto check = almostEqual(out_cpu, out_vulkan.cpu()); if (!check) { showRtol(out_cpu, out_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, avg_pool2d) { if (!at::is_vulkan_available()) { return; } const auto in_cpu = at::rand({3, 19, 43, 79}, at::TensorOptions(at::kCPU).dtype(at::kFloat)); const auto out_cpu = at::avg_pool2d(in_cpu, {5, 3}, {1, 2}, {2, 0}, true); const auto out_vulkan = at::avg_pool2d(in_cpu.vulkan(), {5, 3}, {1, 2}, {2, 0}, true); const auto check = almostEqual(out_cpu, out_vulkan.cpu()); if (!check) { showRtol(out_cpu, out_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, clamp) { if (!at::is_vulkan_available()) { return; } const auto in_cpu = at::rand({17, 197, 302, 5}, at::device(at::kCPU).dtype(at::kFloat)); const auto in_vulkan = in_cpu.vulkan(); const float min_value = 0.2f; const float max_value = 0.8f; const auto out_cpu = at::clamp(in_cpu, min_value, max_value); const auto out_vulkan = at::clamp(in_vulkan, min_value, max_value); const auto check = almostEqual(out_cpu, out_vulkan.cpu()); if (!check) { showRtol(out_cpu, out_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, clamp_) { if (!at::is_vulkan_available()) { return; } const auto cpu = at::rand({17, 197, 302, 5}, at::device(at::kCPU).dtype(at::kFloat)); const auto vulkan = cpu.vulkan(); const float min_value = 0.2f; const float max_value = 0.8f; cpu.clamp_(min_value, max_value); vulkan.clamp_(min_value, max_value); const auto check = almostEqual(cpu, vulkan.cpu()); if (!check) { showRtol(cpu, vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, conv2d) { if (!at::is_vulkan_available()) { return; } constexpr int64_t groups = 1; constexpr std::array<int64_t, 2u> stride{1, 2}; constexpr std::array<int64_t, 2u> padding{3, 0}; //TODO: Support conv2d with dilation != 1 constexpr std::array<int64_t, 2u> dilation{1, 1}; constexpr struct { uint32_t batches; uint32_t channels; uint32_t width; uint32_t height; std::array<int64_t, 4u> size() const { return { batches, channels, width, height, }; } } input {1, 37, 223, 227}; constexpr struct { uint32_t output_channels; uint32_t input_channels; uint32_t width; uint32_t height; std::array<int64_t, 4u> size() const { return { output_channels, input_channels, width, height, }; } } weights {83, input.channels, 13, 2}; const auto input_cpu = at::randn(input.size(), at::device(at::kCPU).dtype(at::kFloat)); const auto weights_cpu = at::randn(weights.size(), at::device(at::kCPU).dtype(at::kFloat)); const auto bias_cpu = at::randn({weights.output_channels}, at::device(at::kCPU).dtype(at::kFloat)); const auto output_cpu = at::conv2d( input_cpu, weights_cpu, bias_cpu, stride, padding, dilation, groups); const auto output_vulkan = at::conv2d( input_cpu.vulkan(), weights_cpu, bias_cpu, stride, padding, dilation, groups); const bool check = almostEqual(output_cpu, output_vulkan.cpu()); if (!check) { showRtol(output_cpu, output_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, conv2d_dw) { if (!at::is_vulkan_available()) { return; } constexpr int64_t groups = 7; constexpr std::array<int64_t, 2u> stride{2, 3}; constexpr std::array<int64_t, 2u> padding{0, 4}; constexpr std::array<int64_t, 2u> dilation{3, 1}; constexpr struct { uint32_t batches; uint32_t channels; uint32_t width; uint32_t height; std::array<int64_t, 4u> size() const { return { batches, channels, width, height, }; } } input {1, groups, 137, 199}; constexpr struct { uint32_t output_channels; uint32_t input_channels; uint32_t width; uint32_t height; std::array<int64_t, 4u> size() const { return { output_channels, input_channels, width, height, }; } } weights {groups, 1, 17, 7}; const auto input_cpu = at::rand(input.size(), at::device(at::kCPU).dtype(at::kFloat)); const auto weights_cpu = at::rand(weights.size(), at::device(at::kCPU).dtype(at::kFloat)); const auto bias_cpu = at::rand({weights.output_channels}, at::device(at::kCPU).dtype(at::kFloat)); const auto output_cpu = at::conv2d( input_cpu, weights_cpu, bias_cpu, stride, padding, dilation, groups); const auto output_vulkan = at::conv2d( input_cpu.vulkan(), weights_cpu, bias_cpu, stride, padding, dilation, groups); const bool check = almostEqual(output_cpu, output_vulkan.cpu()); if (!check) { showRtol(output_cpu, output_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, conv2d_pw) { if (!at::is_vulkan_available()) { return; } constexpr int64_t groups = 1; constexpr std::array<int64_t, 2u> stride{1, 1}; constexpr std::array<int64_t, 2u> padding{0, 0}; constexpr std::array<int64_t, 2u> dilation{1, 1}; constexpr struct { uint32_t batches; uint32_t channels; uint32_t width; uint32_t height; std::array<int64_t, 4u> size() const { return { batches, channels, width, height, }; } } input {1, 17, 127, 397}; constexpr struct { uint32_t output_channels; uint32_t input_channels; uint32_t width; uint32_t height; std::array<int64_t, 4u> size() const { return { output_channels, input_channels, width, height, }; } } weights {29, input.channels, 1, 1}; const auto input_cpu = at::randn(input.size(), at::device(at::kCPU).dtype(at::kFloat)); const auto weights_cpu = at::randn(weights.size(), at::device(at::kCPU).dtype(at::kFloat)); const auto bias_cpu = at::randn({weights.output_channels}, at::device(at::kCPU).dtype(at::kFloat)); const auto output_cpu = at::conv2d( input_cpu, weights_cpu, bias_cpu, stride, padding, dilation, groups); const auto output_vulkan = at::conv2d( input_cpu.vulkan(), weights_cpu, bias_cpu, stride, padding, dilation, groups); const bool check = almostEqual(output_cpu, output_vulkan.cpu()); if (!check) { showRtol(output_cpu, output_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, copy) { if (!at::is_vulkan_available()) { return; } const auto cpu = at::rand({13, 17, 37, 19}, at::device(at::kCPU).dtype(at::kFloat)); const auto vulkan = cpu.vulkan(); const auto check = exactlyEqual(cpu, vulkan.cpu()); if (!check) { showRtol(cpu, vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, div) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({11, 7, 139, 109}, at::device(at::kCPU).dtype(at::kFloat))+0.01; const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({11, 7, 139, 109}, at::device(at::kCPU).dtype(at::kFloat))+0.01; const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::div(a_cpu, b_cpu); const auto c_vulkan = at::div(a_vulkan, b_vulkan); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, div_broadcast0) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({3, 5, 1, 1}, at::device(at::kCPU).dtype(at::kFloat))+0.01; const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({3, 5, 179, 221}, at::device(at::kCPU).dtype(at::kFloat))+0.01; const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::div(a_cpu, b_cpu); const auto c_vulkan = at::div(a_vulkan, b_vulkan); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, div_broadcast1) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({3, 5, 179, 221}, at::device(at::kCPU).dtype(at::kFloat))+0.01; const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({3, 5, 1, 221}, at::device(at::kCPU).dtype(at::kFloat))+0.01; const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::div(a_cpu, b_cpu); const auto c_vulkan = at::div(a_vulkan, b_vulkan); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, div_broadcast2) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({3, 4, 179, 221}, at::device(at::kCPU).dtype(at::kFloat))+0.01; const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({4, 1, 1}, at::device(at::kCPU).dtype(at::kFloat))+0.01; const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::div(a_cpu, b_cpu); const auto c_vulkan = at::div(a_vulkan, b_vulkan); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, div_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({61, 17, 29, 83}, at::device(at::kCPU).dtype(at::kFloat))+0.01; auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({61, 17, 29, 83}, at::device(at::kCPU).dtype(at::kFloat))+0.01; const auto b_vulkan = b_cpu.vulkan(); a_cpu.div_(b_cpu); a_vulkan.div_(b_vulkan); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(b_cpu, b_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, div_broadcast0_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({12, 17, 29, 83}, at::device(at::kCPU).dtype(at::kFloat))+0.01; auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({12, 17, 29, 1}, at::device(at::kCPU).dtype(at::kFloat))+0.01; const auto b_vulkan = b_cpu.vulkan(); a_cpu.div_(b_cpu); a_vulkan.div_(b_vulkan); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(b_cpu, b_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, div_broadcast1_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({3, 8, 29, 83}, at::device(at::kCPU).dtype(at::kFloat))+0.01; auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({8, 1, 1}, at::device(at::kCPU).dtype(at::kFloat))+0.01; const auto b_vulkan = b_cpu.vulkan(); a_cpu.div_(b_cpu); a_vulkan.div_(b_vulkan); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(b_cpu, b_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, div_scalar) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({17, 213, 213, 7}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const float b_scalar = 3.1415f; const auto c_cpu = at::div(a_cpu, b_scalar); const auto c_vulkan = at::div(a_vulkan, b_scalar); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, div_scalar_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({11, 7, 139, 109}, at::device(at::kCPU).dtype(at::kFloat)); auto a_vulkan = a_cpu.vulkan(); const float b_scalar = 3.1415f; a_cpu.div_(b_scalar); a_vulkan.div_(b_scalar); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(a_cpu, a_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, empty) { if (!at::is_vulkan_available()) { return; } ASSERT_NO_THROW(at::empty({1, 17, 41, 53}, at::device(at::kVulkan).dtype(at::kFloat))); } TEST(VulkanAPITest, hardsigmoid) { if (!at::is_vulkan_available()) { return; } const auto in_cpu = at::rand({17, 197, 302, 5}, at::device(at::kCPU).dtype(at::kFloat))*12 - 6; const auto in_vulkan = in_cpu.vulkan(); const auto out_cpu = at::hardsigmoid(in_cpu); const auto out_vulkan = at::hardsigmoid(in_vulkan); const auto check = almostEqual(out_cpu, out_vulkan.cpu()); if (!check) { showRtol(out_cpu, out_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, hardsigmoid_) { if (!at::is_vulkan_available()) { return; } auto cpu = at::rand({17, 197, 302, 5}, at::device(at::kCPU).dtype(at::kFloat))*12 - 6; auto vulkan = cpu.vulkan(); at::native::hardsigmoid_(cpu); at::hardsigmoid_(vulkan); const auto check = almostEqual(cpu, vulkan.cpu()); if (!check) { showRtol(cpu, vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, hardswish) { if (!at::is_vulkan_available()) { return; } const auto in_cpu = at::rand({17, 197, 302, 5}, at::device(at::kCPU).dtype(at::kFloat))*12 - 6; const auto in_vulkan = in_cpu.vulkan(); const auto out_cpu = at::hardswish(in_cpu); const auto out_vulkan = at::hardswish(in_vulkan); const auto check = almostEqual(out_cpu, out_vulkan.cpu()); if (!check) { showRtol(out_cpu, out_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, hardswish_) { if (!at::is_vulkan_available()) { return; } auto cpu = at::rand({17, 197, 302, 5}, at::device(at::kCPU).dtype(at::kFloat))*12 - 6; auto vulkan = cpu.vulkan(); at::native::hardswish_(cpu); at::hardswish_(vulkan); const auto check = almostEqual(cpu, vulkan.cpu()); if (!check) { showRtol(cpu, vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, mean) { const auto in_cpu = at::rand({17, 3, 79, 53}, at::TensorOptions(at::kCPU).dtype(at::kFloat)); const auto out_cpu = at::mean(in_cpu, {-1, -2}, true); const auto in_vulkan = in_cpu.vulkan(); const auto out_vulkan = at::mean(in_vulkan, {-1, -2}, true); const auto check = almostEqual(out_cpu, out_vulkan.cpu()); if (!check) { showRtol(out_cpu, out_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, mean2d) { const auto in_cpu = at::rand({11, 7, 173, 37}, at::TensorOptions(at::kCPU).dtype(at::kFloat)); const auto out_cpu = at::mean(in_cpu, {-1, -2}, false); const auto in_vulkan = in_cpu.vulkan(); const auto out_vulkan = at::mean(in_vulkan, {-1, -2}, false); const auto check = almostEqual(out_cpu, out_vulkan.cpu()); if (!check) { showRtol(out_cpu, out_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, mm) { if (!at::is_vulkan_available()) { return; } const auto m1_cpu = at::rand({179, 67}, at::device(at::kCPU).dtype(at::kFloat)); const auto m2_cpu = at::rand({67, 163}, at::device(at::kCPU).dtype(at::kFloat)); const auto out_cpu = m1_cpu.mm(m2_cpu); const auto m1_vulkan = m1_cpu.vulkan(); const auto out_vulkan = m1_vulkan.mm(m2_cpu); const auto check = almostEqual(out_cpu, out_vulkan.cpu()); if (!check) { showRtol(out_cpu, out_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, mul) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({11, 7, 139, 109}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({11, 7, 139, 109}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::mul(a_cpu, b_cpu); const auto c_vulkan = at::mul(a_vulkan, b_vulkan); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, mul_broadcast0) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({3, 5, 1, 1}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({3, 5, 179, 221}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::mul(a_cpu, b_cpu); const auto c_vulkan = at::mul(a_vulkan, b_vulkan); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, mul_broadcast1) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({3, 5, 179, 221}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({3, 5, 1, 221}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::mul(a_cpu, b_cpu); const auto c_vulkan = at::mul(a_vulkan, b_vulkan); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, mul_broadcast2) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({3, 4, 179, 221}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({4, 1, 1}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::mul(a_cpu, b_cpu); const auto c_vulkan = at::mul(a_vulkan, b_vulkan); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, mul_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({61, 17, 29, 83}, at::device(at::kCPU).dtype(at::kFloat)); auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({61, 17, 29, 83}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); a_cpu.mul_(b_cpu); a_vulkan.mul_(b_vulkan); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(b_cpu, b_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, mul_broadcast0_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({12, 17, 29, 83}, at::device(at::kCPU).dtype(at::kFloat)); auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({12, 17, 29, 1}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); a_cpu.mul_(b_cpu); a_vulkan.mul_(b_vulkan); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(b_cpu, b_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, mul_broadcast1_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({3, 8, 29, 83}, at::device(at::kCPU).dtype(at::kFloat)); auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({8, 1, 1}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); a_cpu.mul_(b_cpu); a_vulkan.mul_(b_vulkan); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(b_cpu, b_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, mul_scalar) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({17, 213, 213, 7}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const float b_scalar = 3.1415f; const auto c_cpu = at::mul(a_cpu, b_scalar); const auto c_vulkan = at::mul(a_vulkan, b_scalar); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, mul_scalar_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({11, 7, 139, 109}, at::device(at::kCPU).dtype(at::kFloat)); auto a_vulkan = a_cpu.vulkan(); const float b_scalar = 3.1415f; a_cpu.mul_(b_scalar); a_vulkan.mul_(b_scalar); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(a_cpu, a_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, reflection_pad2d) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({2, 3, 47, 63}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const auto out_cpu = at::reflection_pad2d(a_cpu, {9,8,5,12}); const auto out_vulkan = at::reflection_pad2d(a_vulkan, {9,8,5,12}).cpu(); const auto check = almostEqual(out_cpu, out_vulkan); if (!check) { showRtol(out_cpu, out_vulkan); } ASSERT_TRUE(check); } TEST(VulkanAPITest, reshape) { if (!at::is_vulkan_available()) { return; } at::AutoNonVariableTypeMode nonVarTypeModeGuard(true); const auto in_cpu = at::rand({47, 11, 83, 97}, at::device(at::kCPU).dtype(at::kFloat)); const auto in_vulkan = in_cpu.vulkan(); const std::array<int64_t, 2> shape{47 * 83, 11 * 97}; const auto out_cpu = at::reshape(in_cpu, shape); const auto out_vulkan = at::reshape(in_vulkan, shape); const auto check = almostEqual(out_cpu, out_vulkan.cpu()); if (!check) { showRtol(out_cpu, out_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, reshape_) { if (!at::is_vulkan_available()) { return; } at::AutoNonVariableTypeMode nonVarTypeModeGuard(true); const auto cpu = at::rand({59, 41, 19, 67}, at::device(at::kCPU).dtype(at::kFloat)); const auto vulkan = cpu.vulkan(); const std::array<int64_t, 3> shape{59, 41 * 67, 19}; cpu.reshape(shape); vulkan.reshape(shape); const auto check = almostEqual(cpu, vulkan.cpu()); if (!check) { showRtol(cpu, vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, sub) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({11, 7, 139, 109}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({11, 7, 139, 109}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::sub(a_cpu, b_cpu, 2.1f); const auto c_vulkan = at::sub(a_vulkan, b_vulkan, 2.1f); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, sub_broadcast0) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({3, 5, 179, 221}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({3, 5, 1, 1}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::sub(a_cpu, b_cpu, 1.8f); const auto c_vulkan = at::sub(a_vulkan, b_vulkan, 1.8f); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, sub_broadcast1) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({3, 5, 179, 221}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({3, 5, 1, 221}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::sub(a_cpu, b_cpu, 1.8f); const auto c_vulkan = at::sub(a_vulkan, b_vulkan, 1.8f); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, sub_broadcast2) { if (!at::is_vulkan_available()) { return; } const auto a_cpu = at::rand({3, 4, 179, 221}, at::device(at::kCPU).dtype(at::kFloat)); const auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({4, 1, 1}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); const auto c_cpu = at::sub(a_cpu, b_cpu, 2.5f); const auto c_vulkan = at::sub(a_vulkan, b_vulkan, 2.5f); const auto check = almostEqual(c_cpu, c_vulkan.cpu()); if (!check) { showRtol(c_cpu, c_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, sub_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({61, 17, 29, 83}, at::device(at::kCPU).dtype(at::kFloat)); auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({61, 17, 29, 83}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); a_cpu.sub_(b_cpu, 2.1f); a_vulkan.sub_(b_vulkan, 2.1f); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(b_cpu, b_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, sub_broadcast0_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({16, 17, 29, 83}, at::device(at::kCPU).dtype(at::kFloat)); auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({16, 17, 29, 1}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); a_cpu.sub_(b_cpu, 2.1f); a_vulkan.sub_(b_vulkan, 2.1f); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(b_cpu, b_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, sub_broadcast1_) { if (!at::is_vulkan_available()) { return; } auto a_cpu = at::rand({3, 8, 29, 83}, at::device(at::kCPU).dtype(at::kFloat)); auto a_vulkan = a_cpu.vulkan(); const auto b_cpu = at::rand({3, 8, 1, 1}, at::device(at::kCPU).dtype(at::kFloat)); const auto b_vulkan = b_cpu.vulkan(); a_cpu.sub_(b_cpu, 2.1f); a_vulkan.sub_(b_vulkan, 2.1f); const auto check = almostEqual(a_cpu, a_vulkan.cpu()); if (!check) { showRtol(b_cpu, b_vulkan.cpu()); } ASSERT_TRUE(check); } TEST(VulkanAPITest, upsample_nearest2d) { if (!at::is_vulkan_available()) { return; } const auto in_cpu = at::rand({1, 2, 2, 3}, at::TensorOptions(at::kCPU).dtype(at::kFloat)); const auto out_cpu = at::upsample_nearest2d(in_cpu, {4, 6}); const auto in_vulkan = in_cpu.vulkan(); const auto out_vulkan = at::upsample_nearest2d(in_vulkan, {4, 6}); const auto check = almostEqual(out_cpu, out_vulkan.cpu()); if (!check) { showRtol(out_cpu, out_vulkan.cpu()); } ASSERT_TRUE(check); } enum class OpType { addmm, conv2d, hardtanh_, mean, }; class BaseOp { public: explicit BaseOp(const OpType type) : type_(type) {} virtual ~BaseOp() = default; virtual at::Tensor run(at::Tensor&) const = 0; virtual std::string toString() const = 0; private: OpType type_; }; class Addmm final : public BaseOp { public: Addmm( const int64_t m1H, const int64_t m1W, const int64_t m2W, const float beta, const float alpha) : BaseOp(OpType::addmm), m2_(at::rand(c10::IntArrayRef({m1W, m2W}), at::device(at::kCPU).dtype(at::kFloat))), b_(at::rand(c10::IntArrayRef({m1H, m2W}), at::device(at::kCPU).dtype(at::kFloat))), beta_(beta), alpha_(alpha) { } at::Tensor run(at::Tensor& t) const override { if (t.is_vulkan()) { return at::addmm(b_, t, m2_, beta_, alpha_); } return at::addmm(b_, t, m2_, beta_, alpha_); } std::string toString() const override { return "addmm"; } private: at::Tensor m2_; at::Tensor b_; float beta_; float alpha_; }; class Conv2d final : public BaseOp { public: Conv2d( const c10::IntArrayRef wsizes, const int64_t groups, const int64_t stride, const int64_t padding) : BaseOp(OpType::conv2d), groups_(groups), stride_(stride), padding_(padding), w_(at::rand(wsizes, at::device(at::kCPU).dtype(at::kFloat))), b_(at::rand(wsizes[0], at::device(at::kCPU).dtype(at::kFloat))){ } at::Tensor run(at::Tensor& t) const override { return at::conv2d(t, w_, b_, {stride_}, {padding_}, {1}, groups_); } std::string toString() const override { return "conv2d"; } private: int64_t groups_; int64_t stride_; int64_t padding_; at::Tensor w_; at::Tensor b_; }; class Hardtanh_ final : public BaseOp { public: Hardtanh_() : BaseOp(OpType::hardtanh_) {} at::Tensor run(at::Tensor& input) const override { return at::hardtanh_(input, 0, 6); } std::string toString() const override { return "hardtanh_"; } }; class Mean final : public BaseOp { public: Mean() : BaseOp(OpType::mean) {} at::Tensor run(at::Tensor& input) const override { return at::mean(input, {2, 3}, false); } std::string toString() const override { return "mean"; } }; class OpsList { public: OpsList() {} explicit OpsList(std::vector<std::unique_ptr<BaseOp>> ops) : ops_(std::move(ops)) { } auto run(const at::Tensor& input) { at::Tensor output = input; for (const auto& op : ops_) { output = op->run(output); } return output; } auto run(const at::Tensor& input, const at::Tensor& v_input) { at::Tensor output = input; at::Tensor v_output = v_input; for (const auto& op : ops_) { output = op->run(output); v_output = op->run(v_output); } return std::make_pair(output, v_output); } protected: std::vector<std::unique_ptr<BaseOp>> ops_; }; class MobileNetV2 final : public OpsList { public: MobileNetV2() { ops_.emplace_back(new Conv2d({32, 3, 3, 3}, 1, 2, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({32, 1, 3, 3}, 32, 1, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({16, 32, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({96, 16, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({96, 1, 3, 3}, 96, 2, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({24, 96, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({144, 24, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({144, 1, 3, 3}, 144, 1, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({24, 144, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({144, 24, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({144, 1, 3, 3}, 144, 2, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({32, 144, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({192, 32, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({192, 1, 3, 3}, 192, 1, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({32, 192, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({192, 32, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({192, 1, 3, 3}, 192, 1, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({32, 192, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({192, 32, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({192, 1, 3, 3}, 192, 2, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({64, 192, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({384, 64, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({384, 1, 3, 3}, 384, 1, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({64, 384, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({384, 64, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({384, 1, 3, 3}, 384, 1, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({64, 384, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({384, 64, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({384, 1, 3, 3}, 384, 1, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({64, 384, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({384, 64, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({384, 1, 3, 3}, 384, 1, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({96, 384, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({576, 96, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({576, 1, 3, 3}, 576, 1, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({96, 576, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({576, 96, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({576, 1, 3, 3}, 576, 1, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({96, 576, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({576, 96, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({576, 1, 3, 3}, 576, 2, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({160, 576, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({960, 160, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({960, 1, 3, 3}, 960, 1, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({160, 960, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({960, 160, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({960, 1, 3, 3}, 960, 1, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({160, 960, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({960, 160, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({960, 1, 3, 3}, 960, 1, 1)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Conv2d({320, 960, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Conv2d({1280, 320, 1, 1}, 1, 1, 0)); ops_.emplace_back(new Hardtanh_()); ops_.emplace_back(new Mean()); ops_.emplace_back(new Addmm(1, 1280, 1000, 0, 1)); } }; TEST(VulkanAPITest, mobilenetv2) { if (!at::is_vulkan_available()) { return; } at::AutoNonVariableTypeMode nonVarTypeModeGuard(true); MobileNetV2 mn2; const auto input = at::rand({1, 3, 224, 224}, at::device(at::kCPU).dtype(at::kFloat)); const auto output = mn2.run(input, input.vulkan()); const auto check = almostEqual(output.first, output.second.cpu()); if (!check) { showRtol(output.first, output.second.cpu()); } ASSERT_TRUE(check); } } // namespace #endif /* USE_VULKAN_API */
25.976321
101
0.63399
[ "shape", "vector" ]
33c8fac9249e7554fe7d7c9888d281a555eaba69
5,292
cxx
C++
sprokit/processes/core/convert_tracks_to_detections_process.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
sprokit/processes/core/convert_tracks_to_detections_process.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
sprokit/processes/core/convert_tracks_to_detections_process.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +29 * Copyright 2019 by Kitware, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither name of Kitware, Inc. nor the names of any 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 AUTHORS 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 "convert_tracks_to_detections_process.h" #include <vital/vital_types.h> #include <vital/types/timestamp.h> #include <vital/types/object_track_set.h> #include <kwiver_type_traits.h> #include <sprokit/processes/kwiver_type_traits.h> #include <sprokit/pipeline/process_exception.h> namespace kwiver { create_config_trait( frame_ids_only, bool, "false", "Only use frame IDs, not entire timestamps, for identifying the current frame." ); //------------------------------------------------------------------------------ // Private implementation class class convert_tracks_to_detections_process::priv { public: priv() : frame_ids_only( false ) {} ~priv() {} bool frame_ids_only; }; // ============================================================================= convert_tracks_to_detections_process ::convert_tracks_to_detections_process( vital::config_block_sptr const& config ) : process( config ), d( new convert_tracks_to_detections_process::priv ) { set_data_checking_level( check_none ); make_ports(); make_config(); } convert_tracks_to_detections_process ::~convert_tracks_to_detections_process() { } // ----------------------------------------------------------------------------- void convert_tracks_to_detections_process ::_configure() { scoped_configure_instrumentation(); vital::config_block_sptr algo_config = get_config(); d->frame_ids_only = config_value_using_trait( frame_ids_only ); process::_configure(); } // ----------------------------------------------------------------------------- void convert_tracks_to_detections_process ::_step() { // Check for complete messages auto port_info = peek_at_port_using_trait( timestamp ); if( port_info.datum->type() == sprokit::datum::complete ) { grab_edge_datum_using_trait( timestamp ); grab_edge_datum_using_trait( object_track_set ); mark_process_as_complete(); const sprokit::datum_t dat = sprokit::datum::complete_datum(); push_datum_to_port_using_trait( detected_object_set, dat ); return; } // Retrieve inputs from ports vital::timestamp ts = grab_from_port_using_trait( timestamp ); vital::object_track_set_sptr tracks = grab_from_port_using_trait( object_track_set ); // Output frame ID LOG_DEBUG( logger(), "Processing frame " << ts ); // Split track set into detections std::vector< vital::detected_object_sptr > output; for( auto trk_ptr : tracks->tracks() ) { if( trk_ptr && !trk_ptr->empty() ) { kwiver::vital::object_track_state* state = dynamic_cast< kwiver::vital::object_track_state* >( trk_ptr->back().get() ); if( state && ( ( d->frame_ids_only && state->frame() == ts.get_frame() ) || state->ts() == ts ) ) { output.push_back( state->detection() ); } } } // Output results push_to_port_using_trait( detected_object_set, std::make_shared< vital::detected_object_set >( output ) ); process::_step(); } // ----------------------------------------------------------------------------- void convert_tracks_to_detections_process ::make_ports() { // Set up for required ports sprokit::process::port_flags_t optional; sprokit::process::port_flags_t required; required.insert( flag_required ); // -- input -- declare_input_port_using_trait( timestamp, optional ); declare_input_port_using_trait( object_track_set, optional ); // -- output -- declare_output_port_using_trait( detected_object_set, optional ); } // ----------------------------------------------------------------------------- void convert_tracks_to_detections_process ::make_config() { declare_config_using_trait( frame_ids_only ); } } // end namespace
30.068182
87
0.670824
[ "vector" ]
33cb8360fb8fb90b0d94041b3845c64b0ab79988
40,757
cc
C++
content/browser/renderer_host/render_document_host_user_data_browsertest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/renderer_host/render_document_host_user_data_browsertest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/renderer_host/render_document_host_user_data_browsertest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-03-07T14:20:02.000Z
2021-03-07T14:20:02.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/public/browser/render_document_host_user_data.h" #include "base/command_line.h" #include "base/memory/weak_ptr.h" #include "base/test/bind.h" #include "base/test/scoped_feature_list.h" #include "content/browser/renderer_host/frame_tree_node.h" #include "content/browser/renderer_host/navigation_request.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/content_navigation_policy.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/site_isolation_policy.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_features.h" #include "content/public/test/back_forward_cache_util.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/navigation_handle_observer.h" #include "content/public/test/render_frame_host_test_support.h" #include "content/public/test/test_navigation_observer.h" #include "content/public/test/test_navigation_throttle.h" #include "content/public/test/test_navigation_throttle_inserter.h" #include "content/public/test/test_utils.h" #include "content/public/test/url_loader_interceptor.h" #include "content/shell/browser/shell.h" #include "content/test/content_browser_test_utils_internal.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/url_request/url_request_failed_job.h" #include "testing/gmock/include/gmock/gmock.h" namespace content { namespace { int next_id = 0; // Example class which inherits the RenderDocumentHostUserData, all the data is // associated to the lifetime of the document. class Data : public RenderDocumentHostUserData<Data> { public: ~Data() override = default; base::WeakPtr<Data> GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } int unique_id() { return unique_id_; } private: explicit Data(RenderFrameHost* render_frame_host) { unique_id_ = ++next_id; } friend class content::RenderDocumentHostUserData<Data>; int unique_id_; base::WeakPtrFactory<Data> weak_ptr_factory_{this}; RENDER_DOCUMENT_HOST_USER_DATA_KEY_DECL(); }; RENDER_DOCUMENT_HOST_USER_DATA_KEY_IMPL(Data) // Observer class to track the creation of RenderFrameHost objects. It is used // in subsequent tests. class RenderFrameHostCreatedObserver : public WebContentsObserver { public: using OnRenderFrameHostCreatedCallback = base::RepeatingCallback<void(RenderFrameHost*)>; RenderFrameHostCreatedObserver( WebContents* web_contents, OnRenderFrameHostCreatedCallback on_rfh_created) : WebContentsObserver(web_contents), on_rfh_created_(std::move(on_rfh_created)) {} void RenderFrameCreated(RenderFrameHost* render_frame_host) override { on_rfh_created_.Run(std::move(render_frame_host)); } private: OnRenderFrameHostCreatedCallback on_rfh_created_; }; // Observer class to track creation of new popups. It is used // in subsequent tests. class PopupCreatedObserver : public WebContentsDelegate { public: using WebContentsCreatedCallback = base::RepeatingCallback<void(WebContents* web_contents)>; explicit PopupCreatedObserver(WebContentsCreatedCallback callback) : callback_(std::move(callback)) {} void AddNewContents(WebContents* source_contents, std::unique_ptr<WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) override { callback_.Run(new_contents.get()); web_contents_.push_back(std::move(new_contents)); } private: WebContentsCreatedCallback callback_; std::vector<std::unique_ptr<WebContents>> web_contents_; }; } // namespace class RenderDocumentHostUserDataTest : public ContentBrowserTest { public: ~RenderDocumentHostUserDataTest() override = default; protected: void SetUpOnMainThread() override { host_resolver()->AddRule("*", "127.0.0.1"); ContentBrowserTest::SetUpOnMainThread(); } WebContentsImpl* web_contents() const { return static_cast<WebContentsImpl*>(shell()->web_contents()); } RenderFrameHostImpl* top_frame_host() { return web_contents()->GetFrameTree()->root()->current_frame_host(); } }; // Test basic functionality of RenderDocumentHostUserData. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, GetCreateAndDeleteForCurrentDocument) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); RenderFrameHostImpl* rfh_a = top_frame_host(); // 2) Get the Data associated with this RenderFrameHost. It should be null // before creation. Data* data = Data::GetForCurrentDocument(rfh_a); EXPECT_FALSE(data); // 3) Create Data and check that GetForCurrentDocument shouldn't return null // now. Data::CreateForCurrentDocument(rfh_a); base::WeakPtr<Data> created_data = Data::GetForCurrentDocument(rfh_a)->GetWeakPtr(); EXPECT_TRUE(created_data); // 4) Delete Data and check that GetForCurrentDocument should return null. Data::DeleteForCurrentDocument(rfh_a); EXPECT_FALSE(created_data); EXPECT_FALSE(Data::GetForCurrentDocument(rfh_a)); } // Test GetOrCreateForCurrentDocument API of RenderDocumentHostUserData. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, GetOrCreateForCurrentDocument) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); RenderFrameHostImpl* rfh_a = top_frame_host(); // 2) Get the Data associated with this RenderFrameHost. It should be null // before creation. Data* data = Data::GetForCurrentDocument(rfh_a); EXPECT_FALSE(data); // 3) |GetOrCreateForCurrentDocument| should create Data. base::WeakPtr<Data> created_data = Data::GetOrCreateForCurrentDocument(rfh_a)->GetWeakPtr(); EXPECT_TRUE(created_data); // 4) Another call to |GetOrCreateForCurrentDocument| should not create the // new data and the previous data created in 3) should be preserved. Data::GetOrCreateForCurrentDocument(rfh_a); EXPECT_TRUE(created_data); } // Tests that RenderDocumentHostUserData objects are different for each // RenderFrameHost in FrameTree when there are multiple frames. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, CheckForMultipleRFHsInFrameTree) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); // 1) Navigate to a(b). EXPECT_TRUE(NavigateToURL(shell(), url_a)); RenderFrameHostImpl* rfh_a = top_frame_host(); RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host(); // 2) Create RenderDocumentHostUserData associated with both RenderFrameHosts // a and b. Data::CreateForCurrentDocument(rfh_a); Data* data_a = Data::GetForCurrentDocument(rfh_a); Data::CreateForCurrentDocument(rfh_b); Data* data_b = Data::GetForCurrentDocument(rfh_b); EXPECT_TRUE(data_a); EXPECT_TRUE(data_b); // 3) Check that RDHUD objects for both RenderFrameHost a and b have different // unique_id's. EXPECT_NE(data_a->unique_id(), data_b->unique_id()); } // Tests that RenderDocumentHostUserData object is preserved when the renderer // process crashes even when RenderFrameHost still exists, but the RDHUD object // is cleared if the RenderFrameHost is reused for the new RenderFrame creation // when the previous renderer process crashes. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, CrashedFrameUserDataIsPreservedAndDeletedOnReset) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); RenderFrameHostImpl* rfh_a = top_frame_host(); // 2) Create RenderDocumentHostUserData associated with A. Data::CreateForCurrentDocument(rfh_a); base::WeakPtr<Data> data = Data::GetForCurrentDocument(rfh_a)->GetWeakPtr(); EXPECT_TRUE(data); // 3) Make the renderer crash. RenderProcessHost* renderer_process = rfh_a->GetProcess(); RenderProcessHostWatcher crash_observer( renderer_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); renderer_process->Shutdown(0); crash_observer.Wait(); // 4) RDHUD shouldn't be cleared after the renderer crash. EXPECT_FALSE(rfh_a->IsRenderFrameLive()); EXPECT_TRUE(data); // 5) Register an observer which observes created RenderFrameHost and checks // if the data is cleared when callback was run. bool did_clear_user_data = false; RenderFrameHostCreatedObserver observer( web_contents(), base::BindRepeating( [](bool* did_clear_user_data, RenderFrameHost* rfh) { if (!Data::GetForCurrentDocument(rfh)) *did_clear_user_data = true; }, &did_clear_user_data)); // 6) Re-initialize RenderFrame, now RDHUD should be cleared on new // RenderFrame creation after crash when // RenderFrameHostImpl::RenderFrameDeleted was called. FrameTreeNode* root = web_contents()->GetFrameTree()->root(); root->render_manager()->InitializeMainRenderFrameForImmediateUse(); EXPECT_TRUE(did_clear_user_data); // With RenderDocument, on a reload renderer crashes would give a new // RenderFrameHost different from rfh_a. RenderFrameHostImpl* new_rfh_a = top_frame_host(); EXPECT_TRUE(new_rfh_a->IsRenderFrameLive()); // 7) RDHUD should be cleared after initialization. EXPECT_FALSE(data); // 8) Check RDHUD object creation after new RenderFrame creation. Data::CreateForCurrentDocument(new_rfh_a); base::WeakPtr<Data> new_data = Data::GetForCurrentDocument(new_rfh_a)->GetWeakPtr(); EXPECT_TRUE(new_data); } // Tests that RenderDocumentHostUserData object is not cleared when speculative // RFH commits after the renderer hosting the current RFH (of old URL) crashes // i.e., while navigating to a new URL (using speculative RFH) and having the // current RFH (of old URL) not alive. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, CheckWithFrameCrashDuringNavigation) { // TODO(sreejakshetty): Investigate why the data is being deleted after crash // when BackForwardCache is enabled. DisableBackForwardCacheForTesting(shell()->web_contents(), BackForwardCache::TEST_ASSUMES_NO_CACHING); ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html")); // Isolate "b.com" so we are guaranteed to get a different process // for navigations to this origin on Android. Doing this ensures that a // speculative RenderFrameHost is used. IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(), {"b.com"}); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); RenderFrameHostImpl* rfh_a = top_frame_host(); // 2) Start navigation to B, but don't commit yet. TestNavigationManager manager(shell()->web_contents(), url_b); // We should disable proactive BrowsingInstance swap for the navigation below // and also use PAGE_TRANSITION_LINK for the navigation to ensure that the // speculative RFH is going to use the same BrowsingInstance as the original // RFH. Otherwise, we'd create a new speculative RFH at ReadyToCommit time, // deleting the RDHUD we created for the first speculative RFH. DisableProactiveBrowsingInstanceSwapFor(rfh_a); shell()->LoadURLForFrame(url_b, std::string(), ui::PageTransitionFromInt(ui::PAGE_TRANSITION_LINK)); EXPECT_TRUE(manager.WaitForRequestStart()); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); RenderFrameHostImpl* pending_rfh = root->render_manager()->speculative_frame_host(); NavigationRequest* navigation_request = root->navigation_request(); EXPECT_EQ(navigation_request->associated_site_instance_type(), NavigationRequest::AssociatedSiteInstanceType::SPECULATIVE); EXPECT_TRUE(pending_rfh); // 3) Get the RenderDocumentHostUserData associated with the speculative // RenderFrameHost. Data::CreateForCurrentDocument(pending_rfh); base::WeakPtr<Data> data = Data::GetForCurrentDocument(pending_rfh)->GetWeakPtr(); EXPECT_TRUE(data); // 4) Crash the renderer hosting current RFH. RenderProcessHost* renderer_process = rfh_a->GetProcess(); RenderProcessHostWatcher crash_observer( renderer_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); renderer_process->Shutdown(0); crash_observer.Wait(); // 5) Check that the RDHUD object is not cleared after renderer process // crashes. EXPECT_EQ(top_frame_host(), rfh_a); EXPECT_FALSE(pending_rfh->IsCurrent()); EXPECT_FALSE(rfh_a->IsRenderFrameLive()); EXPECT_TRUE(pending_rfh->IsRenderFrameLive()); EXPECT_TRUE(data); // 6) Let the navigation finish and make sure it has succeeded. manager.WaitForNavigationFinished(); EXPECT_EQ(url_b, web_contents()->GetMainFrame()->GetLastCommittedURL()); // 7) Data shouldn't be cleared in this case, as state // |committed_speculative_rfh_before_navigation_commit_| is true during the // check in DidCommitInternalNavigation as the speculative RFH swaps with the // crashed RFH and performs commit before navigation commit happens. EXPECT_TRUE(data); } // Tests that RenderDocumentHostUserData object is not cleared when speculative // RFH commits after renderer hosting the current RFH (of old URL) which happens // before navigating to a new URL (using Speculative RFH) and having the current // RenderFrameHost (of old URL) not alive. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, CheckWithFrameCrashBeforeNavigation) { if (ShouldSkipEarlyCommitPendingForCrashedFrame()) return; ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html")); // Isolate "b.com" so we are guaranteed to get a different process // for navigations to this origin on Android. Doing this ensures that a // speculative RenderFrameHost is used. IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(), {"b.com"}); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); RenderFrameHostImpl* rfh_a = top_frame_host(); // 2) Crash the renderer hosting current RFH. RenderProcessHost* renderer_process = rfh_a->GetProcess(); RenderProcessHostWatcher crash_observer( renderer_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); renderer_process->Shutdown(0); crash_observer.Wait(); // 3) Start navigation to B, but don't commit yet. TestNavigationManager manager(shell()->web_contents(), url_b); shell()->LoadURL(url_b); EXPECT_TRUE(manager.WaitForRequestStart()); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Speculative RenderFrameHost for B will commit early because current rfh_a // is not alive after the crash in step (2). RenderFrameHostImpl* current_rfh = root->render_manager()->current_frame_host(); NavigationRequest* navigation_request = root->navigation_request(); EXPECT_EQ(navigation_request->associated_site_instance_type(), NavigationRequest::AssociatedSiteInstanceType::CURRENT); EXPECT_TRUE(current_rfh); EXPECT_TRUE(current_rfh->IsCurrent()); // 4) Get the RenderDocumentHostUserData associated with speculative // RenderFrameHost. Data::CreateForCurrentDocument(current_rfh); base::WeakPtr<Data> data = Data::GetForCurrentDocument(current_rfh)->GetWeakPtr(); EXPECT_TRUE(data); // 5) Let the navigation finish and make sure it has succeeded. manager.WaitForNavigationFinished(); EXPECT_EQ(url_b, web_contents()->GetMainFrame()->GetLastCommittedURL()); // 6) Data shouldn't be cleared in this case, as state // |committed_speculative_rfh_before_navigation_commit_| is true during the // check in DidCommitInternalNavigation as the speculative RFH swaps with the // crashed RFH and performs commit before navigation commit happens. EXPECT_TRUE(data); } // Tests that RenderDocumentHostUserData object is created for speculative // RenderFrameHost and check if they point to same object before and after // commit. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, CheckIDsForSpeculativeRFHBeforeAndAfterCommit) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html")); // Isolate "b.com" so we are guaranteed to get a different process // for navigations to this origin on Android. Doing this ensures that a // speculative RenderFrameHost is used. IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(), {"b.com"}); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); // 2) Start navigation to B, but don't commit yet. TestNavigationManager manager(shell()->web_contents(), url_b); shell()->LoadURL(url_b); EXPECT_TRUE(manager.WaitForRequestStart()); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); RenderFrameHostImpl* pending_rfh = root->render_manager()->speculative_frame_host(); NavigationRequest* navigation_request = root->navigation_request(); EXPECT_EQ(navigation_request->associated_site_instance_type(), NavigationRequest::AssociatedSiteInstanceType::SPECULATIVE); EXPECT_TRUE(pending_rfh); // 3) While there is a speculative RenderFrameHost in the root FrameTreeNode, // get the Data associated with this RenderFrameHost. Data::CreateForCurrentDocument(pending_rfh); Data* data_before_commit = Data::GetForCurrentDocument(pending_rfh); EXPECT_TRUE(data_before_commit); // 4) Let the navigation finish and make sure it is succeeded. manager.WaitForNavigationFinished(); EXPECT_EQ(url_b, web_contents()->GetMainFrame()->GetLastCommittedURL()); RenderFrameHostImpl* rfh_b = top_frame_host(); EXPECT_EQ(pending_rfh, rfh_b); Data* data_after_commit = Data::GetForCurrentDocument(rfh_b); EXPECT_TRUE(data_after_commit); // 5) Check |data_before_commit| and |data_after_commit| have same ID. EXPECT_EQ(data_before_commit->unique_id(), data_after_commit->unique_id()); } // Tests that RenderDocumentHostUserData object is deleted when the speculative // RenderFrameHost gets deleted before being able to commit. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, SpeculativeRFHDeleted) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); GURL url_c(embedded_test_server()->GetURL("c.com", "/hung")); IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess()); // 1) Initial state: A(B). EXPECT_TRUE(NavigateToURL(shell(), url_a)); RenderFrameHostImpl* rfh_a = web_contents()->GetMainFrame(); RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host(); // Leave rfh_b in pending deletion state. LeaveInPendingDeletionState(rfh_b); // 2) Navigation from B to C. The server is slow to respond. TestNavigationManager navigation_observer(web_contents(), url_c); EXPECT_TRUE(ExecJs(rfh_b, JsReplace("location.href=$1;", url_c))); EXPECT_TRUE(navigation_observer.WaitForRequestStart()); RenderFrameHostImpl* pending_rfh_c = rfh_b->frame_tree_node()->render_manager()->speculative_frame_host(); // 3) While there is a speculative RenderFrameHost get the Data associated // with it. Data::CreateForCurrentDocument(pending_rfh_c); base::WeakPtr<Data> data = Data::GetForCurrentDocument(pending_rfh_c)->GetWeakPtr(); EXPECT_TRUE(data); // 4) Delete the speculative RenderFrameHost by navigating from a // RenderFrameHost in pending deletion. RenderFrameDeletedObserver delete_speculative_c(pending_rfh_c); EXPECT_TRUE( ExecJs(rfh_a, JsReplace("document.querySelector('iframe').remove();"))); delete_speculative_c.WaitUntilDeleted(); EXPECT_TRUE(delete_speculative_c.deleted()); // 5) Once the speculative RenderFrameHost is deleted, the associated // RenderDocumentHostUserData should be deleted. EXPECT_FALSE(data); } // Tests that RenderDocumentHostUserData is cleared when the RenderFrameHost is // deleted. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, RenderFrameHostDeleted) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); // 1) Navigate to a(b). EXPECT_TRUE(NavigateToURL(shell(), url_a)); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); RenderFrameHostImpl* rfh_a = top_frame_host(); RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host(); RenderFrameDeletedObserver delete_observer_rfh_b(rfh_b); // 2) Get the Data associated with the rfh_b and check the data gets cleared // on RenderFrameHost deletion. Data::CreateForCurrentDocument(rfh_b); base::WeakPtr<Data> data = Data::GetForCurrentDocument(rfh_b)->GetWeakPtr(); EXPECT_TRUE(data); // 3) Detach the child frame. EXPECT_TRUE(ExecJs(root, "document.querySelector('iframe').remove()")); // 4) Once the RenderFrameHost is deleted, the associated // RenderDocumentHostUserData should be deleted. delete_observer_rfh_b.WaitUntilDeleted(); EXPECT_FALSE(data); } // Tests that RenderDocumentHostUserData object is not cleared when the // RenderFrameHost is in pending deletion state for both main frame and sub // frame. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, CheckInPendingDeletionState) { ASSERT_TRUE(embedded_test_server()->Start()); IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess()); GURL url_ab(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); GURL url_c(embedded_test_server()->GetURL("c.com", "/title1.html")); // 1) Navigate to A(B). EXPECT_TRUE(NavigateToURL(shell(), url_ab)); RenderFrameHostImpl* rfh_a = top_frame_host(); RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host(); // Test needs these RenderFrameHosts to be pending deletion after navigating // but it doesn't happen with BackForwardCache as it is stored in cache. // BFCache case is covered explicitly by // "RenderDocumentHostUserDataWithBackForwardCacheTest. // BackForwardCacheNavigation" test. DisableBackForwardCacheForTesting(shell()->web_contents(), BackForwardCache::TEST_ASSUMES_NO_CACHING); // 2) Leave both rfh_a and rfh_b in pending deletion state. LeaveInPendingDeletionState(rfh_a); LeaveInPendingDeletionState(rfh_b); // 3) Create RDHUD object for both rfh_a and rfh_b before running unload // handlers. Data::CreateForCurrentDocument(rfh_a); Data::CreateForCurrentDocument(rfh_b); base::WeakPtr<Data> data_a = Data::GetForCurrentDocument(rfh_a)->GetWeakPtr(); base::WeakPtr<Data> data_b = Data::GetForCurrentDocument(rfh_b)->GetWeakPtr(); EXPECT_TRUE(data_a); EXPECT_TRUE(data_b); // 4) Navigate from A(B) to C. EXPECT_TRUE(NavigateToURL(shell(), url_c)); // 5) Check RDHUD objects |data_a| and |data_b| are not cleared when rfh_a and // rfh_b are in pending deletion state. EXPECT_EQ(rfh_a->lifecycle_state(), RenderFrameHostImpl::LifecycleState::kRunningUnloadHandlers); EXPECT_EQ(rfh_b->lifecycle_state(), RenderFrameHostImpl::LifecycleState::kRunningUnloadHandlers); EXPECT_TRUE(data_a); EXPECT_TRUE(data_b); EXPECT_FALSE(rfh_a->IsCurrent()); EXPECT_FALSE(rfh_b->IsCurrent()); } // Tests that RenderDocumentHostUserData associated with RenderFrameHost is not // cleared on same document navigation. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, CommitSameDocumentNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL url_a2(embedded_test_server()->GetURL("a.com", "/title1.html#2")); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); RenderFrameHostImpl* rfh_a = top_frame_host(); // 2) Get the Data associated with this RenderFrameHost. Data::CreateForCurrentDocument(rfh_a); Data* data = Data::GetForCurrentDocument(rfh_a); EXPECT_TRUE(data); // 3) Navigate to A#2 (same document navigation). EXPECT_TRUE(ExecJs(shell(), JsReplace("location = $1", url_a2.spec()))); EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); EXPECT_EQ(url_a2, web_contents()->GetMainFrame()->GetLastCommittedURL()); // 4) Check if the RDHUD objects are pointing to the same instance after // navigation. Data* data2 = Data::GetForCurrentDocument(rfh_a); EXPECT_TRUE(data2); EXPECT_EQ(data->unique_id(), data2->unique_id()); } // Tests that RenderDocumentHostUserData object is not cleared when navigation // is cancelled. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, CancelledNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); RenderFrameHostImpl* rfh_a = top_frame_host(); // 2) Get the Data associated with this RenderFrameHost. Data::CreateForCurrentDocument(rfh_a); Data* data = Data::GetForCurrentDocument(rfh_a); EXPECT_TRUE(data); // 3) Cancel all navigation attempts. TestNavigationThrottleInserter throttle_inserter( shell()->web_contents(), base::BindLambdaForTesting( [&](NavigationHandle* handle) -> std::unique_ptr<NavigationThrottle> { auto throttle = std::make_unique<TestNavigationThrottle>(handle); throttle->SetResponse(TestNavigationThrottle::WILL_START_REQUEST, TestNavigationThrottle::SYNCHRONOUS, NavigationThrottle::CANCEL_AND_IGNORE); return throttle; })); // 4) Try navigating to B. EXPECT_FALSE(NavigateToURL(shell(), url_b)); // 5) We should still be showing page A. EXPECT_EQ(rfh_a, top_frame_host()); // 6) The data shouldn't be cleared in the case of cancelled navigations and // should be pointing to the same instances. Data* data2 = Data::GetForCurrentDocument(rfh_a); EXPECT_TRUE(data2); EXPECT_EQ(data->unique_id(), data2->unique_id()); } // Tests that RenderDocumentHostUserData object is cleared when a failed // navigation results in an error page. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, FailedNavigation) { // This test is only valid if error page isolation is enabled. if (!SiteIsolationPolicy::IsErrorPageIsolationEnabled(true)) return; ASSERT_TRUE(embedded_test_server()->Start()); GURL url(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL error_url(embedded_test_server()->GetURL("/close-socket")); std::unique_ptr<URLLoaderInterceptor> url_interceptor = URLLoaderInterceptor::SetupRequestFailForURL(error_url, net::ERR_DNS_TIMED_OUT); // 1) Start with a successful navigation to a document. EXPECT_TRUE(NavigateToURL(shell(), url)); RenderFrameHostImpl* rfh_a = top_frame_host(); RenderFrameDeletedObserver delete_observer_rfh_a(rfh_a); // 2) Get the Data associated with RenderFrameHost associated with url. Data::CreateForCurrentDocument(rfh_a); base::WeakPtr<Data> data = Data::GetForCurrentDocument(rfh_a)->GetWeakPtr(); EXPECT_TRUE(data); // This test expects old RenderFrameHost to be deleted after navigating to an // error page, disable back-forward cache to ensure that RenderFrameHost gets // deleted. DisableBackForwardCacheForTesting(shell()->web_contents(), BackForwardCache::TEST_ASSUMES_NO_CACHING); // 3) Browser-initiated navigation to an error page. NavigationHandleObserver observer(shell()->web_contents(), error_url); EXPECT_FALSE(NavigateToURL(shell(), error_url)); EXPECT_TRUE(observer.is_error()); EXPECT_EQ(net::ERR_DNS_TIMED_OUT, observer.net_error_code()); // 4) The associated RenderDocumentHostUserData object should be deleted. delete_observer_rfh_a.WaitUntilDeleted(); EXPECT_FALSE(data); } // Tests that RenderDocumentHostUserData object is cleared when it is neither a // same document navigation nor when it is stored in back-forward cache after // navigating away. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, CrossSiteNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); RenderFrameHostImpl* rfh_a = top_frame_host(); RenderFrameDeletedObserver delete_observer_rfh_a(rfh_a); // 2) Get the Data associated with this RenderFrameHost. Data::CreateForCurrentDocument(rfh_a); base::WeakPtr<Data> data = Data::GetForCurrentDocument(rfh_a)->GetWeakPtr(); EXPECT_TRUE(data); DisableBackForwardCacheForTesting(shell()->web_contents(), BackForwardCache::TEST_ASSUMES_NO_CACHING); // 3) Navigate to B. EXPECT_TRUE(NavigateToURL(shell(), url_b)); EXPECT_NE(rfh_a, top_frame_host()); // 4) Both rfh_a and RDHUD should be deleted. delete_observer_rfh_a.WaitUntilDeleted(); EXPECT_FALSE(data); } // Tests that RenderDocumentHostUserData object is cleared on performing same // site navigation. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, SameSiteNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a1(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL url_a2(embedded_test_server()->GetURL("a.com", "/title2.html")); // 1) Navigate to A1. EXPECT_TRUE(NavigateToURL(shell(), url_a1)); RenderFrameHostImpl* rfh_a1 = top_frame_host(); // 2) Get the Data associated with this RenderFrameHost. Data::CreateForCurrentDocument(rfh_a1); base::WeakPtr<Data> data = Data::GetForCurrentDocument(rfh_a1)->GetWeakPtr(); EXPECT_TRUE(data); // 3) Navigate to A2. EXPECT_TRUE(NavigateToURL(shell(), url_a2)); // 4) The associated RenderDocumentHostUserData should be deleted. EXPECT_FALSE(data); } // This test ensures that the data created during the new WebContents // initialisation is not lost during the initial "navigation" triggered by the // window.open. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, WindowOpen) { ASSERT_TRUE(embedded_test_server()->Start()); int popup_data_id = -1; WebContents* new_tab = nullptr; // 1) Navigate to A. GURL url(embedded_test_server()->GetURL("a.com", "/title1.html")); EXPECT_TRUE(NavigateToURL(shell(), url)); // 2) Register WebContentsDelegate to get notified about new popups. PopupCreatedObserver observer(base::BindRepeating( [](int* popup_data_id, WebContents** new_tab, WebContents* web_contents) { EXPECT_EQ(*popup_data_id, -1); EXPECT_FALSE(*new_tab); *new_tab = web_contents; *popup_data_id = Data::GetOrCreateForCurrentDocument(web_contents->GetMainFrame()) ->unique_id(); }, &popup_data_id, &new_tab)); web_contents()->SetDelegate(&observer); // 3) Invoke a window.open() without parameters. The delegate should capture // the ownership of the new WebContents and attach Data to its main frame. EXPECT_TRUE(ExecJs(top_frame_host(), "window.open()")); EXPECT_TRUE(new_tab); // Do not check for the success status because we haven't committed a // navigation yet, which causes checks to fail. WaitForLoadStopWithoutSuccessCheck(new_tab); // 4) Expect the data to the preserved (it might have been deleted due to us // having a fake initial navigation for blank window.open). Data* new_tab_data = Data::GetForCurrentDocument(new_tab->GetMainFrame()); EXPECT_TRUE(new_tab_data); EXPECT_EQ(new_tab_data->unique_id(), popup_data_id); web_contents()->SetDelegate(nullptr); } IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, BlankIframe) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL url_b( embedded_test_server()->GetURL("b.com", "/page_with_blank_iframe.html")); // 0) Navigate to A to ensure that we have a live frame (see a comment in // AttachOnCreatingInitialFrame). EXPECT_TRUE(NavigateToURL(shell(), url_a)); int starting_id = next_id + 1; std::vector<RenderFrameHost*> created_rfhs; // 1) Register an observer which observes all created RenderFrameHosts // and attaches user data to them. RenderFrameHostCreatedObserver observer( web_contents(), base::BindRepeating( [](std::vector<RenderFrameHost*>* created_rfhs, RenderFrameHost* rfh) { created_rfhs->push_back(rfh); Data::GetOrCreateForCurrentDocument(rfh); }, &created_rfhs)); // 2) Navigate to a page with a blank iframe. EXPECT_TRUE(NavigateToURL(shell(), url_b)); // 3) Expect that we have two frames with valid user data. // The danger here lies in the perculiar properties of the initial navigation // for the blank iframes, which does not create a new document, but goes via // DidCommitProvisionalLoad. std::vector<int> current_ids; for (RenderFrameHost* rfh : created_rfhs) { if (auto* data = Data::GetForCurrentDocument(rfh)) { current_ids.push_back(data->unique_id()); } } EXPECT_EQ(2u, created_rfhs.size()); EXPECT_THAT(current_ids, testing::ElementsAre(starting_id, starting_id + 1)); } IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, SrcDocIframe) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL url_b(embedded_test_server()->GetURL( "b.com", "/frame_tree/page_with_srcdoc_frame.html")); // 0) Navigate to A to ensure that we have a live frame (see a comment in // AttachOnCreatingInitialFrame). EXPECT_TRUE(NavigateToURL(shell(), url_a)); int starting_id = next_id + 1; std::vector<RenderFrameHost*> created_rfhs; // 1) Register an observer which observes all created RenderFrameHosts // and attaches user data to them. RenderFrameHostCreatedObserver observer( web_contents(), base::BindRepeating( [](std::vector<RenderFrameHost*>* created_rfhs, RenderFrameHost* rfh) { created_rfhs->push_back(rfh); Data::GetOrCreateForCurrentDocument(rfh); }, &created_rfhs)); // 2) Navigate to a page with a srcdoc iframe. EXPECT_TRUE(NavigateToURL(shell(), url_b)); // 3) Expect that we have one frame with valid user data. // For the subframe, the user data was attached to the initial blank document // and should have been deleted when the document was navigated to // about:srcdoc. std::vector<int> current_ids; for (RenderFrameHost* rfh : created_rfhs) { if (auto* data = Data::GetForCurrentDocument(rfh)) { current_ids.push_back(data->unique_id()); } } EXPECT_EQ(2u, created_rfhs.size()); EXPECT_THAT(current_ids, testing::ElementsAre(starting_id)); } // This test doesn't actually work at the moment and documents the current // behaviour rather than intended one. // TODO(sreejakshetty): Fix it. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataTest, AttachOnCreatingInitialFrame) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url(embedded_test_server()->GetURL("a.com", "/title1.html")); bool observed_frame_creation = false; // 1) Register an observer which observes all created RenderFrameHosts // and attaches user data to them. RenderFrameHostCreatedObserver observer( web_contents(), base::BindRepeating( [](bool* observed_frame_creation, RenderFrameHost* rfh) { Data::GetOrCreateForCurrentDocument(rfh); *observed_frame_creation = true; }, &observed_frame_creation)); // 2) Navigate to a new page. EXPECT_FALSE(shell()->web_contents()->GetMainFrame()->IsRenderFrameLive()); EXPECT_TRUE(NavigateToURL(shell(), url)); // 3) Unfortunately, user data will not be there – the reason is that we // actually reuse the initial RenderFrameHost, which wasn't fully initialised // when we started a navigation (IsRenderFrameLive == false). It will complete // its initialisation, dispatching RenderFrameCreated, but during the // navigation commit we will consider the document in it to be reset later // when we commit the navigation. In the short term, we should not reset RDHUD // in that case. In the long term, we probably should create a new // RenderFrameHost here. EXPECT_TRUE(observed_frame_creation); EXPECT_FALSE( Data::GetForCurrentDocument(shell()->web_contents()->GetMainFrame())); } // Test RenderDocumentHostUserData with BackForwardCache feature enabled. class RenderDocumentHostUserDataWithBackForwardCacheTest : public RenderDocumentHostUserDataTest { public: RenderDocumentHostUserDataWithBackForwardCacheTest() { scoped_feature_list_.InitWithFeaturesAndParameters( {{features::kBackForwardCache, // Set a very long TTL before expiration (longer than the test // timeout) so tests that are expecting deletion don't pass when // they shouldn't. {{"TimeToLiveInBackForwardCacheInSeconds", "3600"}}}}, // Allow BackForwardCache for all devices regardless of their memory. {features::kBackForwardCacheMemoryControls}); } private: base::test::ScopedFeatureList scoped_feature_list_; }; // Tests that RenderDocumentHostUserData object is not cleared on storing and // restoring a page from back-forward cache. IN_PROC_BROWSER_TEST_F(RenderDocumentHostUserDataWithBackForwardCacheTest, BackForwardCacheNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html")); // 1) Navigate to A. EXPECT_TRUE(NavigateToURL(shell(), url_a)); RenderFrameHostImpl* rfh_a = top_frame_host(); // 2) Get the Data associated with this RenderFrameHost. Data::CreateForCurrentDocument(rfh_a); Data* data = Data::GetForCurrentDocument(rfh_a); EXPECT_TRUE(data); // 3) Navigate to B. A should be stored in back-forward cache. EXPECT_TRUE(NavigateToURL(shell(), url_b)); EXPECT_TRUE(rfh_a->IsInBackForwardCache()); // 4) Data associated with document shouldn't have been cleared on navigating // away with BackForwardCache. data = Data::GetForCurrentDocument(rfh_a); EXPECT_TRUE(data); // 5) Go back to A. web_contents()->GetController().GoBack(); EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); Data* data_after_restore = Data::GetForCurrentDocument(web_contents()->GetMainFrame()); EXPECT_TRUE(data); // 6) Both the instances of Data before and after restore should point to the // same object and make sure they aren't null. EXPECT_EQ(data_after_restore->unique_id(), data->unique_id()); } } // namespace content
40.961809
80
0.73607
[ "object", "vector" ]
33cbdd1464e788527f6a7801db6c38ae4bac7956
31,290
cc
C++
cartographer/cloud/internal/client_server_test.cc
SilvereGit/cartographer
0c794b3b264074a420069bf003e027348b0561c3
[ "Apache-2.0" ]
null
null
null
cartographer/cloud/internal/client_server_test.cc
SilvereGit/cartographer
0c794b3b264074a420069bf003e027348b0561c3
[ "Apache-2.0" ]
null
null
null
cartographer/cloud/internal/client_server_test.cc
SilvereGit/cartographer
0c794b3b264074a420069bf003e027348b0561c3
[ "Apache-2.0" ]
2
2018-02-01T12:06:44.000Z
2018-08-20T08:57:45.000Z
/* * Copyright 2017 The Cartographer Authors * * 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 <condition_variable> #include <mutex> #include "cartographer/cloud/client/map_builder_stub.h" #include "cartographer/cloud/internal/map_builder_server.h" #include "cartographer/cloud/map_builder_server_options.h" #include "cartographer/io/internal/in_memory_proto_stream.h" #include "cartographer/io/proto_stream.h" #include "cartographer/io/proto_stream_deserializer.h" #include "cartographer/io/testing/test_helpers.h" #include "cartographer/mapping/internal/testing/mock_map_builder.h" #include "cartographer/mapping/internal/testing/mock_pose_graph.h" #include "cartographer/mapping/internal/testing/mock_trajectory_builder.h" #include "cartographer/mapping/internal/testing/test_helpers.h" #include "cartographer/mapping/local_slam_result_data.h" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using ::cartographer::io::testing::ProtoReaderFromStrings; using ::cartographer::mapping::MapBuilder; using ::cartographer::mapping::MapBuilderInterface; using ::cartographer::mapping::PoseGraphInterface; using ::cartographer::mapping::TrajectoryBuilderInterface; using ::cartographer::mapping::testing::MockMapBuilder; using ::cartographer::mapping::testing::MockPoseGraph; using ::cartographer::mapping::testing::MockTrajectoryBuilder; using ::testing::_; using SensorId = ::cartographer::mapping::TrajectoryBuilderInterface::SensorId; namespace cartographer { namespace cloud { namespace { constexpr char kClientId[] = "CLIENT_ID"; const SensorId kImuSensorId{SensorId::SensorType::IMU, "imu"}; const SensorId kRangeSensorId{SensorId::SensorType::RANGE, "range"}; constexpr double kDuration = 4.; // Seconds. constexpr double kTimeStep = 0.1; // Seconds. constexpr double kTravelDistance = 1.2; // Meters. constexpr char kSerializationHeaderProtoString[] = "format_version: 1"; constexpr char kPoseGraphProtoString[] = R"(pose_graph { trajectory: { trajectory_id: 0 node: {} submap: {} } })"; constexpr char kAllTrajectoryBuilderOptionsProtoString[] = R"(all_trajectory_builder_options { options_with_sensor_ids: {} })"; constexpr char kSubmapProtoString[] = "submap {}"; constexpr char kNodeProtoString[] = "node {}"; constexpr char kTrajectoryDataProtoString[] = "trajectory_data {}"; constexpr char kImuDataProtoString[] = "imu_data {}"; constexpr char kOdometryDataProtoString[] = "odometry_data {}"; constexpr char kFixedFramePoseDataProtoString[] = "fixed_frame_pose_data {}"; constexpr char kLandmarkDataProtoString[] = "landmark_data {}"; template <class T> class ClientServerTestBase : public T { protected: void SetUp() override { // TODO(cschuet): Due to the hard-coded addresses these tests will become // flaky when run in parallel. const std::string kMapBuilderServerLua = R"text( include "map_builder_server.lua" MAP_BUILDER.use_trajectory_builder_2d = true MAP_BUILDER.pose_graph.optimize_every_n_nodes = 0 MAP_BUILDER_SERVER.num_event_threads = 1 MAP_BUILDER_SERVER.num_grpc_threads = 1 MAP_BUILDER_SERVER.uplink_server_address = "" MAP_BUILDER_SERVER.server_address = "0.0.0.0:50051" return MAP_BUILDER_SERVER)text"; auto map_builder_server_parameters = mapping::testing::ResolveLuaParameters(kMapBuilderServerLua); map_builder_server_options_ = CreateMapBuilderServerOptions(map_builder_server_parameters.get()); const std::string kUploadingMapBuilderServerLua = R"text( include "map_builder_server.lua" MAP_BUILDER.use_trajectory_builder_2d = true MAP_BUILDER.pose_graph.optimize_every_n_nodes = 0 MAP_BUILDER_SERVER.num_event_threads = 1 MAP_BUILDER_SERVER.num_grpc_threads = 1 MAP_BUILDER_SERVER.uplink_server_address = "localhost:50051" MAP_BUILDER_SERVER.server_address = "0.0.0.0:50052" MAP_BUILDER_SERVER.upload_batch_size = 1 return MAP_BUILDER_SERVER)text"; auto uploading_map_builder_server_parameters = mapping::testing::ResolveLuaParameters(kUploadingMapBuilderServerLua); uploading_map_builder_server_options_ = CreateMapBuilderServerOptions( uploading_map_builder_server_parameters.get()); EXPECT_NE(map_builder_server_options_.server_address(), uploading_map_builder_server_options_.server_address()); const std::string kTrajectoryBuilderLua = R"text( include "trajectory_builder.lua" TRAJECTORY_BUILDER.trajectory_builder_2d.use_imu_data = false TRAJECTORY_BUILDER.trajectory_builder_2d.submaps.num_range_data = 4 return TRAJECTORY_BUILDER)text"; auto trajectory_builder_parameters = mapping::testing::ResolveLuaParameters(kTrajectoryBuilderLua); trajectory_builder_options_ = mapping::CreateTrajectoryBuilderOptions( trajectory_builder_parameters.get()); number_of_insertion_results_ = 0; local_slam_result_callback_ = [this](int, common::Time, transform::Rigid3d local_pose, sensor::RangeData, std::unique_ptr< const mapping::TrajectoryBuilderInterface::InsertionResult> insertion_result) { std::unique_lock<std::mutex> lock(local_slam_result_mutex_); if (insertion_result) { ++number_of_insertion_results_; } local_slam_result_poses_.push_back(local_pose); lock.unlock(); local_slam_result_condition_.notify_all(); }; } void InitializeRealServer() { auto map_builder = absl::make_unique<MapBuilder>( map_builder_server_options_.map_builder_options()); server_ = absl::make_unique<MapBuilderServer>(map_builder_server_options_, std::move(map_builder)); EXPECT_TRUE(server_ != nullptr); } void InitializeRealUploadingServer() { auto map_builder = absl::make_unique<MapBuilder>( uploading_map_builder_server_options_.map_builder_options()); uploading_server_ = absl::make_unique<MapBuilderServer>( uploading_map_builder_server_options_, std::move(map_builder)); EXPECT_TRUE(uploading_server_ != nullptr); } void InitializeServerWithMockMapBuilder() { auto mock_map_builder = absl::make_unique<MockMapBuilder>(); mock_map_builder_ = mock_map_builder.get(); mock_pose_graph_ = absl::make_unique<MockPoseGraph>(); EXPECT_CALL(*mock_map_builder_, pose_graph()) .WillOnce(::testing::Return(mock_pose_graph_.get())); EXPECT_CALL(*mock_pose_graph_, SetGlobalSlamOptimizationCallback(_)); server_ = absl::make_unique<MapBuilderServer>(map_builder_server_options_, std::move(mock_map_builder)); EXPECT_TRUE(server_ != nullptr); mock_trajectory_builder_ = absl::make_unique<MockTrajectoryBuilder>(); } void InitializeStub() { stub_ = absl::make_unique<MapBuilderStub>( map_builder_server_options_.server_address(), kClientId); EXPECT_TRUE(stub_ != nullptr); } void InitializeStubForUploadingServer() { stub_for_uploading_server_ = absl::make_unique<MapBuilderStub>( uploading_map_builder_server_options_.server_address(), kClientId); EXPECT_TRUE(stub_for_uploading_server_ != nullptr); } void SetOptionsToTSDF2D() { trajectory_builder_options_.mutable_trajectory_builder_2d_options() ->mutable_submaps_options() ->mutable_range_data_inserter_options() ->set_range_data_inserter_type( ::cartographer::mapping::proto::RangeDataInserterOptions:: TSDF_INSERTER_2D); trajectory_builder_options_.mutable_trajectory_builder_2d_options() ->mutable_submaps_options() ->mutable_grid_options_2d() ->set_grid_type(::cartographer::mapping::proto::GridOptions2D::TSDF); trajectory_builder_options_.mutable_trajectory_builder_2d_options() ->mutable_ceres_scan_matcher_options() ->set_occupied_space_weight(10.0); map_builder_server_options_.mutable_map_builder_options() ->mutable_pose_graph_options() ->mutable_constraint_builder_options() ->mutable_ceres_scan_matcher_options() ->set_occupied_space_weight(50.0); uploading_map_builder_server_options_.mutable_map_builder_options() ->mutable_pose_graph_options() ->mutable_constraint_builder_options() ->mutable_ceres_scan_matcher_options() ->set_occupied_space_weight(50.0); } void WaitForLocalSlamResults(size_t size) { std::unique_lock<std::mutex> lock(local_slam_result_mutex_); local_slam_result_condition_.wait( lock, [&] { return local_slam_result_poses_.size() >= size; }); } void WaitForLocalSlamResultUploads(size_t size) { while (stub_->pose_graph()->GetTrajectoryNodePoses().size() < size) { LOG(INFO) << stub_->pose_graph()->GetTrajectoryNodePoses().size(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } proto::MapBuilderServerOptions map_builder_server_options_; proto::MapBuilderServerOptions uploading_map_builder_server_options_; MockMapBuilder* mock_map_builder_; std::unique_ptr<MockPoseGraph> mock_pose_graph_; std::unique_ptr<MockTrajectoryBuilder> mock_trajectory_builder_; ::cartographer::mapping::proto::TrajectoryBuilderOptions trajectory_builder_options_; std::unique_ptr<MapBuilderServer> server_; std::unique_ptr<MapBuilderServer> uploading_server_; std::unique_ptr<MapBuilderStub> stub_; std::unique_ptr<MapBuilderStub> stub_for_uploading_server_; TrajectoryBuilderInterface::LocalSlamResultCallback local_slam_result_callback_; std::condition_variable local_slam_result_condition_; std::condition_variable local_slam_result_upload_condition_; std::mutex local_slam_result_mutex_; std::mutex local_slam_result_upload_mutex_; std::vector<transform::Rigid3d> local_slam_result_poses_; int number_of_insertion_results_; }; class ClientServerTest : public ClientServerTestBase<::testing::Test> {}; class ClientServerTestByGridType : public ClientServerTestBase< ::testing::TestWithParam<::cartographer::mapping::GridType>> {}; INSTANTIATE_TEST_CASE_P( ClientServerTestByGridType, ClientServerTestByGridType, ::testing::Values(::cartographer::mapping::GridType::PROBABILITY_GRID, ::cartographer::mapping::GridType::TSDF)); TEST_F(ClientServerTest, StartAndStopServer) { InitializeRealServer(); server_->Start(); server_->Shutdown(); } TEST_P(ClientServerTestByGridType, AddTrajectoryBuilder) { if (GetParam() == ::cartographer::mapping::GridType::TSDF) { SetOptionsToTSDF2D(); } InitializeRealServer(); server_->Start(); InitializeStub(); int trajectory_id = stub_->AddTrajectoryBuilder( {kImuSensorId}, trajectory_builder_options_, nullptr); EXPECT_FALSE(stub_->pose_graph()->IsTrajectoryFinished(trajectory_id)); stub_->FinishTrajectory(trajectory_id); EXPECT_TRUE(stub_->pose_graph()->IsTrajectoryFinished(trajectory_id)); EXPECT_FALSE(stub_->pose_graph()->IsTrajectoryFrozen(trajectory_id)); server_->Shutdown(); } TEST_P(ClientServerTestByGridType, AddTrajectoryBuilderWithMock) { if (GetParam() == ::cartographer::mapping::GridType::TSDF) { SetOptionsToTSDF2D(); } InitializeServerWithMockMapBuilder(); server_->Start(); InitializeStub(); std::set<SensorId> expected_sensor_ids = {kImuSensorId}; EXPECT_CALL( *mock_map_builder_, AddTrajectoryBuilder(::testing::ContainerEq(expected_sensor_ids), _, _)) .WillOnce(::testing::Return(3)); EXPECT_CALL(*mock_map_builder_, GetTrajectoryBuilder(_)) .WillRepeatedly(::testing::Return(nullptr)); int trajectory_id = stub_->AddTrajectoryBuilder( expected_sensor_ids, trajectory_builder_options_, nullptr); EXPECT_EQ(trajectory_id, 3); EXPECT_CALL(*mock_map_builder_, FinishTrajectory(trajectory_id)); stub_->FinishTrajectory(trajectory_id); server_->Shutdown(); } TEST_P(ClientServerTestByGridType, AddSensorData) { if (GetParam() == ::cartographer::mapping::GridType::TSDF) { SetOptionsToTSDF2D(); } trajectory_builder_options_.mutable_trajectory_builder_2d_options() ->set_use_imu_data(true); InitializeRealServer(); server_->Start(); InitializeStub(); int trajectory_id = stub_->AddTrajectoryBuilder( {kImuSensorId}, trajectory_builder_options_, nullptr); TrajectoryBuilderInterface* trajectory_stub = stub_->GetTrajectoryBuilder(trajectory_id); sensor::ImuData imu_data{common::FromUniversal(42), Eigen::Vector3d(0., 0., 9.8), Eigen::Vector3d::Zero()}; trajectory_stub->AddSensorData(kImuSensorId.id, imu_data); stub_->FinishTrajectory(trajectory_id); server_->Shutdown(); } TEST_P(ClientServerTestByGridType, AddSensorDataWithMock) { if (GetParam() == ::cartographer::mapping::GridType::TSDF) { SetOptionsToTSDF2D(); } InitializeServerWithMockMapBuilder(); server_->Start(); InitializeStub(); std::set<SensorId> expected_sensor_ids = {kImuSensorId}; EXPECT_CALL( *mock_map_builder_, AddTrajectoryBuilder(::testing::ContainerEq(expected_sensor_ids), _, _)) .WillOnce(::testing::Return(3)); int trajectory_id = stub_->AddTrajectoryBuilder( expected_sensor_ids, trajectory_builder_options_, nullptr); EXPECT_EQ(trajectory_id, 3); EXPECT_CALL(*mock_map_builder_, GetTrajectoryBuilder(_)) .WillRepeatedly(::testing::Return(mock_trajectory_builder_.get())); mapping::TrajectoryBuilderInterface* trajectory_stub = stub_->GetTrajectoryBuilder(trajectory_id); sensor::ImuData imu_data{common::FromUniversal(42), Eigen::Vector3d(0., 0., 9.8), Eigen::Vector3d::Zero()}; EXPECT_CALL(*mock_trajectory_builder_, AddSensorData(::testing::StrEq(kImuSensorId.id), ::testing::Matcher<const sensor::ImuData&>(_))) .WillOnce(::testing::Return()); trajectory_stub->AddSensorData(kImuSensorId.id, imu_data); EXPECT_CALL(*mock_map_builder_, FinishTrajectory(trajectory_id)); stub_->FinishTrajectory(trajectory_id); server_->Shutdown(); } TEST_P(ClientServerTestByGridType, LocalSlam2D) { if (GetParam() == ::cartographer::mapping::GridType::TSDF) { SetOptionsToTSDF2D(); } InitializeRealServer(); server_->Start(); InitializeStub(); EXPECT_TRUE(stub_->pose_graph()->GetTrajectoryStates().empty()); int trajectory_id = stub_->AddTrajectoryBuilder({kRangeSensorId}, trajectory_builder_options_, local_slam_result_callback_); TrajectoryBuilderInterface* trajectory_stub = stub_->GetTrajectoryBuilder(trajectory_id); const auto measurements = mapping::testing::GenerateFakeRangeMeasurements( kTravelDistance, kDuration, kTimeStep); for (const auto& measurement : measurements) { trajectory_stub->AddSensorData(kRangeSensorId.id, measurement); } WaitForLocalSlamResults(measurements.size()); EXPECT_EQ(stub_->pose_graph()->GetTrajectoryStates().at(trajectory_id), PoseGraphInterface::TrajectoryState::ACTIVE); stub_->FinishTrajectory(trajectory_id); stub_->pose_graph()->RunFinalOptimization(); EXPECT_EQ(stub_->pose_graph()->GetTrajectoryStates().at(trajectory_id), PoseGraphInterface::TrajectoryState::FINISHED); EXPECT_EQ(local_slam_result_poses_.size(), measurements.size()); EXPECT_NEAR(kTravelDistance, (local_slam_result_poses_.back().translation() - local_slam_result_poses_.front().translation()) .norm(), 0.1 * kTravelDistance); server_->Shutdown(); } TEST_P(ClientServerTestByGridType, LocalSlamAndDelete2D) { if (GetParam() == ::cartographer::mapping::GridType::TSDF) { SetOptionsToTSDF2D(); } InitializeRealServer(); server_->Start(); InitializeStub(); int trajectory_id = stub_->AddTrajectoryBuilder({kRangeSensorId}, trajectory_builder_options_, local_slam_result_callback_); TrajectoryBuilderInterface* trajectory_stub = stub_->GetTrajectoryBuilder(trajectory_id); const auto measurements = mapping::testing::GenerateFakeRangeMeasurements( kTravelDistance, kDuration, kTimeStep); for (const auto& measurement : measurements) { trajectory_stub->AddSensorData(kRangeSensorId.id, measurement); } WaitForLocalSlamResults(measurements.size()); stub_->pose_graph()->RunFinalOptimization(); EXPECT_EQ(stub_->pose_graph()->GetTrajectoryStates().at(trajectory_id), PoseGraphInterface::TrajectoryState::ACTIVE); EXPECT_GT(stub_->pose_graph()->GetAllSubmapPoses().size(), 0); EXPECT_GT(stub_->pose_graph()->GetTrajectoryNodePoses().size(), 0); stub_->FinishTrajectory(trajectory_id); stub_->pose_graph()->DeleteTrajectory(trajectory_id); stub_->pose_graph()->RunFinalOptimization(); EXPECT_EQ(stub_->pose_graph()->GetTrajectoryStates().at(trajectory_id), PoseGraphInterface::TrajectoryState::DELETED); EXPECT_EQ(stub_->pose_graph()->GetAllSubmapPoses().size(), 0); EXPECT_EQ(stub_->pose_graph()->GetTrajectoryNodePoses().size(), 0); server_->Shutdown(); } TEST_F(ClientServerTest, GlobalSlam3D) { map_builder_server_options_.mutable_map_builder_options() ->set_use_trajectory_builder_2d(false); map_builder_server_options_.mutable_map_builder_options() ->set_use_trajectory_builder_3d(true); map_builder_server_options_.mutable_map_builder_options() ->mutable_pose_graph_options() ->set_optimize_every_n_nodes(3); trajectory_builder_options_.mutable_trajectory_builder_3d_options() ->mutable_motion_filter_options() ->set_max_distance_meters(0); trajectory_builder_options_.mutable_trajectory_builder_3d_options() ->mutable_motion_filter_options() ->set_max_angle_radians(0); InitializeRealServer(); server_->Start(); InitializeStub(); int trajectory_id = stub_->AddTrajectoryBuilder( {kRangeSensorId, kImuSensorId}, trajectory_builder_options_, local_slam_result_callback_); TrajectoryBuilderInterface* trajectory_stub = stub_->GetTrajectoryBuilder(trajectory_id); const auto measurements = mapping::testing::GenerateFakeRangeMeasurements( kTravelDistance, kDuration, kTimeStep); for (const auto& measurement : measurements) { sensor::ImuData imu_data{ measurement.time - common::FromSeconds(kTimeStep / 2), Eigen::Vector3d(0., 0., 9.8), Eigen::Vector3d::Zero()}; trajectory_stub->AddSensorData(kImuSensorId.id, imu_data); trajectory_stub->AddSensorData(kRangeSensorId.id, measurement); } // First range data will not call back while initializing PoseExtrapolator, so // expect one less. WaitForLocalSlamResults(measurements.size() - 1); stub_->FinishTrajectory(trajectory_id); EXPECT_NEAR(kTravelDistance, (local_slam_result_poses_.back().translation() - local_slam_result_poses_.front().translation()) .norm(), 0.1 * kTravelDistance); server_->Shutdown(); } TEST_P(ClientServerTestByGridType, StartAndStopUploadingServerAndServer) { if (GetParam() == ::cartographer::mapping::GridType::TSDF) { SetOptionsToTSDF2D(); } InitializeRealServer(); server_->Start(); InitializeRealUploadingServer(); uploading_server_->Start(); uploading_server_->Shutdown(); server_->Shutdown(); } TEST_P(ClientServerTestByGridType, AddTrajectoryBuilderWithUploadingServer) { if (GetParam() == ::cartographer::mapping::GridType::TSDF) { SetOptionsToTSDF2D(); } InitializeRealServer(); server_->Start(); InitializeRealUploadingServer(); uploading_server_->Start(); InitializeStub(); InitializeStubForUploadingServer(); int trajectory_id = stub_for_uploading_server_->AddTrajectoryBuilder( {kImuSensorId}, trajectory_builder_options_, nullptr); EXPECT_FALSE(stub_for_uploading_server_->pose_graph()->IsTrajectoryFinished( trajectory_id)); EXPECT_FALSE(stub_->pose_graph()->IsTrajectoryFinished(trajectory_id)); stub_for_uploading_server_->FinishTrajectory(trajectory_id); EXPECT_TRUE(stub_for_uploading_server_->pose_graph()->IsTrajectoryFinished( trajectory_id)); EXPECT_TRUE(stub_->pose_graph()->IsTrajectoryFinished(trajectory_id)); EXPECT_FALSE(stub_for_uploading_server_->pose_graph()->IsTrajectoryFrozen( trajectory_id)); EXPECT_FALSE(stub_->pose_graph()->IsTrajectoryFrozen(trajectory_id)); uploading_server_->Shutdown(); server_->Shutdown(); } TEST_P(ClientServerTestByGridType, LocalSlam2DWithUploadingServer) { if (GetParam() == ::cartographer::mapping::GridType::TSDF) { SetOptionsToTSDF2D(); } InitializeRealServer(); server_->Start(); InitializeStub(); InitializeRealUploadingServer(); uploading_server_->Start(); InitializeStubForUploadingServer(); int trajectory_id = stub_for_uploading_server_->AddTrajectoryBuilder( {kRangeSensorId}, trajectory_builder_options_, local_slam_result_callback_); TrajectoryBuilderInterface* trajectory_stub = stub_for_uploading_server_->GetTrajectoryBuilder(trajectory_id); const auto measurements = mapping::testing::GenerateFakeRangeMeasurements( kTravelDistance, kDuration, kTimeStep); for (const auto& measurement : measurements) { trajectory_stub->AddSensorData(kRangeSensorId.id, measurement); } WaitForLocalSlamResults(measurements.size()); WaitForLocalSlamResultUploads(number_of_insertion_results_); std::queue<std::unique_ptr<google::protobuf::Message>> chunks; io::ForwardingProtoStreamWriter writer( [&chunks](const google::protobuf::Message* proto) -> bool { if (!proto) { return true; } std::unique_ptr<google::protobuf::Message> p(proto->New()); p->CopyFrom(*proto); chunks.push(std::move(p)); return true; }); stub_->SerializeState(false, &writer); CHECK(writer.Close()); // Ensure it can be read. io::InMemoryProtoStreamReader reader(std::move(chunks)); io::ProtoStreamDeserializer deserializer(&reader); EXPECT_EQ(deserializer.pose_graph().trajectory_size(), 1); stub_for_uploading_server_->FinishTrajectory(trajectory_id); EXPECT_EQ(local_slam_result_poses_.size(), measurements.size()); EXPECT_NEAR(kTravelDistance, (local_slam_result_poses_.back().translation() - local_slam_result_poses_.front().translation()) .norm(), 0.1 * kTravelDistance); uploading_server_->Shutdown(); server_->Shutdown(); } TEST_P(ClientServerTestByGridType, LocalSlam2DUplinkServerRestarting) { if (GetParam() == ::cartographer::mapping::GridType::TSDF) { SetOptionsToTSDF2D(); } InitializeRealServer(); server_->Start(); InitializeStub(); InitializeRealUploadingServer(); uploading_server_->Start(); InitializeStubForUploadingServer(); int trajectory_id = stub_for_uploading_server_->AddTrajectoryBuilder( {kRangeSensorId}, trajectory_builder_options_, local_slam_result_callback_); TrajectoryBuilderInterface* trajectory_stub = stub_for_uploading_server_->GetTrajectoryBuilder(trajectory_id); const auto measurements = mapping::testing::GenerateFakeRangeMeasurements( kTravelDistance, kDuration, kTimeStep); // Insert half of the measurements. for (unsigned int i = 0; i < measurements.size() / 2; ++i) { trajectory_stub->AddSensorData(kRangeSensorId.id, measurements.at(i)); } WaitForLocalSlamResults(measurements.size() / 2); WaitForLocalSlamResultUploads(number_of_insertion_results_); // Simulate a cloud server restart. LOG(INFO) << "Simulating server restart."; constexpr int kUplinkTrajectoryId = 0; stub_->FinishTrajectory(kUplinkTrajectoryId); server_->Shutdown(); server_->WaitForShutdown(); InitializeRealServer(); server_->Start(); InitializeStub(); // Insert the second half of the measurements. for (unsigned int i = measurements.size() / 2; i < measurements.size(); ++i) { trajectory_stub->AddSensorData(kRangeSensorId.id, measurements.at(i)); } WaitForLocalSlamResults(measurements.size() / 2); WaitForLocalSlamResultUploads(2); stub_for_uploading_server_->FinishTrajectory(trajectory_id); uploading_server_->Shutdown(); uploading_server_->WaitForShutdown(); server_->Shutdown(); server_->WaitForShutdown(); } TEST_P(ClientServerTestByGridType, LoadStateAndDelete) { if (GetParam() == ::cartographer::mapping::GridType::TSDF) { SetOptionsToTSDF2D(); } InitializeRealServer(); server_->Start(); InitializeStub(); // Load text proto into in_memory_reader. auto reader = ProtoReaderFromStrings(kSerializationHeaderProtoString, { kPoseGraphProtoString, kAllTrajectoryBuilderOptionsProtoString, kSubmapProtoString, kNodeProtoString, kImuDataProtoString, kOdometryDataProtoString, kLandmarkDataProtoString, }); auto trajectory_remapping = stub_->LoadState(reader.get(), true); int expected_trajectory_id = 0; EXPECT_EQ(trajectory_remapping.size(), 1); EXPECT_EQ(trajectory_remapping.at(0), expected_trajectory_id); stub_->pose_graph()->RunFinalOptimization(); EXPECT_TRUE(stub_->pose_graph()->IsTrajectoryFrozen(expected_trajectory_id)); EXPECT_FALSE( stub_->pose_graph()->IsTrajectoryFinished(expected_trajectory_id)); for (const auto& entry : trajectory_remapping) { int trajectory_id = entry.second; stub_->pose_graph()->DeleteTrajectory(trajectory_id); stub_->pose_graph()->RunFinalOptimization(); EXPECT_EQ(stub_->pose_graph()->GetTrajectoryStates().at(trajectory_id), PoseGraphInterface::TrajectoryState::DELETED); } server_->Shutdown(); } TEST_P(ClientServerTestByGridType, LoadUnfrozenStateAndDelete) { if (GetParam() == ::cartographer::mapping::GridType::TSDF) { SetOptionsToTSDF2D(); } InitializeRealServer(); server_->Start(); InitializeStub(); // Load text proto into in_memory_reader. auto reader = ProtoReaderFromStrings(kSerializationHeaderProtoString, { kPoseGraphProtoString, kAllTrajectoryBuilderOptionsProtoString, kSubmapProtoString, kNodeProtoString, kImuDataProtoString, kOdometryDataProtoString, kLandmarkDataProtoString, }); auto trajectory_remapping = stub_->LoadState(reader.get(), false /* load_frozen_state */); int expected_trajectory_id = 0; EXPECT_EQ(trajectory_remapping.size(), 1); EXPECT_EQ(trajectory_remapping.at(0), expected_trajectory_id); stub_->pose_graph()->RunFinalOptimization(); EXPECT_FALSE(stub_->pose_graph()->IsTrajectoryFrozen(expected_trajectory_id)); EXPECT_FALSE( stub_->pose_graph()->IsTrajectoryFinished(expected_trajectory_id)); EXPECT_EQ( stub_->pose_graph()->GetTrajectoryStates().at(expected_trajectory_id), PoseGraphInterface::TrajectoryState::ACTIVE); stub_->FinishTrajectory(expected_trajectory_id); EXPECT_EQ( stub_->pose_graph()->GetTrajectoryStates().at(expected_trajectory_id), PoseGraphInterface::TrajectoryState::FINISHED); for (const auto& entry : trajectory_remapping) { int trajectory_id = entry.second; stub_->pose_graph()->DeleteTrajectory(trajectory_id); stub_->pose_graph()->RunFinalOptimization(); EXPECT_EQ(stub_->pose_graph()->GetTrajectoryStates().at(trajectory_id), PoseGraphInterface::TrajectoryState::DELETED); } server_->Shutdown(); } // TODO(gaschler): Test-cover LoadStateFromFile. TEST_P(ClientServerTestByGridType, LocalSlam2DHandlesInvalidRequests) { if (GetParam() == ::cartographer::mapping::GridType::TSDF) { SetOptionsToTSDF2D(); } InitializeRealServer(); server_->Start(); InitializeStub(); int trajectory_id = stub_->AddTrajectoryBuilder({kRangeSensorId}, trajectory_builder_options_, local_slam_result_callback_); TrajectoryBuilderInterface* trajectory_stub = stub_->GetTrajectoryBuilder(trajectory_id); const auto measurements = mapping::testing::GenerateFakeRangeMeasurements( kTravelDistance, kDuration, kTimeStep); for (const auto& measurement : measurements) { trajectory_stub->AddSensorData(kRangeSensorId.id, measurement); } WaitForLocalSlamResults(measurements.size()); stub_->pose_graph()->RunFinalOptimization(); const int kInvalidTrajectoryId = 7; stub_->pose_graph()->DeleteTrajectory(kInvalidTrajectoryId); EXPECT_FALSE(stub_->pose_graph()->IsTrajectoryFinished(kInvalidTrajectoryId)); EXPECT_FALSE(stub_->pose_graph()->IsTrajectoryFrozen(kInvalidTrajectoryId)); EXPECT_EQ(nullptr, stub_->GetTrajectoryBuilder(kInvalidTrajectoryId)); stub_->FinishTrajectory(kInvalidTrajectoryId); const mapping::SubmapId kInvalidSubmapId0{kInvalidTrajectoryId, 0}, kInvalidSubmapId1{trajectory_id, 424242}; mapping::proto::SubmapQuery::Response submap_query_response; // Expect that it returns non-empty error string. EXPECT_NE("", stub_->SubmapToProto(kInvalidSubmapId0, &submap_query_response)); EXPECT_NE("", stub_->SubmapToProto(kInvalidSubmapId1, &submap_query_response)); EXPECT_EQ(stub_->pose_graph()->GetTrajectoryStates().at(trajectory_id), PoseGraphInterface::TrajectoryState::ACTIVE); auto submap_poses = stub_->pose_graph()->GetAllSubmapPoses(); EXPECT_GT(submap_poses.size(), 0); EXPECT_GT(stub_->pose_graph()->GetTrajectoryNodePoses().size(), 0); stub_->FinishTrajectory(trajectory_id); stub_->pose_graph()->DeleteTrajectory(trajectory_id); stub_->pose_graph()->RunFinalOptimization(); mapping::SubmapId deleted_submap_id = submap_poses.begin()->id; EXPECT_NE("", stub_->SubmapToProto(deleted_submap_id, &submap_query_response)); EXPECT_EQ(stub_->pose_graph()->GetTrajectoryStates().at(trajectory_id), PoseGraphInterface::TrajectoryState::DELETED); // Make sure optimization runs with a deleted trajectory. stub_->pose_graph()->RunFinalOptimization(); server_->Shutdown(); } } // namespace } // namespace cloud } // namespace cartographer
42.169811
80
0.730457
[ "vector", "transform" ]
33cfef82602cc59fcb21d08ff7ea7adb8ab0fbda
8,481
cpp
C++
04_WorldBuilder/Source/grass_maker.cpp
bugsbycarlin/SecretSalsa
b4b15e7ba14cdc2be9aad4d111e710ed0ec507ee
[ "MIT" ]
null
null
null
04_WorldBuilder/Source/grass_maker.cpp
bugsbycarlin/SecretSalsa
b4b15e7ba14cdc2be9aad4d111e710ed0ec507ee
[ "MIT" ]
null
null
null
04_WorldBuilder/Source/grass_maker.cpp
bugsbycarlin/SecretSalsa
b4b15e7ba14cdc2be9aad4d111e710ed0ec507ee
[ "MIT" ]
null
null
null
/* Secret Salsa Matthew Carlin Copyright 2019 */ #include "grass_maker.h" using namespace std; using namespace Honey; void debug(int x) { printf("Here %d\n", x); } int GrassMaker::unique_count = 0; GrassMaker::GrassMaker(std::vector<std::vector<int>> selection_pixels, function<void(int)> progress_action) { unique_count++; wind_frames = {-0.5, -0.25, 0, 0.25, 0.5, 0.625, 0.75, 0.875, 1.0}; int map_width = hot_config.getInt("layout", "selection_width"); int map_height = hot_config.getInt("layout", "selection_height"); int num_calculations = 0; for (int i = 0; i < wind_frames.size(); i++) { SDL_Surface* x = SDL_CreateRGBSurface(0, map_width, map_height, 32, rmask, gmask, bmask, amask); windy_surfaces.push_back(x); } vector<unsigned int *>windy_surface_ptrs; for (int i = 0; i < wind_frames.size(); i++) { SDL_LockSurface(windy_surfaces[i]); windy_surface_ptrs.push_back((unsigned int *)windy_surfaces[i]->pixels); } // Count pixels needed to try int num_pixels_in_selection = 0; for (int k = 0; k < map_width; k++) { for (int l = 0; l < map_height; l++) { if (selection_pixels[k][l] == 1) { num_pixels_in_selection += 1; } } } printf("Number of pixels in selection is %d\n", num_pixels_in_selection); timing.setOverrideTime(0.0); // Set up the parameters int wind_strength_standard = hot_config.getInt("grass", "wind_strength"); int brush_stroke_length_standard = hot_config.getInt("grass", "brush_stroke_length"); int width = hot_config.getInt("grass", "brush_width"); int height = hot_config.getInt("grass", "brush_height"); int density = hot_config.getInt("grass", "brush_density"); float opacity = hot_config.getFloat("grass", "brush_opacity"); float blend_factor = hot_config.getFloat("grass", "brush_blend_factor"); vector<string> grass_colors; string grass_color_string = hot_config.getString("grass", "grass_colors"); boost::split(grass_colors, grass_color_string, boost::is_any_of(","), boost::token_compress_on); // Number of strokes is based on density now int brush_stroke_count = (int) (num_pixels_in_selection * hot_config.getFloat("grass", "brush_stroke_density")); printf("Brush stroke count is %d\n", brush_stroke_count); // Grab a series of points. We're going to sort these in Y order so they draw correctly. vector<position> root_positions; int sample_brush_strokes = brush_stroke_count; while(sample_brush_strokes > 0) { int x = math_utils.randomInt(0, map_width); int y = math_utils.randomInt(0, map_height); if (selection_pixels[x][y] == 1) { sample_brush_strokes -= 1; root_positions.push_back({x, y}); } num_calculations += 1; if (num_calculations % 50000 == 0) { progress_action(num_calculations); } debug(1); } sort(root_positions.begin(), root_positions.end()); debug(2); // Do a series of brush strokes for (int c = 0; c < brush_stroke_count; c++) { debug(3); std::vector<std::vector<int>> brush; // Make a brush stamp from random values according to the configured width, height, and density brush.resize(width); for (int j = 0; j < width; j++) { brush[j].resize(height); } for (int j = 0; j < density; j++) { brush[math_utils.randomInt(0, width)][math_utils.randomInt(0, height)] = 1; } // Vary the length a little bit from configured value to make it more natural int brush_stroke_length = brush_stroke_length_standard + math_utils.randomInt(-1 * (int) (brush_stroke_length_standard / 3.0), (int) (brush_stroke_length_standard / 3.0)); // Save the root color and x,y location of the stroke int root_x = root_positions[c].x; int root_y = root_positions[c].y; intColor root_color = graphics.parseIntColor(grass_colors[math_utils.randomInt(0, grass_colors.size())]); printf("Color is %d,%d,%d\n", root_color.r, root_color.g, root_color.b); // For each desired frame of animated grass, perform the stroke for (int i = 0; i < wind_frames.size(); i++) { // Set the wind strength as configured strength * frame fraction (eg some frames are a little and some are full) // Also vary this a little bit to make it more natural int wind_frame_root = wind_frames[i] * wind_strength_standard; int wind_strength = math_utils.randomInt(-3,3); if (abs(wind_frame_root) > 0) { wind_strength = wind_frame_root + math_utils.randomInt(-1 * (int) (abs(wind_frame_root) / 4.0), (int) (abs(wind_frame_root) / 4.0)); } // printf("Frame %d, strength %d\n", i, wind_strength); // Control the timing and make a series of effects; we'll force timing from 0 to 1 and // use the effects to interpolate the location timing.setOverrideTime(0.0); effects.makeTween("wind", 0, wind_strength, 10.0); // rampup effects.start("wind"); effects.makeTween("stroke", 0, brush_stroke_length - abs(wind_strength) / 2.0, 10.0); // linear effects.start("stroke"); // Parametrize down the length of the brush stroke, copying the stamp onto the image at each location for (int j = 0; j < brush_stroke_length; j++) { float t = (10.0 * j) / brush_stroke_length; timing.setOverrideTime(t); int center_x = root_x + (int) effects.tween("wind", effects.RAMPUP); int center_y = root_y - (int) effects.tween("stroke", effects.LINEAR); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (brush[x][y] == 1) { int k = center_x - width / 2 + x; int l = center_y - y; if (0 <= k && k < map_width && 0 <= l && l < map_height) { // Here's the actual pixel change per pixel int address = l * map_width + k; windy_surface_ptrs[i][address] = SDL_MapRGBA(windy_surfaces[i]->format, root_color.r, root_color.g, root_color.b, 255); num_calculations += 1; if (num_calculations % 200000 == 0) { progress_action(num_calculations); } // This is not anti-aliasing. This is just color blending. // vector<position> positions = {{k - 1, l}, {k + 1, l}, {k, l - 1}}; // for (position p : positions) { // if (0 <= p.x && p.x < old_surface->w && 0 <= p.y && p.y < old_surface->h) { // int blend_address = p.y * old_surface->w + p.x; // Uint8 a,r,g,b; // SDL_GetRGBA(windy_surface_ptrs[i][blend_address], windy_surfaces[i]->format, &r, &g, &b, &a); // Uint8 new_a, new_r, new_g, new_b; // new_r = blend_factor * root_r + (1 - blend_factor) * r; // new_g = blend_factor * root_g + (1 - blend_factor) * g; // new_b = blend_factor * root_b + (1 - blend_factor) * b; // new_a = blend_factor * root_a + (1 - blend_factor) * a; // windy_surface_ptrs[i][blend_address] = SDL_MapRGBA(windy_surfaces[i]->format, new_r, new_g, new_b, new_a); // // if (math_utils.randomInt(0,500) == 88 && abs(g - root_g) > 30) { // // printf("Old %d, %d, %d, %d\n", r, g, b, a); // // printf("Root %d, %d, %d, %d\n", root_r, root_g, root_b, root_a); // // printf("New %d, %d, %d, %d\n", new_r, new_g, new_b, new_a); // // } // // Uint8 new_a = blend_factor * root_a > a ? blend_factor * root_a : a; // // windy_surface_ptrs[i][blend_address] = SDL_MapRGBA(windy_surfaces[i]->format, root_r, root_g, root_b, new_a); // } // } } } } } } } } debug(8); vector<string> frames = {}; for (int i = 0; i < wind_frames.size(); i++) { SDL_UnlockSurface(windy_surfaces[i]); string frame_name = "windy_surface_" + to_string(unique_count) + "_" + to_string(i); graphics.addImageFromSurface(frame_name, windy_surfaces[i]); frames.push_back(frame_name); printf("%s\n", frames[frames.size() - 1].c_str()); } debug(9); result = new Drawable("", map_width / 2, map_height / 2); result->addAnimation("default", frames); timing.removeOverrideTime(); } GrassMaker::~GrassMaker() { }
40.385714
175
0.606768
[ "vector" ]
33d3cffdac9d8ee862d261ebae7f5edcf731c6e2
53,055
cc
C++
transaction_redundancy_test/v3lock.pb.cc
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
1
2020-05-22T08:47:00.000Z
2020-05-22T08:47:00.000Z
transaction_redundancy_test/v3lock.pb.cc
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
null
null
null
transaction_redundancy_test/v3lock.pb.cc
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: v3lock.proto #include "v3lock.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> extern PROTOBUF_INTERNAL_EXPORT_v3lock_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_ResponseHeader_v3lock_2eproto; namespace v3lockpb { class LockRequestDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<LockRequest> _instance; } _LockRequest_default_instance_; class LockResponseDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<LockResponse> _instance; } _LockResponse_default_instance_; class UnlockRequestDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<UnlockRequest> _instance; } _UnlockRequest_default_instance_; class UnlockResponseDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<UnlockResponse> _instance; } _UnlockResponse_default_instance_; class ResponseHeaderDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<ResponseHeader> _instance; } _ResponseHeader_default_instance_; } // namespace v3lockpb static void InitDefaultsscc_info_LockRequest_v3lock_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::v3lockpb::_LockRequest_default_instance_; new (ptr) ::v3lockpb::LockRequest(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::v3lockpb::LockRequest::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_LockRequest_v3lock_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_LockRequest_v3lock_2eproto}, {}}; static void InitDefaultsscc_info_LockResponse_v3lock_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::v3lockpb::_LockResponse_default_instance_; new (ptr) ::v3lockpb::LockResponse(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::v3lockpb::LockResponse::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_LockResponse_v3lock_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_LockResponse_v3lock_2eproto}, { &scc_info_ResponseHeader_v3lock_2eproto.base,}}; static void InitDefaultsscc_info_ResponseHeader_v3lock_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::v3lockpb::_ResponseHeader_default_instance_; new (ptr) ::v3lockpb::ResponseHeader(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::v3lockpb::ResponseHeader::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_ResponseHeader_v3lock_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_ResponseHeader_v3lock_2eproto}, {}}; static void InitDefaultsscc_info_UnlockRequest_v3lock_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::v3lockpb::_UnlockRequest_default_instance_; new (ptr) ::v3lockpb::UnlockRequest(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::v3lockpb::UnlockRequest::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_UnlockRequest_v3lock_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_UnlockRequest_v3lock_2eproto}, {}}; static void InitDefaultsscc_info_UnlockResponse_v3lock_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::v3lockpb::_UnlockResponse_default_instance_; new (ptr) ::v3lockpb::UnlockResponse(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::v3lockpb::UnlockResponse::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_UnlockResponse_v3lock_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_UnlockResponse_v3lock_2eproto}, { &scc_info_ResponseHeader_v3lock_2eproto.base,}}; static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_v3lock_2eproto[5]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_v3lock_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_v3lock_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_v3lock_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::v3lockpb::LockRequest, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::v3lockpb::LockRequest, name_), PROTOBUF_FIELD_OFFSET(::v3lockpb::LockRequest, lease_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::v3lockpb::LockResponse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::v3lockpb::LockResponse, header_), PROTOBUF_FIELD_OFFSET(::v3lockpb::LockResponse, key_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::v3lockpb::UnlockRequest, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::v3lockpb::UnlockRequest, key_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::v3lockpb::UnlockResponse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::v3lockpb::UnlockResponse, header_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::v3lockpb::ResponseHeader, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::v3lockpb::ResponseHeader, cluster_id_), PROTOBUF_FIELD_OFFSET(::v3lockpb::ResponseHeader, member_id_), PROTOBUF_FIELD_OFFSET(::v3lockpb::ResponseHeader, revision_), PROTOBUF_FIELD_OFFSET(::v3lockpb::ResponseHeader, raft_term_), }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::v3lockpb::LockRequest)}, { 7, -1, sizeof(::v3lockpb::LockResponse)}, { 14, -1, sizeof(::v3lockpb::UnlockRequest)}, { 20, -1, sizeof(::v3lockpb::UnlockResponse)}, { 26, -1, sizeof(::v3lockpb::ResponseHeader)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::v3lockpb::_LockRequest_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::v3lockpb::_LockResponse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::v3lockpb::_UnlockRequest_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::v3lockpb::_UnlockResponse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::v3lockpb::_ResponseHeader_default_instance_), }; const char descriptor_table_protodef_v3lock_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\014v3lock.proto\022\010v3lockpb\032\034google/api/ann" "otations.proto\"*\n\013LockRequest\022\014\n\004name\030\001 " "\001(\014\022\r\n\005lease\030\002 \001(\003\"E\n\014LockResponse\022(\n\006he" "ader\030\001 \001(\0132\030.v3lockpb.ResponseHeader\022\013\n\003" "key\030\002 \001(\014\"\034\n\rUnlockRequest\022\013\n\003key\030\001 \001(\014\"" ":\n\016UnlockResponse\022(\n\006header\030\001 \001(\0132\030.v3lo" "ckpb.ResponseHeader\"\\\n\016ResponseHeader\022\022\n" "\ncluster_id\030\001 \001(\004\022\021\n\tmember_id\030\002 \001(\004\022\020\n\010" "revision\030\003 \001(\003\022\021\n\traft_term\030\004 \001(\0042\260\001\n\004Lo" "ck\022O\n\004Lock\022\025.v3lockpb.LockRequest\032\026.v3lo" "ckpb.LockResponse\"\030\202\323\344\223\002\022\"\r/v3/lock/lock" ":\001*\022W\n\006Unlock\022\027.v3lockpb.UnlockRequest\032\030" ".v3lockpb.UnlockResponse\"\032\202\323\344\223\002\024\"\017/v3/lo" "ck/unlock:\001*b\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_v3lock_2eproto_deps[1] = { &::descriptor_table_google_2fapi_2fannotations_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_v3lock_2eproto_sccs[5] = { &scc_info_LockRequest_v3lock_2eproto.base, &scc_info_LockResponse_v3lock_2eproto.base, &scc_info_ResponseHeader_v3lock_2eproto.base, &scc_info_UnlockRequest_v3lock_2eproto.base, &scc_info_UnlockResponse_v3lock_2eproto.base, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_v3lock_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_v3lock_2eproto = { false, false, descriptor_table_protodef_v3lock_2eproto, "v3lock.proto", 540, &descriptor_table_v3lock_2eproto_once, descriptor_table_v3lock_2eproto_sccs, descriptor_table_v3lock_2eproto_deps, 5, 1, schemas, file_default_instances, TableStruct_v3lock_2eproto::offsets, file_level_metadata_v3lock_2eproto, 5, file_level_enum_descriptors_v3lock_2eproto, file_level_service_descriptors_v3lock_2eproto, }; // Force running AddDescriptors() at dynamic initialization time. static bool dynamic_init_dummy_v3lock_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_v3lock_2eproto)), true); namespace v3lockpb { // =================================================================== void LockRequest::InitAsDefaultInstance() { } class LockRequest::_Internal { public: }; LockRequest::LockRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:v3lockpb.LockRequest) } LockRequest::LockRequest(const LockRequest& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_name().empty()) { name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(), GetArena()); } lease_ = from.lease_; // @@protoc_insertion_point(copy_constructor:v3lockpb.LockRequest) } void LockRequest::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_LockRequest_v3lock_2eproto.base); name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); lease_ = PROTOBUF_LONGLONG(0); } LockRequest::~LockRequest() { // @@protoc_insertion_point(destructor:v3lockpb.LockRequest) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void LockRequest::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void LockRequest::ArenaDtor(void* object) { LockRequest* _this = reinterpret_cast< LockRequest* >(object); (void)_this; } void LockRequest::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void LockRequest::SetCachedSize(int size) const { _cached_size_.Set(size); } const LockRequest& LockRequest::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_LockRequest_v3lock_2eproto.base); return *internal_default_instance(); } void LockRequest::Clear() { // @@protoc_insertion_point(message_clear_start:v3lockpb.LockRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); lease_ = PROTOBUF_LONGLONG(0); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* LockRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // bytes name = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // int64 lease = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { lease_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* LockRequest::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:v3lockpb.LockRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // bytes name = 1; if (this->name().size() > 0) { target = stream->WriteBytesMaybeAliased( 1, this->_internal_name(), target); } // int64 lease = 2; if (this->lease() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64ToArray(2, this->_internal_lease(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:v3lockpb.LockRequest) return target; } size_t LockRequest::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:v3lockpb.LockRequest) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // bytes name = 1; if (this->name().size() > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_name()); } // int64 lease = 2; if (this->lease() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int64Size( this->_internal_lease()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void LockRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:v3lockpb.LockRequest) GOOGLE_DCHECK_NE(&from, this); const LockRequest* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<LockRequest>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:v3lockpb.LockRequest) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:v3lockpb.LockRequest) MergeFrom(*source); } } void LockRequest::MergeFrom(const LockRequest& from) { // @@protoc_insertion_point(class_specific_merge_from_start:v3lockpb.LockRequest) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.name().size() > 0) { _internal_set_name(from._internal_name()); } if (from.lease() != 0) { _internal_set_lease(from._internal_lease()); } } void LockRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:v3lockpb.LockRequest) if (&from == this) return; Clear(); MergeFrom(from); } void LockRequest::CopyFrom(const LockRequest& from) { // @@protoc_insertion_point(class_specific_copy_from_start:v3lockpb.LockRequest) if (&from == this) return; Clear(); MergeFrom(from); } bool LockRequest::IsInitialized() const { return true; } void LockRequest::InternalSwap(LockRequest* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); swap(lease_, other->lease_); } ::PROTOBUF_NAMESPACE_ID::Metadata LockRequest::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void LockResponse::InitAsDefaultInstance() { ::v3lockpb::_LockResponse_default_instance_._instance.get_mutable()->header_ = const_cast< ::v3lockpb::ResponseHeader*>( ::v3lockpb::ResponseHeader::internal_default_instance()); } class LockResponse::_Internal { public: static const ::v3lockpb::ResponseHeader& header(const LockResponse* msg); }; const ::v3lockpb::ResponseHeader& LockResponse::_Internal::header(const LockResponse* msg) { return *msg->header_; } LockResponse::LockResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:v3lockpb.LockResponse) } LockResponse::LockResponse(const LockResponse& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_key().empty()) { key_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_key(), GetArena()); } if (from._internal_has_header()) { header_ = new ::v3lockpb::ResponseHeader(*from.header_); } else { header_ = nullptr; } // @@protoc_insertion_point(copy_constructor:v3lockpb.LockResponse) } void LockResponse::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_LockResponse_v3lock_2eproto.base); key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); header_ = nullptr; } LockResponse::~LockResponse() { // @@protoc_insertion_point(destructor:v3lockpb.LockResponse) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void LockResponse::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); key_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete header_; } void LockResponse::ArenaDtor(void* object) { LockResponse* _this = reinterpret_cast< LockResponse* >(object); (void)_this; } void LockResponse::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void LockResponse::SetCachedSize(int size) const { _cached_size_.Set(size); } const LockResponse& LockResponse::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_LockResponse_v3lock_2eproto.base); return *internal_default_instance(); } void LockResponse::Clear() { // @@protoc_insertion_point(message_clear_start:v3lockpb.LockResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; key_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); if (GetArena() == nullptr && header_ != nullptr) { delete header_; } header_ = nullptr; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* LockResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // .v3lockpb.ResponseHeader header = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr = ctx->ParseMessage(_internal_mutable_header(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // bytes key = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_key(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* LockResponse::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:v3lockpb.LockResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // .v3lockpb.ResponseHeader header = 1; if (this->has_header()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 1, _Internal::header(this), target, stream); } // bytes key = 2; if (this->key().size() > 0) { target = stream->WriteBytesMaybeAliased( 2, this->_internal_key(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:v3lockpb.LockResponse) return target; } size_t LockResponse::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:v3lockpb.LockResponse) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // bytes key = 2; if (this->key().size() > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_key()); } // .v3lockpb.ResponseHeader header = 1; if (this->has_header()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *header_); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void LockResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:v3lockpb.LockResponse) GOOGLE_DCHECK_NE(&from, this); const LockResponse* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<LockResponse>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:v3lockpb.LockResponse) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:v3lockpb.LockResponse) MergeFrom(*source); } } void LockResponse::MergeFrom(const LockResponse& from) { // @@protoc_insertion_point(class_specific_merge_from_start:v3lockpb.LockResponse) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.key().size() > 0) { _internal_set_key(from._internal_key()); } if (from.has_header()) { _internal_mutable_header()->::v3lockpb::ResponseHeader::MergeFrom(from._internal_header()); } } void LockResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:v3lockpb.LockResponse) if (&from == this) return; Clear(); MergeFrom(from); } void LockResponse::CopyFrom(const LockResponse& from) { // @@protoc_insertion_point(class_specific_copy_from_start:v3lockpb.LockResponse) if (&from == this) return; Clear(); MergeFrom(from); } bool LockResponse::IsInitialized() const { return true; } void LockResponse::InternalSwap(LockResponse* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); key_.Swap(&other->key_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); swap(header_, other->header_); } ::PROTOBUF_NAMESPACE_ID::Metadata LockResponse::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void UnlockRequest::InitAsDefaultInstance() { } class UnlockRequest::_Internal { public: }; UnlockRequest::UnlockRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:v3lockpb.UnlockRequest) } UnlockRequest::UnlockRequest(const UnlockRequest& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_key().empty()) { key_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_key(), GetArena()); } // @@protoc_insertion_point(copy_constructor:v3lockpb.UnlockRequest) } void UnlockRequest::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_UnlockRequest_v3lock_2eproto.base); key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } UnlockRequest::~UnlockRequest() { // @@protoc_insertion_point(destructor:v3lockpb.UnlockRequest) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void UnlockRequest::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); key_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void UnlockRequest::ArenaDtor(void* object) { UnlockRequest* _this = reinterpret_cast< UnlockRequest* >(object); (void)_this; } void UnlockRequest::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void UnlockRequest::SetCachedSize(int size) const { _cached_size_.Set(size); } const UnlockRequest& UnlockRequest::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_UnlockRequest_v3lock_2eproto.base); return *internal_default_instance(); } void UnlockRequest::Clear() { // @@protoc_insertion_point(message_clear_start:v3lockpb.UnlockRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; key_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* UnlockRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // bytes key = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_key(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* UnlockRequest::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:v3lockpb.UnlockRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // bytes key = 1; if (this->key().size() > 0) { target = stream->WriteBytesMaybeAliased( 1, this->_internal_key(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:v3lockpb.UnlockRequest) return target; } size_t UnlockRequest::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:v3lockpb.UnlockRequest) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // bytes key = 1; if (this->key().size() > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_key()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void UnlockRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:v3lockpb.UnlockRequest) GOOGLE_DCHECK_NE(&from, this); const UnlockRequest* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<UnlockRequest>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:v3lockpb.UnlockRequest) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:v3lockpb.UnlockRequest) MergeFrom(*source); } } void UnlockRequest::MergeFrom(const UnlockRequest& from) { // @@protoc_insertion_point(class_specific_merge_from_start:v3lockpb.UnlockRequest) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.key().size() > 0) { _internal_set_key(from._internal_key()); } } void UnlockRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:v3lockpb.UnlockRequest) if (&from == this) return; Clear(); MergeFrom(from); } void UnlockRequest::CopyFrom(const UnlockRequest& from) { // @@protoc_insertion_point(class_specific_copy_from_start:v3lockpb.UnlockRequest) if (&from == this) return; Clear(); MergeFrom(from); } bool UnlockRequest::IsInitialized() const { return true; } void UnlockRequest::InternalSwap(UnlockRequest* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); key_.Swap(&other->key_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } ::PROTOBUF_NAMESPACE_ID::Metadata UnlockRequest::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void UnlockResponse::InitAsDefaultInstance() { ::v3lockpb::_UnlockResponse_default_instance_._instance.get_mutable()->header_ = const_cast< ::v3lockpb::ResponseHeader*>( ::v3lockpb::ResponseHeader::internal_default_instance()); } class UnlockResponse::_Internal { public: static const ::v3lockpb::ResponseHeader& header(const UnlockResponse* msg); }; const ::v3lockpb::ResponseHeader& UnlockResponse::_Internal::header(const UnlockResponse* msg) { return *msg->header_; } UnlockResponse::UnlockResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:v3lockpb.UnlockResponse) } UnlockResponse::UnlockResponse(const UnlockResponse& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); if (from._internal_has_header()) { header_ = new ::v3lockpb::ResponseHeader(*from.header_); } else { header_ = nullptr; } // @@protoc_insertion_point(copy_constructor:v3lockpb.UnlockResponse) } void UnlockResponse::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_UnlockResponse_v3lock_2eproto.base); header_ = nullptr; } UnlockResponse::~UnlockResponse() { // @@protoc_insertion_point(destructor:v3lockpb.UnlockResponse) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void UnlockResponse::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); if (this != internal_default_instance()) delete header_; } void UnlockResponse::ArenaDtor(void* object) { UnlockResponse* _this = reinterpret_cast< UnlockResponse* >(object); (void)_this; } void UnlockResponse::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void UnlockResponse::SetCachedSize(int size) const { _cached_size_.Set(size); } const UnlockResponse& UnlockResponse::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_UnlockResponse_v3lock_2eproto.base); return *internal_default_instance(); } void UnlockResponse::Clear() { // @@protoc_insertion_point(message_clear_start:v3lockpb.UnlockResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (GetArena() == nullptr && header_ != nullptr) { delete header_; } header_ = nullptr; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* UnlockResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // .v3lockpb.ResponseHeader header = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr = ctx->ParseMessage(_internal_mutable_header(), ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* UnlockResponse::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:v3lockpb.UnlockResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // .v3lockpb.ResponseHeader header = 1; if (this->has_header()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 1, _Internal::header(this), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:v3lockpb.UnlockResponse) return target; } size_t UnlockResponse::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:v3lockpb.UnlockResponse) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // .v3lockpb.ResponseHeader header = 1; if (this->has_header()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *header_); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void UnlockResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:v3lockpb.UnlockResponse) GOOGLE_DCHECK_NE(&from, this); const UnlockResponse* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<UnlockResponse>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:v3lockpb.UnlockResponse) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:v3lockpb.UnlockResponse) MergeFrom(*source); } } void UnlockResponse::MergeFrom(const UnlockResponse& from) { // @@protoc_insertion_point(class_specific_merge_from_start:v3lockpb.UnlockResponse) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.has_header()) { _internal_mutable_header()->::v3lockpb::ResponseHeader::MergeFrom(from._internal_header()); } } void UnlockResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:v3lockpb.UnlockResponse) if (&from == this) return; Clear(); MergeFrom(from); } void UnlockResponse::CopyFrom(const UnlockResponse& from) { // @@protoc_insertion_point(class_specific_copy_from_start:v3lockpb.UnlockResponse) if (&from == this) return; Clear(); MergeFrom(from); } bool UnlockResponse::IsInitialized() const { return true; } void UnlockResponse::InternalSwap(UnlockResponse* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(header_, other->header_); } ::PROTOBUF_NAMESPACE_ID::Metadata UnlockResponse::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void ResponseHeader::InitAsDefaultInstance() { } class ResponseHeader::_Internal { public: }; ResponseHeader::ResponseHeader(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:v3lockpb.ResponseHeader) } ResponseHeader::ResponseHeader(const ResponseHeader& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&cluster_id_, &from.cluster_id_, static_cast<size_t>(reinterpret_cast<char*>(&raft_term_) - reinterpret_cast<char*>(&cluster_id_)) + sizeof(raft_term_)); // @@protoc_insertion_point(copy_constructor:v3lockpb.ResponseHeader) } void ResponseHeader::SharedCtor() { ::memset(&cluster_id_, 0, static_cast<size_t>( reinterpret_cast<char*>(&raft_term_) - reinterpret_cast<char*>(&cluster_id_)) + sizeof(raft_term_)); } ResponseHeader::~ResponseHeader() { // @@protoc_insertion_point(destructor:v3lockpb.ResponseHeader) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void ResponseHeader::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void ResponseHeader::ArenaDtor(void* object) { ResponseHeader* _this = reinterpret_cast< ResponseHeader* >(object); (void)_this; } void ResponseHeader::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void ResponseHeader::SetCachedSize(int size) const { _cached_size_.Set(size); } const ResponseHeader& ResponseHeader::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_ResponseHeader_v3lock_2eproto.base); return *internal_default_instance(); } void ResponseHeader::Clear() { // @@protoc_insertion_point(message_clear_start:v3lockpb.ResponseHeader) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; ::memset(&cluster_id_, 0, static_cast<size_t>( reinterpret_cast<char*>(&raft_term_) - reinterpret_cast<char*>(&cluster_id_)) + sizeof(raft_term_)); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* ResponseHeader::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // uint64 cluster_id = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { cluster_id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // uint64 member_id = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { member_id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int64 revision = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { revision_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // uint64 raft_term = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { raft_term_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* ResponseHeader::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:v3lockpb.ResponseHeader) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint64 cluster_id = 1; if (this->cluster_id() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(1, this->_internal_cluster_id(), target); } // uint64 member_id = 2; if (this->member_id() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(2, this->_internal_member_id(), target); } // int64 revision = 3; if (this->revision() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64ToArray(3, this->_internal_revision(), target); } // uint64 raft_term = 4; if (this->raft_term() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(4, this->_internal_raft_term(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:v3lockpb.ResponseHeader) return target; } size_t ResponseHeader::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:v3lockpb.ResponseHeader) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // uint64 cluster_id = 1; if (this->cluster_id() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size( this->_internal_cluster_id()); } // uint64 member_id = 2; if (this->member_id() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size( this->_internal_member_id()); } // int64 revision = 3; if (this->revision() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int64Size( this->_internal_revision()); } // uint64 raft_term = 4; if (this->raft_term() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size( this->_internal_raft_term()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void ResponseHeader::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:v3lockpb.ResponseHeader) GOOGLE_DCHECK_NE(&from, this); const ResponseHeader* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<ResponseHeader>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:v3lockpb.ResponseHeader) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:v3lockpb.ResponseHeader) MergeFrom(*source); } } void ResponseHeader::MergeFrom(const ResponseHeader& from) { // @@protoc_insertion_point(class_specific_merge_from_start:v3lockpb.ResponseHeader) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.cluster_id() != 0) { _internal_set_cluster_id(from._internal_cluster_id()); } if (from.member_id() != 0) { _internal_set_member_id(from._internal_member_id()); } if (from.revision() != 0) { _internal_set_revision(from._internal_revision()); } if (from.raft_term() != 0) { _internal_set_raft_term(from._internal_raft_term()); } } void ResponseHeader::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:v3lockpb.ResponseHeader) if (&from == this) return; Clear(); MergeFrom(from); } void ResponseHeader::CopyFrom(const ResponseHeader& from) { // @@protoc_insertion_point(class_specific_copy_from_start:v3lockpb.ResponseHeader) if (&from == this) return; Clear(); MergeFrom(from); } bool ResponseHeader::IsInitialized() const { return true; } void ResponseHeader::InternalSwap(ResponseHeader* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(ResponseHeader, raft_term_) + sizeof(ResponseHeader::raft_term_) - PROTOBUF_FIELD_OFFSET(ResponseHeader, cluster_id_)>( reinterpret_cast<char*>(&cluster_id_), reinterpret_cast<char*>(&other->cluster_id_)); } ::PROTOBUF_NAMESPACE_ID::Metadata ResponseHeader::GetMetadata() const { return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) } // namespace v3lockpb PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::v3lockpb::LockRequest* Arena::CreateMaybeMessage< ::v3lockpb::LockRequest >(Arena* arena) { return Arena::CreateMessageInternal< ::v3lockpb::LockRequest >(arena); } template<> PROTOBUF_NOINLINE ::v3lockpb::LockResponse* Arena::CreateMaybeMessage< ::v3lockpb::LockResponse >(Arena* arena) { return Arena::CreateMessageInternal< ::v3lockpb::LockResponse >(arena); } template<> PROTOBUF_NOINLINE ::v3lockpb::UnlockRequest* Arena::CreateMaybeMessage< ::v3lockpb::UnlockRequest >(Arena* arena) { return Arena::CreateMessageInternal< ::v3lockpb::UnlockRequest >(arena); } template<> PROTOBUF_NOINLINE ::v3lockpb::UnlockResponse* Arena::CreateMaybeMessage< ::v3lockpb::UnlockResponse >(Arena* arena) { return Arena::CreateMessageInternal< ::v3lockpb::UnlockResponse >(arena); } template<> PROTOBUF_NOINLINE ::v3lockpb::ResponseHeader* Arena::CreateMaybeMessage< ::v3lockpb::ResponseHeader >(Arena* arena) { return Arena::CreateMessageInternal< ::v3lockpb::ResponseHeader >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
37.788462
162
0.738875
[ "object" ]
33d6110aaad9715c80fc3f54ce794a59cb7590a4
71,185
cpp
C++
test/TestData.cpp
doe300/VC4C
f69ba1f7114be0e97de421301c788176daafef29
[ "MIT" ]
111
2017-11-02T14:46:45.000Z
2022-03-15T21:32:59.000Z
test/TestData.cpp
doe300/VC4C
f69ba1f7114be0e97de421301c788176daafef29
[ "MIT" ]
139
2017-10-09T07:39:01.000Z
2021-11-20T15:31:27.000Z
test/TestData.cpp
doe300/VC4C
f69ba1f7114be0e97de421301c788176daafef29
[ "MIT" ]
33
2017-10-10T10:19:58.000Z
2022-02-27T15:59:50.000Z
/* * Author: doe300 * * See the file "LICENSE" for the full license governing this code. */ #include "TestData.h" #include "TestEntries.h" #include "test_files.h" #include <algorithm> #include <regex> #include <stdexcept> using namespace test_data; using namespace test_files; Result test_data::RESULT_OK{true, ""}; TestRunner::~TestRunner() noexcept = default; static Result checkPiSum(const std::vector<float>& result) { auto tmp = std::accumulate(result.begin(), result.end(), 0.0f) / 1024.0f; return checkScalarEqualsUlp(static_cast<float>(M_PI), tmp, 8, " as total sum"); } static std::map<std::string, TestData> ALL_TESTS{}; void test_data::registerTest(TestData&& data) { auto key = data.uniqueName; auto wasInserted = ALL_TESTS.emplace(key, std::move(data)).second; if(!wasInserted) throw std::runtime_error{"TestData key is not unique: " + key}; } void test_data::registerGeneralTests() { //// // Examples //// registerTest(TestData{"fibonacci", DataFilter::NONE, &fibonacci_cl_string, "", "fibonacci", {toScalarParameter(1u), toScalarParameter(1u), toBufferParameter(std::vector<uint32_t>(10))}, toDimensions(1), {checkParameterEquals(2, std::vector<uint32_t>{2, 3, 5, 8, 13, 21, 34, 55, 89, 144})}}); registerTest(TestData{"hello_world", DataFilter::NONE, &hello_world_cl_string, "", "hello_world", {toBufferParameter(std::vector<uint8_t>(8 * 16))}, toDimensions(8), {checkParameterEquals(0, std::vector<uint8_t>{ 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0', '\0', // 1st work-item 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0', '\0', // 2nd work-item 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0', '\0', // 3rd work-item 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0', '\0', // 4th work-item 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0', '\0', // 5th work-item 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0', '\0', // 6th work-item 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0', '\0', // 7th work-item 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0', '\0', // 8th work-item })}}); registerTest(TestData{"hello_world_constant", DataFilter::NONE, &hello_world_constant_cl_string, "", "hello_world", {toBufferParameter(std::vector<uint8_t>(16, 0x42))}, toDimensions(12), {checkParameterEquals(0, std::vector<uint8_t>{ 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', 0x42, 0x42, 0x42, 0x42})}}); registerTest(TestData{"hello_world_vector", DataFilter::NONE, &hello_world_vector_cl_string, "", "hello_world", {toBufferParameter( std::vector<uint8_t>{'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0', '\0'}), toBufferParameter(std::vector<uint8_t>(16))}, toDimensions(1), {checkParameterEquals(0, std::vector<uint8_t>{'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0', '\0'}), checkParameterEquals(1, std::vector<uint8_t>{ 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0', '\0'})}}); registerTest(TestData{"llvm_ir", DataFilter::NONE, &test_cl_string, "", "test_llvm_ir", {toBufferParameter(std::vector<uint32_t>(10))}, toDimensions(1), {checkParameterEquals(0, std::vector<uint32_t>{142})}}); registerTest(TestData{"instructions", DataFilter::INT_ARITHMETIC | DataFilter::FLOAT_ARITHMETIC, &test_instructions_cl_string, "", "test_instructions", {toScalarParameter(2u), toScalarParameter(4u), toScalarParameter(2.0f), toScalarParameter(4.0f), toBufferParameter(std::vector<uint32_t>(32)), toBufferParameter(std::vector<uint32_t>(32))}, toDimensions(1), {checkParameterEquals(4, std::vector<int32_t>{ 6, -2, 8, 0, 2, 4, 2, 2, 32, 0, 0, 6, 6, -3, 30, 3, 3, 1, 1, 0, 0, 0, 1, 1, 1, 0, 4, 8}), checkParameter<CompareULP<1>>(5, std::vector<float>{6.0f, -2.0f, 8.0f, 0.5f, 4.0f, 2.0f, 2.0f})}}); registerTest(TestData{"SHA1", DataFilter::DISABLED | DataFilter::COMPLEX_KERNEL, &md5_cl_string, "", "sha1_crypt_kernel", {// parameter 0 is the control data toBufferParameter(std::vector<uint32_t>{0 /* padding*/, 1 /* number of keys */}), // parameter 1 is the salt, set to zero toBufferParameter(std::vector<uint32_t>(24, 0x0)), // parameter 2 is the "plain_key", the input TODO might need to invert the bytes in a word! toBufferParameter(std::vector<uint8_t>{'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!'}), // parameter 3 is the digest toBufferParameter(std::vector<uint32_t>(8))}, toDimensions(1), {checkParameterEquals(3, std::vector<uint32_t>{0x2ef7bde6, 0x08ce5404, 0xe97d5f04, 0x2f95f89f, 0x1c232871})}}); registerTest(TestData{"SHA256", DataFilter::DISABLED | DataFilter::COMPLEX_KERNEL, &SHA_256_cl_string, "", "execute_sha256_cpu", {// parameter 0 is the input with a block-size of 16 words toBufferParameter(std::vector<uint8_t>{'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '1', '1', '1', '1', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}), // parameter 1 is the digest toBufferParameter(std::vector<uint32_t>(128)), // parameter 2 is the stride toScalarParameter(0)}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{ 0xf90a1ef4, 0x422350ca, 0x8c448530, 0xa7d5d0b2, 0x35054803, 0xf7b2a73d, 0x86f4b639, 0x4b1329a5})}}); registerTest(TestData{"prime_found", DataFilter::NONE, &test_prime_cl_string, "", "test_prime", {toScalarParameter(17u), toBufferParameter(std::vector<uint32_t>(1))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{true})}}); registerTest(TestData{"prime_no_prime", DataFilter::NONE, &test_prime_cl_string, "", "test_prime", {toScalarParameter(18u), toBufferParameter(std::vector<uint32_t>(1))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{false})}}); //// // General Tests //// registerTest(TestData{"async_copy", DataFilter::ASYNC_BARRIER, &test_async_copy_cl_string, "", "test_async_copy", {toBufferParameter(toRange<unsigned>(0, 12 * 16)), toBufferParameter(std::vector<unsigned>(12 * 16)), toBufferParameter(std::vector<unsigned>(12 * 16))}, toDimensions(12), {/* the __local arg might be lowered to VPM */ checkParameterEquals(2, toRange<unsigned>(0, 12 * 16))}}); registerTest(TestData{"async_copy_general", DataFilter::ASYNC_BARRIER, &test_async_copy_cl_string, "", "test_async_copy_general", {toBufferParameter(toRange<unsigned>(0, 7 * 16)), toBufferParameter(std::vector<unsigned>(7 * 16)), toBufferParameter(std::vector<unsigned>(7 * 16))}, toDimensions(7), {/* the __local arg might be lowered to VPM */ checkParameterEquals(2, toRange<unsigned>(0, 7 * 16))}}); registerTest(TestData{"barrier_dynamic_work_size", DataFilter::ASYNC_BARRIER, &test_barrier_cl_string, "", "test_barrier", {toBufferParameter(std::vector<uint32_t>(12 * 8 * 2, 0x42))}, toDimensions(8, 1, 1, 2), {checkParameterEquals(0, std::vector<uint32_t>{ 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 1st work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 2nd work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 3rd work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 4th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 5th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 6th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 7th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 8th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 9th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 10th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 11th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 12th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 13th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 14th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 15th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 16th work-item })}}); registerTest(TestData{"barrier_fix_work_size", DataFilter::ASYNC_BARRIER, &test_barrier_cl_string, "-DFIXED_SIZE=1", "test_barrier", {toBufferParameter(std::vector<uint32_t>(12 * 8 * 2, 0x42))}, toDimensions(8, 1, 1, 2), {checkParameterEquals(0, std::vector<uint32_t>{ 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 1st work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 2nd work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 3rd work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 4th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 5th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 6th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 7th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 8th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 9th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 10th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 11th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 12th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 13th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 14th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 15th work-item 0, 1, 2, 0x42, 4, 5, 6, 7, 8, 9, 10, 0x42, // 16th work-item })}}); registerTest(TestData{"branches", DataFilter::CONTROL_FLOW, &test_branches_cl_string, "", "test_branches", {toBufferParameter(std::vector<uint32_t>{512, 1024, 256, 32, 64, 42}), toBufferParameter(std::vector<uint32_t>(6 * 12, 0x42))}, toDimensions(6), {checkParameterEquals(1, std::vector<uint32_t>{ 109, 1849, 512, 100, 100, 512, 0x42, 109, 0x42, 0x42, 0x42, 0x42, // in = 512 1010, 2027, 1024, 1000, 1000, 1024, 1010, 0x42, 0x42, 0x42, 0x42, 0x42, // in = 1024 108, 1833, 256, 100, 100, 256, 0x42, 0x42, 108, 0x42, 0x42, 0x42, // in = 256 15, 1401, 32, 10, 10, 32, 0x42, 0x42, 0x42, 0x42, 15, 0x42, // in = 32 16, 1465, 64, 10, 10, 64, 0x42, 0x42, 0x42, 16, 0x42, 0x42, // in = 64 11, 1145, 42, 10, 10, 42, 0x42, 0x42, 0x42, 0x42, 0x42, 11, // in = 42 })}}); registerTest(TestData{"switch_short", DataFilter::CONTROL_FLOW, &test_branches_cl_string, "", "test_short_switch", {toBufferParameter(std::vector<int16_t>{0x123, 0x124, 0x6432, 0x1345, -0x567, -0x7777}), toBufferParameter(std::vector<int16_t>(6, 0x42))}, toDimensions(6), {checkParameterEquals(1, std::vector<int16_t>{11, 0x124, 17 + 0x1245, 0x1345 + 0x1245, 0x42 - 0x0FFF, 42})}}); // TODO results are wrong for SPIR-V registerTest(TestData{"switch_long", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_branches_cl_string, "", "test_long_switch", {toBufferParameter( std::vector<int64_t>{0x12345678, 0x1F1F1F1F1F1F, 0x65432, 0x12345, -0x12345671234567, -0x12388887777}), toBufferParameter(std::vector<int64_t>(6, 0x42))}, toDimensions(6), {checkParameterEquals(1, std::vector<int64_t>{ 11, 0x1F1F1F1F1F1F, 17 + 0x1234500000000, 0x12345 + 0x1234500000000, 0x42 + 0x0FFF0000FFFF0000, 42})}}); registerTest(TestData{"CRC16", DataFilter::COMPLEX_KERNEL, &test_hashes_cl_string, "", "crc16", {// output half-word toBufferParameter(std::vector<uint16_t>(1)), // data toBufferParameter(std::vector<uint8_t>{'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!'}), // data size toScalarParameter(12)}, // algorithm is CRC-16/ARC toDimensions(1), {checkParameterEquals(0, std::vector<uint16_t>{0x57BE})}}); registerTest(TestData{"Pearson16", DataFilter::COMPLEX_KERNEL, &test_hashes_cl_string, "", "Pearson16", {// data toBufferParameter(std::vector<uint8_t>{'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!'}), // data size toScalarParameter(12), // 8 byte result toBufferParameter(std::vector<uint8_t>(8))}, toDimensions(1), {checkParameterEquals(2, std::vector<uint8_t>{92, 148, 236, 199, 49, 126, 212, 250})}}); registerTest(TestData{"atomics", DataFilter::ATOMIC_FUNCTIONS, &test_other_cl_string, "", "test_atomics", {toBufferParameter(toRange<int32_t>(1, 12)), toBufferParameter(toRange<int32_t>(1, 12))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{2, 0, 3, 5, 4, 6, 7, 8, 9, 10, 0})}}); registerTest(TestData{"f2i", DataFilter::TYPE_CONVERSIONS, &test_other_cl_string, "", "test_f2i", {toScalarParameter(1.0f), toScalarParameter(1.1f), toScalarParameter(1.5f), toScalarParameter(1.9f), toBufferParameter(std::vector<int32_t>(32))}, toDimensions(1), {checkParameterEquals(4, std::vector<int32_t>{1, 1, 1, 1, -1, -1, -1, -1, 1, -1, 2, -1, 1, -1, 1, -2, 1, -1, 2, -2, 1, 1, 2, 2, -1, -1, -2, -2, 1, -1})}}); registerTest(TestData{"sfu", DataFilter::NONE, &test_sfu_cl_string, "", "test_sfu", {toBufferParameter(std::vector<float>{1.0f, 2.0f, 8.0f, 32.0f, 128.0f, 25.70f, 11.1f, 10.240f, 1.5f, 2.7f, 9.0f, 124.340f, 112.2334455f, 56.7f, 74.1f, 0.00001f}), toBufferParameter(std::vector<float>(4 * 16))}, toDimensions(1), {// hardware passes with 1024 but fails with 512 checkParameter<CompareULP<1024>>(1, std::vector<float>{// recip 1.0f / 1.0f, 1.0f / 2.0f, 1.0f / 8.0f, 1.0f / 32.0f, 1.0f / 128.0f, 1.0f / 25.7f, 1.0f / 11.1f, 1.0f / 10.240f, 1.0f / 1.5f, 1.0f / 2.7f, 1.0f / 9.0f, 1.0f / 124.34f, 1.0f / 112.2334455f, 1.0f / 56.7f, 1.0f / 74.1f, 1.0f / 0.00001f, // rsqrt 1.0f / std::sqrt(1.0f), 1.0f / std::sqrt(2.0f), 1.0f / std::sqrt(8.0f), 1.0f / std::sqrt(32.0f), 1.0f / std::sqrt(128.0f), 1.0f / std::sqrt(25.7f), 1.0f / std::sqrt(11.1f), 1.0f / std::sqrt(10.240f), 1.0f / std::sqrt(1.5f), 1.0f / std::sqrt(2.7f), 1.0f / std::sqrt(9.0f), 1.0f / std::sqrt(124.34f), 1.0f / std::sqrt(112.2334455f), 1.0f / std::sqrt(56.7f), 1.0f / std::sqrt(74.1f), 1.0f / std::sqrt(0.00001f), // exp2 std::exp2(1.0f), std::exp2(2.0f), std::exp2(8.0f), std::exp2(32.0f), std::exp2(128.0f), std::exp2(25.70f), std::exp2(11.1f), std::exp2(10.240f), std::exp2(1.5f), std::exp2(2.7f), std::exp2(9.0f), std::exp2(124.340f), std::exp2(112.2334455f), std::exp2(56.7f), std::exp2(74.1f), std::exp2(0.00001f), // log2 std::log2(1.0f), std::log2(2.0f), std::log2(8.0f), std::log2(32.0f), std::log2(128.0f), std::log2(25.70f), std::log2(11.1f), std::log2(10.240f), std::log2(1.5f), std::log2(2.7f), std::log2(9.0f), std::log2(124.340f), std::log2(112.2334455f), std::log2(56.7f), std::log2(74.1f), std::log2(0.00001f)})}}); registerTest(TestData{"shuffle", DataFilter::VECTOR_OPERATIONS, &test_shuffle_cl_string, "", "test_shuffle", {toBufferParameter(toRange<uint8_t>(0, 32)), toBufferParameter(std::vector<uint8_t>(10 * 16))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint8_t>{ 0x07, 0x06, 0x04, 0x08, 0x01, 0x0c, 0x0d, 0x01, 0x00, 0x09, 0x0e, 0x0f, 0x04, 0x03, 0x08, 0x06, // out[0] 0x01, 0x07, 0x0b, 0x12, 0x15, 0x0f, 0x08, 0x09, 0x00, 0x13, 0x02, 0x01, 0x11, 0x0d, 0x07, 0x08, // out[1] 0x1a, 0x1b, 0x02, 0x10, 0x04, 0x19, 0x06, 0x17, 0x08, 0x09, 0x1c, 0x13, 0x1a, 0x0d, 0x0e, 0x0f, // out[2] 0x11, 0x01, 0x02, 0x10, 0x11, 0x01, 0x02, 0x10, 0x11, 0x01, 0x02, 0x10, 0x11, 0x01, 0x02, 0x10, // out[3] 0x00, 0x00, 0x00, 0x01, 0x11, 0x00, 0x00, 0x10, 0x00, 0x11, 0x01, 0x02, 0x02, 0x10, 0x00, 0x00, // out[4] 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x0c, 0x0c, 0x0c, 0x0c, // out[5] 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // out[6] 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, // out[7] 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, // out[8] 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, // out[9] })}}); registerTest( TestData{"shuffle_upcast", DataFilter::VECTOR_OPERATIONS, &test_shuffle_cl_string, "", "test_shuffle_upcast", {toBufferParameter(std::vector<uint8_t>{0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7}), toBufferParameter(std::vector<uint8_t>{4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3}), toBufferParameter(std::vector<uint8_t>(6 * 8))}, toDimensions(1), {checkParameterEquals(2, std::vector<uint8_t>{ 0x17, 0x17, 0x17, 0x17, 0x02, 0x17, 0x17, 0x17, // out[0] 0x42, 0x42, 0x42, 0x04, 0x42, 0x42, 0x42, 0x01, // out[1] 0x07, 0x13, 0x02, 0x13, 0x13, 0x03, 0x13, 0x13, // out[2] 0xFF, 0x05, 0xFF, 0x06, 0x01, 0xFF, 0xFF, 0x03, // out[3] 0x06, 0x05, 0x01, 0x03, 0x71, 0x71, 0x71, 0x71, // out[4] 0x03, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, // out[5] })}}); registerTest(TestData{"shuffle_sample3", DataFilter::VECTOR_OPERATIONS, &test_shuffle_cl_string, "", "sample_test_char3", {toBufferParameter(toRange<uint8_t>(0, 32)), toBufferParameter(std::vector<uint8_t>(3 * 32))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{0x01000000, 0x00020000, 0x03000000, 0x00040000, 0x00000005, 0x07000006, 0x00080000, 0x00000009, 0x000B000A, 0x0000000C, 0x0E00000D, 0x000F0000, 0x11001000, 0x00000000, 0x13000012, 0x15001400, 0x00160000, 0x17000000, 0x00000018, 0x001A0019, 0x001B0000, 0x001C0000, 0x0000001D, 0x00001F1E})}}); registerTest(TestData{"shuffle_sample4", DataFilter::VECTOR_OPERATIONS, &test_shuffle_cl_string, "", "sample_test_char4", {toBufferParameter(toRange<uint8_t>(0, 32)), toBufferParameter(std::vector<uint8_t>(4 * 32))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{0x00000000, 0x01000000, 0x00020000, 0x03000000, 0x00000400, 0x05000000, 0x00000600, 0x00000007, 0x00080000, 0x00000009, 0x00000A00, 0x0000000B, 0x0000000C, 0x0D000000, 0x00000E00, 0x0F000000, 0x00000010, 0x11000000, 0x00000012, 0x00130000, 0x00140000, 0x00150000, 0x00000016, 0x00170000, 0x00000018, 0x00190000, 0x00001A00, 0x001B0000, 0x1C000000, 0x001D0000, 0x1E000000, 0x00001F00})}}); registerTest(TestData{"struct", DataFilter::TYPE_HANDLING, &test_struct_cl_string, "", "test_struct", {toBufferParameter(std::vector<uint32_t>(20)), toBufferParameter(std::vector<uint32_t>(20))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0})}}); registerTest(TestData{"vector_arithmetic", DataFilter::NONE, &test_vector_cl_string, "", "test_arithm", {toScalarParameter(2.0f), toBufferParameter(toRange(1.0f, 17.0f)), toBufferParameter(std::vector<float>(16))}, toDimensions(1), {checkParameterEquals(2, toRange(3.0f, 19.0f))}}); registerTest(TestData{"copy_vector", DataFilter::NONE, &test_vector_cl_string, "", "test_copy", {toBufferParameter(toRange(1, 17)), toBufferParameter(std::vector<uint32_t>(32))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16})}}); registerTest(TestData{"vector_param", DataFilter::VECTOR_PARAM | DataFilter::USES_LONG, &test_vector_cl_string, "", "test_param", {toVectorParameter(toRange<uint8_t>(0, 16)), toVectorParameter(toRange<uint32_t>(0, 4)), toVectorParameter(toRange<uint64_t>(0, 2)), toBufferParameter(std::vector<uint32_t>(4))}, toDimensions(1), {checkParameterEquals(3, std::vector<uint32_t>{0x03020100, 0x07060505, 0x0B0A090B, 0x0F0E0D0F})}}); // XXX LLVM-SPIRV Translator does not support i3 type used for switch in test19 registerTest(TestData{"vectorization1", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test1", {toBufferParameter(std::vector<float>(1000)), toBufferParameter(std::vector<float>(1000))}, toDimensions(1), {checkParameterEquals(0, toRange(-0.0f, -1000.0f, -1.0f)), checkParameterEquals(1, toRange(-0.0f, -1000.0f, -1.0f))}}); registerTest(TestData{"vectorization2", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test2", {toBufferParameter(toRange(1.0f, 10.0f)), toBufferParameter(toRange(1.0f, 10.0f)), toScalarParameter(7.0f), toScalarParameter(1u), toScalarParameter(6u)}, toDimensions(1), {checkParameterEquals(0, std::vector<float>{1.0f, 18.0f, 30.0f, 44.0f, 60.0f, 78.0f, 7.0f, 8.0f, 9.0f})}}); registerTest(TestData{"vectorization3", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test3", {toBufferParameter(toRange(1.0f, 801.0f)), toBufferParameter(toRange(1.0f, 801.0f)), toScalarParameter(7.0f)}, toDimensions(1), {checkParameterEquals(0, std::vector<float>{8.0f, 18.0f, 30.0f, 44.0f, 60.0f, 78.0f, 98.0f, 120.0f, 144.0f})}}); registerTest( TestData{"vectorization4", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test4", {toBufferParameter(toRange<int>(0, 1024)), toBufferParameter(std::vector<uint32_t>(1))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{(1023 * 1024) / 2 + (5 * 1024)})}}); registerTest(TestData{"vectorization5", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test5", {toBufferParameter(std::vector<float>(1024))}, toDimensions(1), {checkParameterEquals(0, toRange(0.0f, 1024.0f))}}); registerTest( TestData{"vectorization6", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test6", {toBufferParameter(std::vector<int32_t>(1024, 2)), toBufferParameter(toRange(-510, 514))}, toDimensions(1), {checkParameterEquals(1, std::vector<int32_t>{512 * (2 + 5)})}}); auto vectorization7Result = toRange(1, 1025); vectorization7Result[0] = 0; registerTest(TestData{"vectorization7", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test7", {toBufferParameter(toRange(0, 1024))}, toDimensions(1), {checkParameterEquals(0, std::move(vectorization7Result))}}); registerTest( TestData{"vectorization8", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test8", {toBufferParameter(toRange<int>(0, 1024)), toBufferParameter(toRange<int>(0, 4096))}, toDimensions(1), {checkParameterEquals(0, std::vector<uint32_t>{0, 5, 10, 15, 20, 25, 30, 35, 40})}}); registerTest(TestData{"vectorization9", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test9", {toBufferParameter(toRange<int>(0, 4096)), toBufferParameter(toRange<int>(0, 4096))}, toDimensions(1), {checkParameterEquals(0, std::vector<uint32_t>{0, 1, 2, 3, 5, 5, 6, 7, 10, 9, 10, 11, 15, 13, 14, 15, 20})}}); registerTest(TestData{"vectorization10", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test10", {toBufferParameter(toRange<int>(0, 1024)), toBufferParameter(toRange<int>(0, 1024))}, toDimensions(1), {checkParameterEquals(0, std::vector<uint32_t>{0, 1, 2, 3, 8, 5, 6, 7, 16, 9, 10, 11, 24})}}); registerTest( TestData{"vectorization11", DataFilter::CONTROL_FLOW | DataFilter::TYPE_HANDLING | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test11", {toBufferParameter(toRange<int>(0, 256))}, toDimensions(1), {checkParameterEquals(0, std::vector<uint32_t>{100, 100, 100, 100, 100, 100, 100, 100, 100})}}); auto vectorization12Result = toRange<float>(0.0f + 42.0f, 1024.0f + 42.0f); // only elements 200 to 500 are modified std::fill_n(vectorization12Result.begin(), 200, 17.0f); std::fill_n(vectorization12Result.begin() + 500, vectorization12Result.size() - 500, 17.0f); registerTest(TestData{"vectorization12_partial", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test12", {toBufferParameter(std::vector<float>(1024, 17.0f)), toBufferParameter(toRange<float>(0.0f, 1024.0f)), toScalarParameter<float>(42.0f), toScalarParameter(200), toScalarParameter(500)}, toDimensions(1), {checkParameterEquals(0, std::move(vectorization12Result))}}); registerTest(TestData{"vectorization12", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test12", {toBufferParameter(std::vector<float>(1024, 17.0f)), toBufferParameter(toRange<float>(0.0f, 1024.0f)), toScalarParameter<float>(42.0f), toScalarParameter(0), toScalarParameter(1024)}, toDimensions(1), {checkParameterEquals(0, toRange<float>(0.0f + 42.0f, 1024.0f + 42.0f))}}); registerTest(TestData{"vectorization13", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test13", {toBufferParameter(toRange<int>(0, 1024)), toBufferParameter(std::vector<uint32_t>(1)), toScalarParameter(1000)}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{(999 * 1000) / 2 + (5 * 1000)})}}); // Tests less than a full loop iteration used registerTest(TestData{"vectorization13_partial", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test13", {toBufferParameter(toRange<int>(0, 5)), toBufferParameter(std::vector<uint32_t>(1)), toScalarParameter(5)}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{(4 * 5) / 2 + (5 * 5)})}}); registerTest(TestData{"vectorization14", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test14", {toBufferParameter(std::vector<int32_t>(1024, 2)), toBufferParameter(toRange(-510, 514)), toScalarParameter(1024)}, toDimensions(1), {checkParameterEquals(1, std::vector<int32_t>{512 * (2 + 5)})}}); // Tests less than a full loop iteration used registerTest(TestData{"vectorization14_partial", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test14", {toBufferParameter(std::vector<int32_t>(5, 2)), toBufferParameter(toRange(0, 5)), toScalarParameter(5)}, toDimensions(1), {checkParameterEquals(1, std::vector<int32_t>{2 * (2 + 5)})}}); registerTest(TestData{"vectorization15", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test15", {toBufferParameter(toRange<int>(0, 1024)), toBufferParameter(std::vector<uint32_t>(1))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{17 + (1023 * 1024) / 2 + (5 * 1024)})}}); registerTest(TestData{"vectorization16", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test16", {toBufferParameter(toRange<int>(0, 1024)), toBufferParameter(std::vector<uint32_t>(1))}, toDimensions(1), {checkParameterEquals(1, std::vector<float>{(1023 * 1024) / 2 + (5 * 1024)})}}); registerTest(TestData{"vectorization17", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test17", {toBufferParameter(toRange<int>(0, 1024)), toBufferParameter(std::vector<uint32_t>(1))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{267264})}}); registerTest(TestData{"vectorization18", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test18", {toBufferParameter(toRange<int>(0, 1024)), toBufferParameter(std::vector<uint32_t>(6))}, toDimensions(3, 1, 1, 2), {checkParameterEquals( 1, std::vector<uint32_t>{5 * 1024, (1023 * 1024) / 2, 5 * 1024, 5 * 1024, (1023 * 1024) / 2, 5 * 1024})}}); registerTest(TestData{"vectorization19", DataFilter::CONTROL_FLOW | DataFilter::SPIRV_DISABLED, &test_vectorization_cl_string, "", "test19", {toBufferParameter(toRange<int>(0, 1024)), toBufferParameter(std::vector<uint32_t>(1))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{324088})}}); registerTest(TestData{"work_item", DataFilter::WORK_GROUP, &test_work_item_cl_string, "", "test_work_item", {toBufferParameter(std::vector<uint32_t>(24 * 8 * 4, 0x42))}, toDimensions(8, 1, 1, 4, 1, 1), {checkParameterEquals(0, std::vector<uint32_t>{ 3, 8 * 4, 1, 1, 0, 0, 0, 0, 0, 0, 4, 1, 1, 0, 0, 0, 8, 1, 1, 0, 0, 0, 0x43, 0x42, // work-item (0, 0) 3, 8 * 4, 1, 1, 1, 0, 0, 0, 0, 0, 4, 1, 1, 0, 0, 0, 8, 1, 1, 1, 0, 0, 0x43, 0x42, // work-item (0, 1) 3, 8 * 4, 1, 1, 2, 0, 0, 0, 0, 0, 4, 1, 1, 0, 0, 0, 8, 1, 1, 2, 0, 0, 0x43, 0x42, // work-item (0, 2) 3, 8 * 4, 1, 1, 3, 0, 0, 0, 0, 0, 4, 1, 1, 0, 0, 0, 8, 1, 1, 3, 0, 0, 0x43, 0x42, // work-item (0, 3) 3, 8 * 4, 1, 1, 4, 0, 0, 0, 0, 0, 4, 1, 1, 0, 0, 0, 8, 1, 1, 4, 0, 0, 0x43, 0x42, // work-item (0, 4) 3, 8 * 4, 1, 1, 5, 0, 0, 0, 0, 0, 4, 1, 1, 0, 0, 0, 8, 1, 1, 5, 0, 0, 0x43, 0x42, // work-item (0, 5) 3, 8 * 4, 1, 1, 6, 0, 0, 0, 0, 0, 4, 1, 1, 0, 0, 0, 8, 1, 1, 6, 0, 0, 0x43, 0x42, // work-item (0, 6) 3, 8 * 4, 1, 1, 7, 0, 0, 0, 0, 0, 4, 1, 1, 0, 0, 0, 8, 1, 1, 7, 0, 0, 0x43, 0x42, // work-item (0, 7) 3, 8 * 4, 1, 1, 8, 0, 0, 0, 0, 0, 4, 1, 1, 1, 0, 0, 8, 1, 1, 0, 0, 0, 0x43, 0x42, // work-item (1, 0) 3, 8 * 4, 1, 1, 9, 0, 0, 0, 0, 0, 4, 1, 1, 1, 0, 0, 8, 1, 1, 1, 0, 0, 0x43, 0x42, // work-item (1, 1) 3, 8 * 4, 1, 1, 10, 0, 0, 0, 0, 0, 4, 1, 1, 1, 0, 0, 8, 1, 1, 2, 0, 0, 0x43, 0x42, // work-item (1, 2) 3, 8 * 4, 1, 1, 11, 0, 0, 0, 0, 0, 4, 1, 1, 1, 0, 0, 8, 1, 1, 3, 0, 0, 0x43, 0x42, // work-item (1, 3) 3, 8 * 4, 1, 1, 12, 0, 0, 0, 0, 0, 4, 1, 1, 1, 0, 0, 8, 1, 1, 4, 0, 0, 0x43, 0x42, // work-item (1, 4) 3, 8 * 4, 1, 1, 13, 0, 0, 0, 0, 0, 4, 1, 1, 1, 0, 0, 8, 1, 1, 5, 0, 0, 0x43, 0x42, // work-item (1, 5) 3, 8 * 4, 1, 1, 14, 0, 0, 0, 0, 0, 4, 1, 1, 1, 0, 0, 8, 1, 1, 6, 0, 0, 0x43, 0x42, // work-item (1, 6) 3, 8 * 4, 1, 1, 15, 0, 0, 0, 0, 0, 4, 1, 1, 1, 0, 0, 8, 1, 1, 7, 0, 0, 0x43, 0x42, // work-item (1, 7) 3, 8 * 4, 1, 1, 16, 0, 0, 0, 0, 0, 4, 1, 1, 2, 0, 0, 8, 1, 1, 0, 0, 0, 0x43, 0x42, // work-item (2, 0) 3, 8 * 4, 1, 1, 17, 0, 0, 0, 0, 0, 4, 1, 1, 2, 0, 0, 8, 1, 1, 1, 0, 0, 0x43, 0x42, // work-item (2, 1) 3, 8 * 4, 1, 1, 18, 0, 0, 0, 0, 0, 4, 1, 1, 2, 0, 0, 8, 1, 1, 2, 0, 0, 0x43, 0x42, // work-item (2, 2) 3, 8 * 4, 1, 1, 19, 0, 0, 0, 0, 0, 4, 1, 1, 2, 0, 0, 8, 1, 1, 3, 0, 0, 0x43, 0x42, // work-item (2, 3) 3, 8 * 4, 1, 1, 20, 0, 0, 0, 0, 0, 4, 1, 1, 2, 0, 0, 8, 1, 1, 4, 0, 0, 0x43, 0x42, // work-item (2, 4) 3, 8 * 4, 1, 1, 21, 0, 0, 0, 0, 0, 4, 1, 1, 2, 0, 0, 8, 1, 1, 5, 0, 0, 0x43, 0x42, // work-item (2, 5) 3, 8 * 4, 1, 1, 22, 0, 0, 0, 0, 0, 4, 1, 1, 2, 0, 0, 8, 1, 1, 6, 0, 0, 0x43, 0x42, // work-item (2, 6) 3, 8 * 4, 1, 1, 23, 0, 0, 0, 0, 0, 4, 1, 1, 2, 0, 0, 8, 1, 1, 7, 0, 0, 0x43, 0x42, // work-item (2, 7) 3, 8 * 4, 1, 1, 24, 0, 0, 0, 0, 0, 4, 1, 1, 3, 0, 0, 8, 1, 1, 0, 0, 0, 0x43, 0x42, // work-item (3, 0) 3, 8 * 4, 1, 1, 25, 0, 0, 0, 0, 0, 4, 1, 1, 3, 0, 0, 8, 1, 1, 1, 0, 0, 0x43, 0x42, // work-item (3, 1) 3, 8 * 4, 1, 1, 26, 0, 0, 0, 0, 0, 4, 1, 1, 3, 0, 0, 8, 1, 1, 2, 0, 0, 0x43, 0x42, // work-item (3, 2) 3, 8 * 4, 1, 1, 27, 0, 0, 0, 0, 0, 4, 1, 1, 3, 0, 0, 8, 1, 1, 3, 0, 0, 0x43, 0x42, // work-item (3, 3) 3, 8 * 4, 1, 1, 28, 0, 0, 0, 0, 0, 4, 1, 1, 3, 0, 0, 8, 1, 1, 4, 0, 0, 0x43, 0x42, // work-item (3, 4) 3, 8 * 4, 1, 1, 29, 0, 0, 0, 0, 0, 4, 1, 1, 3, 0, 0, 8, 1, 1, 5, 0, 0, 0x43, 0x42, // work-item (3, 5) 3, 8 * 4, 1, 1, 30, 0, 0, 0, 0, 0, 4, 1, 1, 3, 0, 0, 8, 1, 1, 6, 0, 0, 0x43, 0x42, // work-item (3, 6) 3, 8 * 4, 1, 1, 31, 0, 0, 0, 0, 0, 4, 1, 1, 3, 0, 0, 8, 1, 1, 7, 0, 0, 0x43, 0x42, // work-item (3, 7) })}}); registerTest(TestData{"work_item_global_offset", DataFilter::WORK_GROUP, &test_work_item_cl_string, "", "test_work_item", {toBufferParameter(std::vector<uint32_t>(24 * 2 * 2, 0x42))}, toDimensions(2, 1, 1, 2, 1, 1, 0, 2, 3), {checkParameterEquals(0, std::vector<uint32_t>{ 3, 2 * 2, 1, 1, 0, 2, 3, 0, 2, 3, 2, 1, 1, 0, 0, 0, 2, 1, 1, 0, 0, 0, 0x43, 0x42, // work-item (0, 0) 3, 2 * 2, 1, 1, 1, 2, 3, 0, 2, 3, 2, 1, 1, 0, 0, 0, 2, 1, 1, 1, 0, 0, 0x43, 0x42, // work-item (0, 1) 3, 2 * 2, 1, 1, 2, 2, 3, 0, 2, 3, 2, 1, 1, 1, 0, 0, 2, 1, 1, 0, 0, 0, 0x43, 0x42, // work-item (1, 0) 3, 2 * 2, 1, 1, 3, 2, 3, 0, 2, 3, 2, 1, 1, 1, 0, 0, 2, 1, 1, 1, 0, 0, 0x43, 0x42, // work-item (1, 1) })}}); //// // Bug Regression Tests //// // TODO add for all/most bugs/ files registerTest(TestData{"bug_local_memory_dot3", DataFilter::WORK_GROUP, &bugs_30_local_memory_cl_string, "", "dot3", {toBufferParameter(toRange<float>(0.0f, 20.0f)), toBufferParameter(std::vector<float>{0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f}), toBufferParameter(std::vector<float>(24)), toBufferParameter(std::vector<float>(16))}, toDimensions(10, 1, 1, 2, 1, 1), {checkParameter<CompareULP<1>>(2, std::vector<float>{0.1f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 2.1f, 1.1f, 1.2f, 1.3f, 1.4f, 1.5f, 1.6f, 1.7f, 1.8f, 1.9f})}}); registerTest(TestData{"bug_local_memory_dot3_local", DataFilter::WORK_GROUP, &bugs_30_local_memory_cl_string, "", "dot3_local", {toBufferParameter(toRange<float>(0.0f, 20.0f)), toBufferParameter(std::vector<float>{0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f}), toBufferParameter(std::vector<float>(24))}, toDimensions(10, 1, 1, 2, 1, 1), {checkParameter<CompareULP<1>>(2, std::vector<float>{0.1f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 2.1f, 1.1f, 1.2f, 1.3f, 1.4f, 1.5f, 1.6f, 1.7f, 1.8f, 1.9f})}}); registerTest(TestData{"bug_float_add_redundancy", DataFilter::NONE, &bugs_33_floating_point_folding_cl_string, "", "add_redundancy", {toBufferParameter(std::vector<float>{5.0f})}, toDimensions(1), {checkParameterEquals(0, std::vector<float>{5.0f})}}); registerTest(TestData{"bug_float_mul_redundancy", DataFilter::NONE, &bugs_33_floating_point_folding_cl_string, "", "mul_redundancy", {toBufferParameter(std::vector<float>{5.0f})}, toDimensions(1), {checkParameterEquals(0, std::vector<float>{0.0f})}}); registerTest(TestData{"bug_read_write_memory", DataFilter::NONE, &bugs_vc4cl_27_wrong_result_cl_string, "", "hello", {toBufferParameter(toRange<float>(-15.0f, 15.0f))}, toDimensions(10, 1, 1, 3, 1, 1), {checkParameterEquals(0, toRange<float>(-30.0f, 30.0f, 2.0f))}}); registerTest(TestData{"bug_const_assign", DataFilter::NONE, &bugs_54_invalid_results_cl_string, "", "sum", {toBufferParameter(std::vector<float>(9))}, toDimensions(3, 1, 1, 3, 1, 1), {checkParameterEquals(0, std::vector<float>{1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f})}}); //// // OpenCL CTS Tests //// // XXX passes for SPIR-V locally, but fails in CI registerTest(TestData{"OpenCL_CTS_async_copy", DataFilter::ASYNC_BARRIER | DataFilter::SPIRV_DISABLED, &OpenCL_CTS_async_copy_global_to_local_cl_string, "", "test_async_copy_global_to_local", {toBufferParameter(toRange<uint8_t>(0, 2 * 4 * 3 * 8)), toBufferParameter(std::vector<uint8_t>(2 * 4 * 3 * 8)), toBufferParameter(std::vector<uint8_t>(4 * 3 * 8)), toScalarParameter(4 * 3), toScalarParameter(3)}, toDimensions(4, 1, 1, 2, 1, 1), {checkParameterEquals(1, toRange<uint8_t>(0, 2 * 4 * 3 * 8))}}); registerTest( TestData{"OpenCL_CTS_barrier", DataFilter::ASYNC_BARRIER, &OpenCL_CTS_barrier_cl_string, "", "compute_sum", {toBufferParameter(toRange<uint32_t>(0, 24)), toScalarParameter(23), toBufferParameter(std::vector<uint32_t>(16)), toBufferParameter(std::vector<uint32_t>(1))}, toDimensions(11), {checkParameterEquals(3, std::vector<uint32_t>{253})}}); registerTest(TestData{"OpenCL_CTS_clamp", DataFilter::NONE, &OpenCL_CTS_clamp_cl_string, "", "test_clamp", {toBufferParameter(std::vector<float>{17.0f, 0.0f, 3.0f}), toBufferParameter(std::vector<float>{1.0f, 1.0f, 1.0f}), toBufferParameter(std::vector<float>{5.0f, 5.0f, 5.0f}), toBufferParameter(std::vector<float>(3))}, toDimensions(3), {checkParameterEquals(3, std::vector<float>{5.0f, 1.0f, 3.0f})}}); registerTest( TestData{"OpenCL_CTS_constant", DataFilter::NONE, &OpenCL_CTS_constant_cl_string, "", "constant_kernel", {toBufferParameter(std::vector<float>(32)), toBufferParameter(toRange<float>(0.0f, 32.0f)), toBufferParameter(toRange<int32_t>(0, 32))}, calculateDimensions(32, 1), {checkParameterEquals( 0, transform<float>(toRange<float>(0.0f, 32.0f), [](float f) -> float { return f * f; }))}}); registerTest(TestData{"OpenCL_CTS_constant_loop", DataFilter::NONE, &OpenCL_CTS_constant_cl_string, "", "loop_constant_kernel", {toBufferParameter(std::vector<float>(32)), toBufferParameter(toRange<float>(0.0f, 32.0f)), toScalarParameter(2)}, calculateDimensions(32, 1), {checkParameterEquals(0, std::vector<float>(32, 0.0f + 3.0f))}}); registerTest(TestData{"OpenCL_CTS_cross", DataFilter::VECTOR_OPERATIONS | DataFilter::FLOAT_ARITHMETIC, &OpenCL_CTS_cross_product_cl_string, "", "test_cross", {toBufferParameter(std::vector<float>{1.0f, 2.0f, 3.0f}), toBufferParameter(std::vector<float>{3.0f, 4.0f, 5.0f}), toBufferParameter(std::vector<float>(3))}, toDimensions(1), {checkParameterEquals(2, std::vector<float>{-2.0f, 4.0f, -2.0f})}}); registerTest(TestData{"OpenCL_CTS_add_sat_int3", DataFilter::VECTOR_OPERATIONS | DataFilter::INT_ARITHMETIC, &OpenCL_CTS_integer_add_sat_cl_string, "", "test_add_sat_int3", {toBufferParameter(std::vector<int32_t>{std::numeric_limits<int>::min(), std::numeric_limits<int>::max(), std::numeric_limits<int>::min(), std::numeric_limits<int>::max(), static_cast<int32_t>(0x97c4aa2f), static_cast<int32_t>(0xa91a356a)}), toBufferParameter(std::vector<int>{-1, 1, std::numeric_limits<int>::min(), std::numeric_limits<int>::max(), static_cast<int32_t>(0xa91a356a), static_cast<int32_t>(0xa91a356a)}), toBufferParameter(std::vector<int>(6))}, toDimensions(2), {checkParameterEquals(2, std::vector<int>{std::numeric_limits<int>::min(), std::numeric_limits<int>::max(), std::numeric_limits<int>::min(), std::numeric_limits<int>::max(), std::numeric_limits<int>::min(), std::numeric_limits<int>::min()})}}); registerTest(TestData{"OpenCL_CTS_add_sat_ushort4", DataFilter::VECTOR_OPERATIONS | DataFilter::INT_ARITHMETIC, &OpenCL_CTS_integer_add_sat_cl_string, "", "test_add_sat_ushort4", {toBufferParameter(std::vector<uint16_t>{std::numeric_limits<uint16_t>::min(), std::numeric_limits<uint16_t>::max(), std::numeric_limits<uint16_t>::min(), std::numeric_limits<uint16_t>::max(), 0x2F, 0x8C7F, 0x8C7F, 0x1902}), toBufferParameter( std::vector<uint16_t>{std::numeric_limits<uint16_t>::max(), 1, std::numeric_limits<uint16_t>::min(), std::numeric_limits<uint16_t>::max(), 0x6A, 0x8C7F, 0x1902, 0x1902}), toBufferParameter(std::vector<uint16_t>(8))}, toDimensions(2), {checkParameterEquals(2, std::vector<uint16_t>{std::numeric_limits<uint16_t>::max(), std::numeric_limits<uint16_t>::max(), std::numeric_limits<uint16_t>::min(), std::numeric_limits<uint16_t>::max(), 0x99, std::numeric_limits<uint16_t>::max(), 0xA581, 0x3204})}}); registerTest( TestData{"OpenCL_CTS_local_kernel_scope", DataFilter::MEMORY_ACCESS, &OpenCL_CTS_local_kernel_scope_cl_string, "", "test", {toBufferParameter(toRange<uint32_t>(0, 64)), toBufferParameter(std::vector<uint32_t>(8))}, toDimensions(8, 1, 1, 8, 1, 1), {checkParameterEquals(1, std::vector<uint32_t>{7, 15, 23, 31, 39, 47, 55, 63})}}); registerTest(TestData{"OpenCL_CTS_min_max_constant_args", DataFilter::CORNER_CASES, &OpenCL_CTS_min_max_constant_args_cl_string, "", "sample_test", // has 64 parameters, 63 inputs and 1 output {toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(toRange(0, 8)), toBufferParameter(std::vector<uint32_t>(8))}, toDimensions(4, 1, 1, 2), // dest[gid] = sum(src0[gid], src1[gid], ..., src63[gid]) {checkParameterEquals( 63, std::vector<uint32_t>{0 * 63, 1 * 63, 2 * 63, 3 * 63, 4 * 63, 5 * 63, 6 * 63, 7 * 63})}}); registerTest(TestData{"OpenCL_CTS_pointer_cast", DataFilter::CORNER_CASES, &OpenCL_CTS_pointer_cast_cl_string, "", "test_pointer_cast", {toBufferParameter(std::vector<uint8_t>{4, 3, 2, 1}), toBufferParameter(std::vector<uint32_t>(1))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{0x01020304})}}); registerTest(TestData{"OpenCL_CTS_select_short", DataFilter::CORNER_CASES, &OpenCL_CTS_test_select_cl_string, "", "select_short_short", {toBufferParameter(std::vector<int16_t>(8, 0x42)), toBufferParameter(toRange<int16_t>(0, 8)), toBufferParameter(toRange<int16_t>(8, 16)), /* scalar has different comparison (comp ==/!=0) then vector versions (cmp </>= 0) */ toBufferParameter(std::vector<int16_t>{0, 0, 42, 42, 0, 42, 42, 0})}, toDimensions(8), {checkParameterEquals(0, std::vector<int16_t>{0, 1, 10, 11, 4, 13, 14, 7})}}); registerTest(TestData{"OpenCL_CTS_select_uint2", DataFilter::CORNER_CASES, &OpenCL_CTS_test_select_cl_string, "", "select_uint2_int2", {toBufferParameter(std::vector<uint32_t>(8, 0x42)), toBufferParameter(toRange<uint32_t>(0, 8)), toBufferParameter(toRange<uint32_t>(8, 16)), toBufferParameter(std::vector<int32_t>{1, 1, -1, -1, 1, -1, -1, 1})}, calculateDimensions(8, 2), {checkParameterEquals(0, std::vector<uint32_t>{0, 1, 10, 11, 4, 13, 14, 7})}}); registerTest(TestData{"OpenCL_CTS_select_int3", DataFilter::CORNER_CASES, &OpenCL_CTS_test_select_cl_string, "", "select_int3_uint3", {toBufferParameter(std::vector<int32_t>(8, 0x42)), toBufferParameter(toRange<int32_t>(0, 8)), toBufferParameter(toRange<int32_t>(8, 16)), toBufferParameter(std::vector<int32_t>{1, 1, -1, -1, 1, -1, -1, 1})}, calculateDimensions(8, 3), {checkParameterEquals(0, std::vector<int32_t>{0, 1, 10, 11, 4, 13, 14, 7})}}); registerTest(TestData{"OpenCL_CTS_select_char4", DataFilter::CORNER_CASES, &OpenCL_CTS_test_select_cl_string, "", "select_char4_char4", {toBufferParameter(std::vector<int8_t>(8, 0x42)), toBufferParameter(toRange<int8_t>(0, 8)), toBufferParameter(toRange<int8_t>(8, 16)), toBufferParameter(std::vector<int8_t>{1, 1, -1, -1, 1, -1, -1, 1})}, calculateDimensions(8, 4), {checkParameterEquals(0, std::vector<int8_t>{0, 1, 10, 11, 4, 13, 14, 7})}}); registerTest(TestData{"OpenCL_CTS_sub_buffers_read", DataFilter::NONE, &OpenCL_CTS_sub_buffers_read_write_cl_string, "", "readTest", {toBufferParameter(std::vector<uint8_t>{4, 3, 2, 1, 8, 7, 6, 5}), toScalarParameter<int8_t>(0x10)}, toDimensions(4, 1, 1, 2), {checkParameterEquals(0, std::vector<uint8_t>{20, 19, 18, 17, 24, 23, 22, 21})}}); registerTest(TestData{"OpenCL_CTS_sub_sat", DataFilter::INT_ARITHMETIC, &OpenCL_CTS_sub_sat_cl_string, "", "test_sub_sat_int", {toBufferParameter(std::vector<int32_t>{std::numeric_limits<int>::min(), std::numeric_limits<int>::max(), std::numeric_limits<int>::min(), std::numeric_limits<int>::max(), static_cast<int32_t>(0x8c7f0aac)}), toBufferParameter(std::vector<int32_t>{1, -1, std::numeric_limits<int>::max(), std::numeric_limits<int>::min(), static_cast<int32_t>(0x1902f8c8)}), toBufferParameter(std::vector<int32_t>(5))}, toDimensions(5), {checkParameterEquals(2, std::vector<int32_t>{std::numeric_limits<int>::min(), std::numeric_limits<int>::max(), std::numeric_limits<int>::min(), std::numeric_limits<int>::max(), std::numeric_limits<int>::min()})}}); registerTest(TestData{"OpenCL_CTS_uchar_compare", DataFilter::COMPARISONS, &OpenCL_CTS_uchar_compare_cl_string, "", "test_select", {toBufferParameter(std::vector<uint8_t>{4, 3, 2, 1}), toBufferParameter(std::vector<uint8_t>{1, 3, 2, 4}), toBufferParameter(std::vector<uint8_t>(4))}, toDimensions(1), {checkParameterEquals(2, std::vector<uint8_t>{1, 3, 2, 4})}}); //// // Boost Compute Tests //// registerTest(TestData{"boost_adjacent_find", DataFilter::NONE, &boost_compute_adjacent_find_cl_string, "", "serial_adjacent_find", {toScalarParameter(16u), toBufferParameter(std::vector<uint32_t>(2)), toBufferParameter(std::vector<uint32_t>{0, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10, 11, 11, 12, 13})}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{7})}}); registerTest(TestData{"boost_adjacent_find_with_atomics", DataFilter::ATOMIC_FUNCTIONS, &boost_compute_adjacent_find_cl_string, "", "adjacent_find_with_atomics", {toBufferParameter(std::vector<uint32_t>{0xFFFFFFFFu}), toBufferParameter(std::vector<uint32_t>{0, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10, 11, 11, 12, 13, 0})}, toDimensions(8, 1, 1, 2, 1, 1), {checkParameterEquals(0, std::vector<uint32_t>{7})}}); registerTest(TestData{"boost_find_extrema_min", DataFilter::NONE, &boost_compute_test_extrema_cl_string, "", "find_extrema_min_max", {toBufferParameter(std::vector<uint32_t>{17, 15, 45, 65, 3, 2, 7, 9, 11, 1300, 12, 6, 8, 200}), toBufferParameter(std::vector<uint32_t>(1))}, toDimensions(7, 1, 1, 2, 1, 1), {checkParameterEquals(1, std::vector<uint32_t>{5})}}); registerTest(TestData{"boost_find_extrema_max", DataFilter::NONE, &boost_compute_test_extrema_cl_string, "-DBOOST_COMPUTE_FIND_MAXIMUM=1", "find_extrema_min_max", {toBufferParameter(std::vector<uint32_t>{17, 15, 45, 65, 3, 2, 7, 9, 11, 1300, 12, 6, 8, 200}), toBufferParameter(std::vector<uint32_t>(1))}, toDimensions(7, 1, 1, 2, 1, 1), {checkParameterEquals(1, std::vector<uint32_t>{9})}}); registerTest(TestData{"boost_find_extrema_on_cpu_min", DataFilter::NONE, &boost_compute_test_extrema_cl_string, "", "find_extrema_on_cpu_min_max", {toScalarParameter(15), toBufferParameter(std::vector<uint32_t>(4)), toBufferParameter(std::vector<uint32_t>(4)), toBufferParameter(std::vector<uint32_t>{17, 15, 45, 65, 3, 2, 7, 9, 11, 1300, 12, 6, 8, 200, 65, 0})}, toDimensions(2, 1, 1, 2, 1, 1), {checkParameterEquals(1, std::vector<uint32_t>{15, 2, 6, 8}), checkParameterEquals(2, std::vector<uint32_t>{1, 5, 11, 12})}}); registerTest(TestData{"boost_find_extrema_on_cpu_max", DataFilter::NONE, &boost_compute_test_extrema_cl_string, "-DBOOST_COMPUTE_FIND_MAXIMUM=1", "find_extrema_on_cpu_min_max", {toScalarParameter(15), toBufferParameter(std::vector<uint32_t>(4)), toBufferParameter(std::vector<uint32_t>(4)), toBufferParameter(std::vector<uint32_t>{17, 15, 45, 65, 3, 2, 7, 9, 11, 1300, 12, 6, 8, 200, 65, 0})}, toDimensions(2, 1, 1, 2, 1, 1), {checkParameterEquals(1, std::vector<uint32_t>{65, 9, 1300, 200}), checkParameterEquals(2, std::vector<uint32_t>{3, 7, 9, 13})}}); registerTest(TestData{"boost_functional_popcount_long", DataFilter::USES_LONG, &boost_compute_test_functional_popcount_cl_string, "", "copy", {toBufferParameter(std::vector<uint32_t>(7, 0x42)), toBufferParameter( std::vector<uint64_t>{0, 1, 17, 0x200000000001, 0x100000F00000, 0xFFFFFFFFFFFFFFFF, 0x34000000001}), toScalarParameter(7)}, toDimensions(8), {checkParameterEquals(0, std::vector<uint32_t>{0, 1, 2, 2, 5, 64, 4})}}); registerTest(TestData{"boost_functional_popcount_int", DataFilter::NONE, &boost_compute_test_functional_popcount_cl_string, "", "popcount_uint", {toBufferParameter(std::vector<uint32_t>(6, 0x42)), toBufferParameter(std::vector<uint32_t>{0, 1, 17, 0x20001, 0x100F000, 0xFFFFFFFF}), toScalarParameter(6)}, toDimensions(8), {checkParameterEquals(0, std::vector<uint32_t>{0, 1, 2, 2, 5, 32})}}); registerTest(TestData{"boost_initial_reduce", DataFilter::CONTROL_FLOW | DataFilter::ASYNC_BARRIER | DataFilter::USES_LONG, &boost_compute_initial_reduce_cl_string, "", "initial_reduce", {toScalarParameter(static_cast<uint32_t>(32 * sizeof(uint32_t))), toBufferParameter(std::vector<uint64_t>(2)), toBufferParameter(std::vector<uint32_t>{ 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0})}, toDimensions(8, 1, 1, 2, 1, 1), {checkParameterEquals(1, std::vector<uint32_t>{8, 0, 7, 0})}}); // TODO has random result mismatch errors registerTest( TestData{"boost_insertion_sort", DataFilter::CONTROL_FLOW | DataFilter::USES_LONG | DataFilter::DISABLED, &boost_compute_test_insertion_sort_cl_string, "", "serial_insertion_sort", {toBufferParameter(std::vector<uint64_t>(16)), toScalarParameter(16u), toBufferParameter(std::vector<uint64_t>{1, 0, 2, 15, 14, 3, 11, 12, 4, 8, 7, 5, 10, 6, 9, 13})}, toDimensions(1), {checkParameterEquals(2, std::vector<uint64_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15})}}); registerTest(TestData{"boost_insertion_sort_short", DataFilter::CONTROL_FLOW, &boost_compute_test_insertion_sort_cl_string, "", "serial_insertion_sort_short", {toBufferParameter(std::vector<uint32_t>(8)), toScalarParameter(16u), toBufferParameter( std::vector<uint16_t>{0x1, 0x0, 0x2, 0xF, 0x3, 0xE, 0xC, 0xB, 0x4, 0x8, 0x7, 0x5, 0xA, 0x6, 0x9, 0xD})}, toDimensions(1), {checkParameterEquals(2, std::vector<uint16_t>{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF})}}); registerTest(TestData{"boost_serial_merge", DataFilter::CONTROL_FLOW | DataFilter::TYPE_HANDLING, &boost_compute_test_merge_cl_string, "", "serial_merge", {toScalarParameter(16u), toScalarParameter(16u), toBufferParameter(std::vector<uint32_t>{1, 0, 3, 0, 5, 0, 7, 0, 9, 0, 11, 0, 13, 0, 15, 0, 17, 0, 19, 0, 21, 0, 23, 0, 25, 0, 27, 0, 29, 0, 31, 0}), toBufferParameter(std::vector<uint32_t>{0, 0, 2, 0, 4, 0, 6, 0, 8, 0, 10, 0, 12, 0, 14, 0, 16, 0, 18, 0, 20, 0, 22, 0, 24, 0, 26, 0, 28, 0, 30, 0}), toBufferParameter(std::vector<uint32_t>(64))}, toDimensions(1), {checkParameterEquals(4, std::vector<uint32_t>{0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 9, 0, 10, 0, 11, 0, 12, 0, 13, 0, 14, 0, 15, 0, 16, 0, 17, 0, 18, 0, 19, 0, 20, 0, 21, 0, 22, 0, 23, 0, 24, 0, 25, 0, 26, 0, 27, 0, 28, 0, 29, 0, 30, 0, 31, 0})}}); registerTest(TestData{"boost_reduce", DataFilter::CONTROL_FLOW | DataFilter::ASYNC_BARRIER, &boost_compute_test_reduce_cl_string, "", "reduce", {toBufferParameter(std::vector<uint32_t>{1, 5, 9, 13, 17}), toScalarParameter(0u), toScalarParameter(5u), toBufferParameter(std::vector<uint32_t>(1)), toScalarParameter(0u)}, toDimensions(8), {checkParameterEquals(3, std::vector<uint32_t>{1 + 5 + 9 + 13 + 17})}}); registerTest(TestData{"boost_fibonacci", DataFilter::INT_ARITHMETIC | DataFilter::FLOAT_ARITHMETIC, &boost_compute_test_transform2_cl_string, "", "copy", {toBufferParameter(std::vector<uint32_t>(25, 0x42)), toScalarParameter(25u)}, toDimensions(8), {checkParameterEquals(0, std::vector<uint32_t>{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368})}}); //// // Application Tests //// // TODO fails on CI, but works locally... registerTest( TestData{"clNN_upscale", DataFilter::COMPLEX_KERNEL | DataFilter::INT_ARITHMETIC | DataFilter::WORK_GROUP, &clNN_SpatialUpSamplingNearest_cl_string, "", "upscale", {toBufferParameter(toRange<float>(0.0f, 8.0f)), toScalarParameter(0), toBufferParameter(std::vector<float>(24, 42.0f)), toScalarParameter(0), toScalarParameter(19), toScalarParameter(2), toScalarParameter(2), toScalarParameter(2), toScalarParameter(2)}, toDimensions(8, 1, 1, 3, 1, 1), {checkParameterEquals( 2, std::vector<float>{0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 42, 42, 42, 42, 42})}}); registerTest(TestData{"single_element_struct", DataFilter::TYPE_HANDLING, &pocl_test_structs_as_args_cl_string, "", "test_single", {toVectorParameter(std::vector<uint32_t>{0x01000102}), toBufferParameter(std::vector<uint32_t>(1))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{0x01000102})}}); registerTest( TestData{"two_element_struct", DataFilter::TYPE_HANDLING, &pocl_test_structs_as_args_cl_string, "", "test_pair", {toVectorParameter(std::vector<uint32_t>{0x01010101, 0x23232323, 0x45454545, 0x67676767}), toBufferParameter(std::vector<uint32_t>(2))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{0x01010101, 0x45454545})}}); registerTest(TestData{"multi_element_struct", DataFilter::TYPE_HANDLING, &pocl_test_structs_as_args_cl_string, "", "test_kernel", {toVectorParameter(std::vector<uint32_t>{0x01001001, 0x02002002, 0x03003003, 0x04004004, 0x05005005, 0xDEADDEAD, 0x06006006, 0x07007007, 0x48008008, 0x09009009, 0x0A00A00A, 0x0B00B00B}), toBufferParameter(std::vector<uint32_t>(10))}, toDimensions(1), {checkParameterEquals(1, std::vector<uint32_t>{ 0x01001001, 0x02002002, 0x03003003, 0x05, 0x06006006, 131584, 0xFFFF9009, 0x0A00A00A, 48, 8})}}); registerTest(TestData{"pi", DataFilter::NONE, &HandsOnOpenCL_pi_ocl_cl_string, "", "pi", {toScalarParameter(32), toScalarParameter(1.0f / 1024.0f), toBufferParameter(std::vector<uint32_t>(8)), toBufferParameter(std::vector<uint32_t>(4))}, toDimensions(8, 1, 1, 4, 1, 1), {checkParameter<float>(3, 4, checkPiSum)}}); registerTest(TestData{"mmul", DataFilter::CONTROL_FLOW, &HandsOnOpenCL_matmul_cl_string, "", "mmul", {toScalarParameter(4), toBufferParameter(std::vector<float>(4 * 4, 3.0f)), toBufferParameter(std::vector<float>(4 * 4, 5.0f)), toBufferParameter(std::vector<float>(4 * 4, 0.0f))}, toDimensions(2, 2, 1, 2, 2, 1), {checkParameterEquals(3, std::vector<float>(4 * 4, 4 * 3.0f * 5.0f))}}); // TODO requires# include headers registerTest(TestData{"histogram_1C", DataFilter::DISABLED | DataFilter::ATOMIC_FUNCTIONS | DataFilter::ASYNC_BARRIER | DataFilter::COMPLEX_KERNEL, &OpenCLIPP_Histogram_cl_string, "", "histogram_1C", {toBufferParameter( std::vector<uint8_t>{0x02, 0x01, 0x00, 0x01, 0x01, 0x01, 0x06, 0x01, 0x05, 0x04, 0x03, 0x02}), toBufferParameter(std::vector<uint32_t>(8)), toScalarParameter(4)}, toDimensions(4, 3), /* the value is the count of bytes <= the position */ {checkParameterEquals(1, std::vector<uint32_t>{1, 6, 8, 9, 10, 11, 12, 12})}}); registerTest(TestData{"VectorAdd", DataFilter::WORK_GROUP, &NVIDIA_VectorAdd_cl_string, "", "VectorAdd", {toBufferParameter(toRange<float>(0.0f, 18.0f)), toBufferParameter(toRange<float>(0.0f, 18.0f)), toBufferParameter(std::vector<uint32_t>(20)), toScalarParameter(16u)}, toDimensions(12, 1, 1, 2, 1, 1), {checkParameterEquals(2, std::vector<float>{0.0f, 2.0f, 4.0f, 6.0f, 8.0f, 10.0f, 12.0f, 14.0f, 16.0f, 18.0f, 20.0f, 22.0f, 24.0f, 26.0f, 28.0f, 30.0f, 0.0f})}}); registerTest(TestData{"deepCL_copy", DataFilter::NONE, &deepCL_copy_cl_string, "", "copy", {toScalarParameter(10u), toBufferParameter(std::vector<float>{1, 9, -2, 8, 3, 7, 4, 6, 5, 0, 11, 12}), toBufferParameter(std::vector<float>(16))}, toDimensions(12), {checkParameterEquals(2, std::vector<float>{1, 9, -2, 8, 3, 7, 4, 6, 5, 0, 0, 0})}}); registerTest(TestData{"deepCL_multiplyConstant", DataFilter::NONE, &deepCL_copy_cl_string, "", "multiplyConstant", {toScalarParameter(10u), toScalarParameter(5.0f), toBufferParameter(std::vector<float>{1, 9, -2, 8, 3, 7, 4, 6, 5, 0, 11, 12}), toBufferParameter(std::vector<float>(16))}, toDimensions(12), {checkParameterEquals( 3, std::vector<float>{5 * 1, 5 * 9, 5 * -2, 5 * 8, 5 * 3, 5 * 7, 5 * 4, 5 * 6, 5 * 5, 5 * 0, 0, 0})}}); registerTest(TestData{"deepCL_multiplyInplace", DataFilter::NONE, &deepCL_copy_cl_string, "", "multiplyInplace", {toScalarParameter(10u), toScalarParameter(5.0f), toBufferParameter(std::vector<float>{1, 9, -2, 8, 3, 7, 4, 6, 5, 0, 11, 12})}, toDimensions(12), {checkParameterEquals( 2, std::vector<float>{5 * 1, 5 * 9, 5 * -2, 5 * 8, 5 * 3, 5 * 7, 5 * 4, 5 * 6, 5 * 5, 5 * 0, 11, 12})}}); registerTest(TestData{"deepCL_array_inv", DataFilter::FLOAT_ARITHMETIC, &deepCL_inv_cl_string, "", "array_inv", {toScalarParameter(10u), toBufferParameter(std::vector<float>{1, 9, -2, 8, 0.3f, 7, 0.4f, 6, -5, 0.1f, 11, 12})}, toDimensions(12), {checkParameter<CompareULP<1>>(1, std::vector<float>{1, 1.0f / 9.0f, 1.0f / -2.0f, 1.0f / 8.0f, 1.0f / 0.3f, 1.0f / 7.0f, 1.0f / 0.4f, 1.0f / 6.0f, 1.0f / -5.0f, 1.0f / 0.1f, 11, 12})}}); registerTest(TestData{"deepCL_memset", DataFilter::NONE, &deepCL_memset_cl_string, "", "cl_memset", {toBufferParameter(std::vector<float>(16)), toScalarParameter(17.0f), toScalarParameter(10)}, toDimensions(12), {checkParameterEquals( 0, std::vector<float>{17.0f, 17.0f, 17.0f, 17.0f, 17.0f, 17.0f, 17.0f, 17.0f, 17.0f, 17.0f, 0, 0, 0, 0})}}); // TODO has result mismatch in sqrt() registerTest(TestData{"NearestNeighbor", DataFilter::DISABLED | DataFilter::FLOAT_ARITHMETIC, &rodinia_nearestNeighbor_kernel_cl_string, "", "NearestNeighbor", {toBufferParameter(std::vector<float>{0, 0, 1, 1, 0, 1, 1, 0, -1, -1, -1, 0, 0, -1, 1, -1, -1, 1}), toBufferParameter(std::vector<float>(16)), toScalarParameter(9), toScalarParameter(0.5f), toScalarParameter(-0.5f)}, toDimensions(12), {checkParameterEquals(0, std::vector<float>{ 0.707107f, 1.58114f, 1.58114f, 0.707107f, 1.58114f, 1.58114f, 0.707107f, 0.707107f, 2.12132f})}}); // TODO has some ULP errors near zero registerTest(TestData{"BabelStream_mul", DataFilter::DISABLED, &BabelStream_OCLStream_cl_string, "", "mul", {toBufferParameter(std::vector<float>(16)), toBufferParameter(toRange<float>(-4, 4, 0.5f))}, toDimensions(4, 1, 1, 4, 1, 1), {checkParameter<CompareULP<2>>(0, toRange<float>(-1.6f, 1.6f, 0.2f))}}); registerTest(TestData{"BabelStream_add", DataFilter::NONE, &BabelStream_OCLStream_cl_string, "", "add", {toBufferParameter(std::vector<float>(16, 17.0f)), toBufferParameter(toRange<float>(-4, 4, 0.5f)), toBufferParameter(std::vector<float>(16))}, toDimensions(4, 1, 1, 4, 1, 1), {checkParameterEquals(2, toRange<float>(13, 21, 0.5f))}}); // TODO result error (2 ULP) on actual hardware registerTest(TestData{"BabelStream_triad", DataFilter::NONE, &BabelStream_OCLStream_cl_string, "", "triad", {toBufferParameter(std::vector<float>(16)), toBufferParameter(toRange<float>(-4, 4, 0.5f)), toBufferParameter(std::vector<float>(16, 17.0f))}, toDimensions(4, 1, 1, 4, 1, 1), {checkParameter<CompareULP<1>>(0, toRange<float>(-4 + 0.4f * 17, 4 + 0.4f * 17, 0.5f))}}); // TODO has some result mismatch errors, expected result could also be wrong? registerTest(TestData{"BabelStream_dot", DataFilter::DISABLED | DataFilter::CONTROL_FLOW, &BabelStream_OCLStream_cl_string, "", "stream_dot", {toBufferParameter(toRange<float>(0, 32)), toBufferParameter(std::vector<float>(32, 17.0f)), toBufferParameter(std::vector<float>(4)), toBufferParameter(std::vector<float>(4)), toScalarParameter(32)}, toDimensions(4, 1, 1, 4, 1, 1), // lid 0 calculates a[0] * b[0] + a[16] * b [16]= 0 * 17 + 16 * 17 = 272 // group 0 calculates lid 0 + ... + lid 3 {checkParameterEquals(3, std::vector<float>{ 272 + 306 + 340 + 374, 408 + 442 + 476 + 510, 544 + 578 + 612 + 646, 680 + 714 + 748 + 782})}}); }; static void initializeTests() { if(ALL_TESTS.empty()) { registerGeneralTests(); registerArithmeticTests(); registerOpenCLCommonFunctionTests(); registerOpenCLGeometricFunctionTests(); registerOpenCLIntegerFunctionTests(); registerOpenCLRelationalFunctionTests(); registerMathTests(); registerMemoryTests(); registerTypeConversionTests(); registerVectorTests(); } } std::map<std::string, const TestData*> test_data::getAllTests(DataFilter exclusionFilter) { initializeTests(); std::map<std::string, const TestData*> result; for(const auto& test : ALL_TESTS) { if((test.second.filter & exclusionFilter) != DataFilter::NONE) continue; result.emplace(test.first, &test.second); } return result; } const TestData* test_data::getTest(const std::string& name) { initializeTests(); auto it = ALL_TESTS.find(name); if(it != ALL_TESTS.end()) return &it->second; return nullptr; } static std::regex createRegex(std::string pattern) { if(!pattern.empty() && (pattern[0] == '"' || pattern[0] == '\'')) pattern = pattern.substr(1, pattern.find_last_not_of(pattern[0] == '"' ? '"' : '\'') - 1); return std::regex{pattern, std::regex::basic}; } bool test_data::parseTestDataParameter(const std::string& param, std::vector<std::string>& enabledTests) { // TODO add support for data filter flags + add everything to --help // TODO add flag to list all tests + their flags they are added to + list all flags if(getTest(param)) { enabledTests.emplace_back(param); return true; } // check whether parameter is regex and try to match strings if(param.find("--test-pattern=") == 0) { std::regex pattern = createRegex(param.substr(param.find('=') + 1)); for(const auto& test : getAllTests()) { if(std::regex_match(test.first, pattern)) { enabledTests.emplace_back(test.first); } } return true; } return false; } Result test_data::execute(const TestData* data, TestRunner& runner) try { auto result = runner.compile(*data->sources, data->compilationOptions); if(!result) return result; result = runner.selectKernel(data->kernelName); if(!result) return result; for(std::size_t i = 0; i < data->kernelArguments.size(); ++i) { result = data->kernelArguments[i](i, runner); if(!result) return result; } result = runner.setWorkDimensions(data->workDimensions); if(!result) return result; result = runner.execute(); if(!result) return result; for(const auto& verification : data->verifications) { auto tmpResult = verification(runner); if(!tmpResult) { // combine the errors into one result.wasSuccess = false; if(!result.error.empty()) result.error.append("\n"); result.error.append(tmpResult.error); } } return result; } catch(const std::exception& err) { return Result{false, err.what()}; }
64.188458
120
0.597738
[ "vector", "transform" ]
33d949b9974612b55b3e07295af717ab6d9bb726
3,560
cpp
C++
ch15/ex15.18.19.20/main.cpp
beautiful-boyyy/Cpp-Primer
7802029df51bcac4a029044fc4fd38c3a9ff6177
[ "CC0-1.0" ]
null
null
null
ch15/ex15.18.19.20/main.cpp
beautiful-boyyy/Cpp-Primer
7802029df51bcac4a029044fc4fd38c3a9ff6177
[ "CC0-1.0" ]
null
null
null
ch15/ex15.18.19.20/main.cpp
beautiful-boyyy/Cpp-Primer
7802029df51bcac4a029044fc4fd38c3a9ff6177
[ "CC0-1.0" ]
null
null
null
/*************************************************************************** * @file main.cpp * @author Alan.W * @date 23 Jan 2014 * @remark This code is for the exercises from C++ Primer 5th Edition * @note ***************************************************************************/ // // Exercise 15.18: // Given the classes from page 612 and page 613, and assuming each object // has the type specified in the comments, determine which of these assignments // are legal. Explain why those that are illegal aren’t allowed: // // Base *p = &d1; // d1 has type Pub_Derv -- legal --right // p = &d2; // d2 has type Priv_Derv -- illegal --right // p = &d3; // d3 has type Prot_Derv -- illegal --right // // p = &dd1; // dd1 has type Derived_from_Public -- legal --right // p = &dd2; // dd2 has type Derived_from_Private -- illegal --right // p = &dd3; // dd3 has type Derived_from_Protected -- illegal --right // // User code may use the derived-to-base conversion only if D inherits // publicly from B. User code may not use the conversion if D inherits // from B using either protected or private. // // Exercise 15.19: // Assume that each of the classes from page 612 and page 613 has a member // function of the form: // // void memfcn(Base &b) { b = *this; } // // For each class, determine whether this function would be legal. // // Member functions and friends of D can use the conversion to B regardless // of how D inherits from B. The derived-to-base conversion to a direct base // class is always accessible to members and friends of a derived class. // Hence, the 3 below are all legal: // // Pub_Derv -- legal --right // Priv_Derv -- legal --right // Prot_Derv -- legal --right // // Member functions and friends of classes derived from D may use the // derived-to-base conversion if D inherits from B using either public or // protected. Such code may not use the conversion if D inherits privately // from B.Hence: // Derived_from_Public -- legal --right // Derived_from_Private -- illegal --right // Derived_from_Protected -- legal --right // // Exercise 15.20: // Write code to test your answers to the previous two exercises. // #include <iostream> #include <string> #include "../ex15.15.16.17/quote.h" #include "../ex15.15.16.17/bulk_quote.h" #include "../ex15.15.16.17/limit_quote.h" #include "../ex15.15.16.17/disc_quote.h" class Base { public: void pub_mem(); // public member protected: int prot_mem; // protected member private: char priv_mem; // private member }; struct Pub_Derv : public Base { void memfcn(Base &b) { b = *this; } }; struct Priv_Derv : private Base { void memfcn(Base &b) { b = *this; } }; struct Prot_Derv : protected Base { void memfcn(Base &b) { b = *this; } }; struct Derived_from_Public : public Pub_Derv { void memfcn(Base &b) { b = *this; } }; struct Derived_from_Private : public Priv_Derv { //void memfcn(Base &b) { b = *this; } }; struct Derived_from_Protected : public Prot_Derv { void memfcn(Base &b) { b = *this; } }; int main() { Pub_Derv d1; Base *p = &d1; Priv_Derv d2; //p = &d2; Prot_Derv d3; //p = &d3; Derived_from_Public dd1; p = &dd1; Derived_from_Private dd2; //p =& dd2; Derived_from_Protected dd3; //p = &dd3; return 0; }
29.180328
82
0.592135
[ "object" ]
33d94a062f1ee12ceaa3e62183372cb233eecd69
7,254
hpp
C++
pwiz/utility/bindings/CLI/common/BinaryData.hpp
vagisha/pwiz
aa65186bf863cdebde3d15c293d137085365bead
[ "Apache-2.0" ]
null
null
null
pwiz/utility/bindings/CLI/common/BinaryData.hpp
vagisha/pwiz
aa65186bf863cdebde3d15c293d137085365bead
[ "Apache-2.0" ]
null
null
null
pwiz/utility/bindings/CLI/common/BinaryData.hpp
vagisha/pwiz
aa65186bf863cdebde3d15c293d137085365bead
[ "Apache-2.0" ]
null
null
null
// // $Id$ // // // Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu> // // Copyright 2017 Matt Chambers // // 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. // #ifndef _PWIZ_CLI_BINARYDATA_ #define _PWIZ_CLI_BINARYDATA_ #pragma warning( push ) #pragma warning( disable : 4634 4635 ) #include "pwiz/data/msdata/MSData.hpp" #pragma warning( pop ) using namespace System; #include "vector.hpp" // for RANGE_CHECK and ValidateCopyToArrayArgs #include "SharedCLI.hpp" #include <cstring> #ifndef INTERNAL #define INTERNAL internal #endif namespace pwiz { namespace CLI { namespace util { /// <summary> /// Wrapper for binary data from spectra and chromatograms, accessible as IList&lt;double&gt; the underlying data may be stored in a native std::vector or in a managed cli::array. /// Call Storage() to get access to the managed array: if the underlying storage is a std::vector, it will be copied to a managed array before returning. /// </summary> template <typename ValueType> public ref class BinaryData : public System::Collections::Generic::IList<ValueType> { public: System::IntPtr void_base() { return (System::IntPtr) base_; } INTERNAL: typedef pwiz::util::BinaryData<ValueType> binarydata_type; typedef binarydata_type* binarydataptr_type; typedef typename binarydata_type::iterator iterator_type; /* void* downcast is needed for cross-assembly calls; */ /* native types are private by default and */ /* #pragma make_public doesn't work on templated types */ BinaryData(void* base, System::Object^ owner) : base_(static_cast<binarydataptr_type>(base)), baseRef_((*base_)), owner_(owner) {} BinaryData(void* base) : base_(static_cast<binarydataptr_type>(base)), baseRef_((*base_)), owner_(nullptr) {} virtual ~BinaryData() { if (owner_ == nullptr && base_ != NULL) delete base_; } !BinaryData() { delete this; } binarydataptr_type base_; binarydata_type& baseRef_; System::Object^ owner_; binarydata_type& base() { return baseRef_; } binarydata_type& assign(BinaryData<ValueType>^ rhs) { return base() = rhs->base(); } public: BinaryData() : base_(new binarydata_type()), baseRef_((*base_)) {} property int Count { virtual int get() { return (int)base().size(); } } property bool IsReadOnly { virtual bool get() { return false; } } property ValueType default[int] { virtual ValueType get(int index) { RANGE_CHECK(index) return base()[(size_t)index]; } virtual void set(int index, ValueType value) { RANGE_CHECK(index) base()[(size_t)index] = value; } } virtual void Add(ValueType item) { base().push_back(item); } virtual void Clear() { base().clear(); } virtual bool Contains(ValueType item) { return std::find(base().begin(), base().end(), item) != base().end(); } virtual void CopyTo(array<ValueType>^ arrayTarget, int arrayIndex) { ValidateCopyToArrayArgs(arrayTarget, arrayIndex, base().size()); pin_ptr<ValueType> pinnedArray = &arrayTarget[0]; memcpy((ValueType*)pinnedArray + arrayIndex, &base()[0], base().size()); } virtual bool Remove(ValueType item) { auto itr = std::find(base().begin(), base().end(), item); if (itr == base().end()) return false; base().erase(itr); return true; } virtual int IndexOf(ValueType item) { return (int)(std::find(base().begin(), base().end(), item) - base().begin()); } virtual void Insert(int index, ValueType item) { base().insert(base().begin() + index, item); } virtual void RemoveAt(int index) { RANGE_CHECK(index) base().erase(base().begin() + index); } /// <summary> /// Returns a managed array storing the underlying data; if the underlying storage is a std::vector, it will be copied to a managed array before returning. /// </summary> virtual cli::array<ValueType>^ Storage() { try { System::Runtime::InteropServices::GCHandle handle = (System::Runtime::InteropServices::GCHandle) System::IntPtr(base().managedStorage()); return (cli::array<ValueType>^) handle.Target; } CATCH_AND_FORWARD } ref struct Enumerator : System::Collections::Generic::IEnumerator<ValueType> { Enumerator(binarydataptr_type base) : base_(base), itr_(new iterator_type), end_(new iterator_type(base_->end())), owner_(nullptr), isReset_(true) {} Enumerator(binarydataptr_type base, System::Object^ owner) : base_(base), itr_(new iterator_type), end_(new iterator_type(base_->end())), owner_(owner), isReset_(true) {} property ValueType Current { virtual ValueType get() { return **itr_; } } property System::Object^ Current2 { virtual System::Object^ get() sealed = System::Collections::IEnumerator::Current::get{ return (System::Object^) **itr_; } } virtual bool MoveNext() { /*if (base().empty()) return false; else */if (isReset_) { isReset_ = false; *itr_ = base().begin(); } else if (*itr_ + 1 == *end_) return false; else ++*itr_; return true; } virtual void Reset() { isReset_ = true; *itr_ = *end_ = base().end(); } ~Enumerator() { delete itr_; delete end_; } internal: typedef pwiz::util::BinaryData<ValueType> binarydata_type; typedef binarydata_type* binarydataptr_type; typedef typename binarydata_type::iterator iterator_type; binarydataptr_type base_; iterator_type* itr_; iterator_type* end_; System::Object^ owner_; bool isReset_; binarydata_type& base() { return (*base_); } }; virtual System::Collections::Generic::IEnumerator<ValueType>^ GetEnumerator() { return gcnew Enumerator(base_, this); } virtual System::Collections::IEnumerator^ GetEnumerator2() sealed = System::Collections::IEnumerable::GetEnumerator{ return gcnew Enumerator(base_, this); } }; // unfortunately C# can't use C++ template instantiations directly, even through typedefs or type aliases, // so these subclasses make the instantiations accessible public ref class BinaryDataDouble : public BinaryData<double> { INTERNAL: BinaryDataDouble(void* base, System::Object^ owner) : BinaryData(base, owner) {} BinaryDataDouble(void* base) : BinaryData(base) {} public: BinaryDataDouble() : BinaryData() {} }; public ref class BinaryDataInteger : public BinaryData<System::Int64> { INTERNAL: BinaryDataInteger(void* base, System::Object^ owner) : BinaryData(base, owner) {} BinaryDataInteger(void* base) : BinaryData(base) {} public: BinaryDataInteger() : BinaryData() {} }; } // namespace util } // namespace CLI } // namespace pwiz #endif // _PWIZ_CLI_BINARYDATA_
40.3
179
0.681969
[ "object", "vector" ]
33da52764fdf86e6fcb1b6fe58dd95bb328fe7b0
5,779
cpp
C++
lib/djvGL/ImageConvert.cpp
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
null
null
null
lib/djvGL/ImageConvert.cpp
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
null
null
null
lib/djvGL/ImageConvert.cpp
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2004-2020 Darby Johnston // All rights reserved. #include <djvGL/ImageConvert.h> #include <djvGL/Mesh.h> #include <djvGL/OffscreenBuffer.h> #include <djvGL/Shader.h> #include <djvGL/Texture.h> #include <djvSystem/TextSystem.h> #include <djvSystem/ResourceSystem.h> #include <djvGeom/Shape.h> #include <djvGeom/TriangleMesh.h> #include <glm/gtc/matrix_transform.hpp> using namespace djv::Core; namespace djv { namespace GL { struct ImageConvert::Private { std::shared_ptr<System::TextSystem> textSystem; std::shared_ptr<System::ResourceSystem> resourceSystem; Image::Size size; Image::Mirror mirror; std::shared_ptr<OffscreenBuffer> offscreenBuffer; std::shared_ptr<Texture> texture; std::shared_ptr<VBO> vbo; std::shared_ptr<VAO> vao; std::shared_ptr<Shader> shader; glm::mat4x4 mvp = glm::mat4x4(1.F); }; void ImageConvert::_init( const std::shared_ptr<System::TextSystem>& textSystem, const std::shared_ptr<System::ResourceSystem>& resourceSystem) { DJV_PRIVATE_PTR(); p.textSystem = textSystem; p.resourceSystem = resourceSystem; const auto shaderPath = resourceSystem->getPath(System::File::ResourcePath::Shaders); p.shader = Shader::create( System::File::Path(shaderPath, "djvImageConvertVertex.glsl"), System::File::Path(shaderPath, "djvImageConvertFragment.glsl")); } ImageConvert::ImageConvert() : _p(new Private) {} ImageConvert::~ImageConvert() {} std::shared_ptr<ImageConvert> ImageConvert::create( const std::shared_ptr<System::TextSystem>& textSystem, const std::shared_ptr<System::ResourceSystem>& resourceSystem) { auto out = std::shared_ptr<ImageConvert>(new ImageConvert); out->_init(textSystem, resourceSystem); return out; } void ImageConvert::process(const Image::Data& data, const Image::Info& info, Image::Data& out) { DJV_PRIVATE_PTR(); bool create = !p.offscreenBuffer; create |= p.offscreenBuffer && info.size != p.offscreenBuffer->getSize(); create |= p.offscreenBuffer && info.type != p.offscreenBuffer->getColorType(); if (create) { p.offscreenBuffer = OffscreenBuffer::create(info.size, info.type, p.textSystem); } const OffscreenBufferBinding binding(p.offscreenBuffer); if (!p.texture || (p.texture && data.getInfo() != p.texture->getInfo())) { p.texture = Texture::create(data.getInfo()); } p.texture->bind(); p.texture->copy(data); p.shader->bind(); p.shader->setUniform("textureSampler", 0); if (info.size != p.size) { p.size = info.size; glm::mat4x4 modelMatrix(1); modelMatrix = glm::rotate(modelMatrix, Math::deg2rad(90.F), glm::vec3(1.F, 0.F, 0.F)); modelMatrix = glm::scale(modelMatrix, glm::vec3(info.size.w, 0.F, info.size.h)); modelMatrix = glm::translate(modelMatrix, glm::vec3(.5F, 0.F, -.5F)); glm::mat4x4 viewMatrix(1); glm::mat4x4 projectionMatrix(1); projectionMatrix = glm::ortho( 0.F, static_cast<float>(info.size.w) - 1.F, 0.F, static_cast<float>(info.size.h) - 1.F, -1.F, 1.F); p.mvp = projectionMatrix * viewMatrix * modelMatrix; } p.shader->setUniform("transform.mvp", p.mvp); if (!p.vbo || (p.vbo && data.getLayout().mirror != p.mirror)) { p.mirror = data.getLayout().mirror; Geom::Square square; Geom::TriangleMesh mesh; square.triangulate(mesh); if (p.mirror.x) { auto tmp = mesh.t[0].x; mesh.t[0].x = mesh.t[1].x; mesh.t[1].x = tmp; tmp = mesh.t[2].x; mesh.t[2].x = mesh.t[3].x; mesh.t[3].x = tmp; } if (p.mirror.y) { auto tmp = mesh.t[0].y; mesh.t[0].y = mesh.t[2].y; mesh.t[2].y = tmp; tmp = mesh.t[1].y; mesh.t[1].y = mesh.t[3].y; mesh.t[3].y = tmp; } p.vbo = VBO::create(2 * 3, VBOType::Pos3_F32_UV_U16); p.vbo->copy(VBO::convert(mesh, p.vbo->getType())); p.vao = VAO::create(p.vbo->getType(), p.vbo->getID()); } p.vao->bind(); glViewport(0, 0, info.size.w, info.size.h); glClearColor(0.F, 0.F, 0.F, 0.F); glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); p.vao->draw(GL_TRIANGLES, 0, 6); glPixelStorei(GL_PACK_ALIGNMENT, 1); #if !defined(DJV_GL_ES2) glPixelStorei(GL_PACK_SWAP_BYTES, info.layout.endian != Memory::getEndian()); #endif // DJV_GL_ES2 glReadPixels( 0, 0, info.size.w, info.size.h, info.getGLFormat(), info.getGLType(), out.getData()); } } // namespace GL } // namespace djv
35.89441
102
0.51393
[ "mesh", "shape", "transform" ]
33db99613f4e3c861d98c93a5bbbd159dcae7875
8,617
cc
C++
chrome/browser/chrome_browser_main_parts_fuchsia.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-11-16T13:10:29.000Z
2021-11-16T13:10:29.000Z
chrome/browser/chrome_browser_main_parts_fuchsia.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chrome_browser_main_parts_fuchsia.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chrome_browser_main_parts_fuchsia.h" #include <fuchsia/ui/app/cpp/fidl.h> #include <lib/sys/cpp/component_context.h> #include <lib/ui/scenic/cpp/commands.h> #include <lib/ui/scenic/cpp/resources.h> #include <lib/ui/scenic/cpp/session.h> #include "base/bind.h" #include "base/check.h" #include "base/fuchsia/fuchsia_logging.h" #include "base/fuchsia/process_context.h" #include "base/fuchsia/process_lifecycle.h" #include "base/fuchsia/scoped_service_binding.h" #include "base/notreached.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "ui/platform_window/fuchsia/initialize_presenter_api_view.h" namespace { fuchsia::ui::views::ViewRef CloneViewRef( const fuchsia::ui::views::ViewRef& view_ref) { fuchsia::ui::views::ViewRef dup; zx_status_t status = view_ref.reference.duplicate(ZX_RIGHT_SAME_RIGHTS, &dup.reference); ZX_CHECK(status == ZX_OK, status) << "zx_object_duplicate"; return dup; } struct SubViewData { scenic::ViewHolder view_holder; fuchsia::ui::views::ViewRef view_ref; }; // ViewProvider implementation that provides a single view and exposes all // requested view from PlatformOzoneScenic inside it. class ViewProviderScenic : public fuchsia::ui::app::ViewProvider { public: ViewProviderScenic() : binding_(base::ComponentContextForProcess()->outgoing().get(), this), scenic_(base::ComponentContextForProcess() ->svc() ->Connect<fuchsia::ui::scenic::Scenic>()), scenic_session_(scenic_.get(), focuser_.NewRequest()) { scenic_.set_error_handler([](zx_status_t status) { ZX_LOG(ERROR, status) << " Scenic lost."; // Terminate here so that e.g. a Scenic crash results in the browser // immediately terminating, without generating a cascading crash report. base::Process::TerminateCurrentProcessImmediately(1); }); scenic_session_.set_event_handler( fit::bind_member(this, &ViewProviderScenic::OnScenicEvents)); } ~ViewProviderScenic() override { scenic_.Unbind(); } // fuchsia::ui::app::ViewProvider overrides. void CreateView( zx::eventpair token, fidl::InterfaceRequest<fuchsia::sys::ServiceProvider> incoming_services, fidl::InterfaceHandle<fuchsia::sys::ServiceProvider> outgoing_services) override { CreateViewWithViewRef(std::move(token), {}, {}); } void CreateViewWithViewRef(zx::eventpair token, fuchsia::ui::views::ViewRefControl control_ref, fuchsia::ui::views::ViewRef view_ref) override { if (view_) { LOG(WARNING) << "Unexpected spurious call to |CreateViewWithViewRef|. " "Deleting previously created view."; subviews_.clear(); is_node_attached_ = false; view_has_focus_ = false; node_.reset(); view_.reset(); view_properties_ = absl::nullopt; } view_ = std::make_unique<scenic::View>( &scenic_session_, fuchsia::ui::views::ViewToken({std::move(token)}), std::move(control_ref), std::move(view_ref), "root-view"); node_ = std::make_unique<scenic::EntityNode>(&scenic_session_); for (auto& subview : subviews_) { node_->AddChild(subview.view_holder); } Present(); } void PresentView(fuchsia::ui::views::ViewHolderToken view_holder_token, fuchsia::ui::views::ViewRef view_ref) { SubViewData subview = { .view_holder = scenic::ViewHolder(&scenic_session_, std::move(view_holder_token).value, "subview-holder"), .view_ref = std::move(view_ref)}; if (view_) { if (view_properties_) { subview.view_holder.SetViewProperties(*view_properties_); } node_->AddChild(subview.view_holder); Present(); } subviews_.push_back(std::move(subview)); } private: void OnScenicEvents(std::vector<fuchsia::ui::scenic::Event> events) { for (const auto& event : events) { if (event.is_gfx() && event.gfx().is_view_properties_changed()) { if (event.gfx().view_properties_changed().view_id != view_->id()) { LOG(WARNING) << "Received event for unknown view."; return; } UpdateViewProperties(event.gfx().view_properties_changed().properties); } else if (event.is_input() && event.input().is_focus()) { view_has_focus_ = event.input().focus().focused; FocusView(); } } } void UpdateViewProperties( const fuchsia::ui::gfx::ViewProperties& view_properties) { const float width = view_properties.bounding_box.max.x - view_properties.bounding_box.min.x; const float height = view_properties.bounding_box.max.y - view_properties.bounding_box.min.y; if (width == 0 || height == 0) { if (is_node_attached_) { node_->Detach(); is_node_attached_ = false; } } else { if (!is_node_attached_) { view_->AddChild(*node_); is_node_attached_ = true; } } view_properties_ = view_properties; for (auto& subview : subviews_) { subview.view_holder.SetViewProperties(*view_properties_); } Present(); } void FocusView(int tries = 2) { if (tries == 0) { LOG(ERROR) << "Unable to pass focus to chrome window."; return; } if (!subviews_.empty() && view_has_focus_) { focuser_->RequestFocus({CloneViewRef(subviews_.front().view_ref)}, [this, tries](auto result) { if (result.is_err()) { FocusView(tries - 1); } }); } } void Present() { scenic_session_.Present( zx_clock_get_monotonic(), [this](fuchsia::images::PresentationInfo info) { FocusView(); }); } const base::ScopedServiceBinding<fuchsia::ui::app::ViewProvider> binding_; fuchsia::ui::scenic::ScenicPtr scenic_; fuchsia::ui::views::FocuserPtr focuser_; scenic::Session scenic_session_; // The view created by this ViewProvider. The view is created lazily when a // request is received. std::unique_ptr<scenic::View> view_; // Entity node for the |view_|. std::unique_ptr<scenic::EntityNode> node_; // True if the root EntityNode has been added to the View. bool is_node_attached_ = false; // True is the root view has focus. bool view_has_focus_ = false; // The holders for all the views that are presented. std::vector<SubViewData> subviews_; // The properties of the top level view. They are forwarded to the embedded // views. absl::optional<fuchsia::ui::gfx::ViewProperties> view_properties_; }; } // namespace ChromeBrowserMainPartsFuchsia::ChromeBrowserMainPartsFuchsia( content::MainFunctionParams parameters, StartupData* startup_data) : ChromeBrowserMainParts(std::move(parameters), startup_data) {} ChromeBrowserMainPartsFuchsia::~ChromeBrowserMainPartsFuchsia() = default; void ChromeBrowserMainPartsFuchsia::ShowMissingLocaleMessageBox() { // Locale data should be bundled for all possible platform locales, // so crash here to make missing-locale states more visible. CHECK(false); } int ChromeBrowserMainPartsFuchsia::PreMainMessageLoopRun() { // Register the ViewPresenter API. ui::fuchsia::SetScenicViewPresenter( base::BindRepeating(&ViewProviderScenic::PresentView, std::make_unique<ViewProviderScenic>())); zx_status_t status = base::ComponentContextForProcess()->outgoing()->ServeFromStartupInfo(); ZX_CHECK(status == ZX_OK, status); // Publish the fuchsia.process.lifecycle.Lifecycle service to allow graceful // teardown. If there is a |ui_task| then this is a browser-test and graceful // shutdown is not required. if (!parameters().ui_task) { lifecycle_ = std::make_unique<base::ProcessLifecycle>( base::BindOnce(&chrome::ExitIgnoreUnloadHandlers)); } return ChromeBrowserMainParts::PreMainMessageLoopRun(); } void ChromeBrowserMainPartsFuchsia::PostMainMessageLoopRun() { // ViewProviderScenic owns the Scenic channel and its lifetime is bound // to this callback so replacing it will unnbind the scenic channel. ui::fuchsia::SetScenicViewPresenter(ui::fuchsia::PresentViewCallback()); ChromeBrowserMainParts::PostMainMessageLoopRun(); }
35.755187
80
0.671928
[ "vector" ]
33dc21f06b34c58a312c39fb7636c694b51d470d
2,837
cc
C++
ai/DeepCoder/docker/DeepCoder/src/generate_program.cc
quanpan302/test
313c6e310be0ef608543c23bd52a5466047cd378
[ "Apache-2.0" ]
null
null
null
ai/DeepCoder/docker/DeepCoder/src/generate_program.cc
quanpan302/test
313c6e310be0ef608543c23bd52a5466047cd378
[ "Apache-2.0" ]
null
null
null
ai/DeepCoder/docker/DeepCoder/src/generate_program.cc
quanpan302/test
313c6e310be0ef608543c23bd52a5466047cd378
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <sstream> #include <string> #include <vector> #include <iomanip> #include "dsl/utils.h" #include "find-program.h" using namespace std; using namespace dsl; Value to_value(const string &line) { istringstream iss(line); string type; iss >> type; vector<int> vec; while (!iss.eof()) { int x; iss >> x; vec.push_back(x); } if (type == "Integer") { return Value(vec.at(0)); } else { return Value(vec); } } Input read_input() { string line; Input input; while (true) { getline(cin, line); if (line == "---") { return input; } input.push_back(to_value(line)); } } Output read_output() { string line; getline(cin, line); Output output = to_value(line); getline(cin, line); // Read "---" return output; } int main(int argc, char **argv) { size_t max_length = 4; bool is_dfs = false; bool is_none = false; if (argc >= 2) { max_length = atoi(argv[1]); } if (argc >= 3) { auto x = string(argv[2]); if (x == "dfs") { is_dfs = true; } else if (x == "none") { is_none = true; } } // Read examples vector<Example> examples; while (cin) { auto input = read_input(); if (input.size() == 0) { break; } auto output = read_output(); examples.push_back({input, output}); } // Read attribute vector<double> attr_; string tmp; cin >> tmp; // Read "Attribute:" while (cin) { double x; cin >> x; if (x < 0) { break; } attr_.push_back(x); } if (is_none) { for (auto &a: attr_) { a = 1.0; } } else { for (auto i = 0; i < all_functions.size() - 2; i++) { auto f = all_functions[i]; cerr << stringify(f) << "\t"; } for (auto x: all_predicate_lambdas) { cerr << stringify(x) << "\t"; } for (auto x: all_one_argument_lambdas) { cerr << stringify(x) << "\t"; } for (auto x: all_two_arguments_lambdas) { cerr << stringify(x) << "\t"; } cerr << endl; for (const auto &a: attr_) { cerr << setprecision(3) << a << "\t"; } cerr << endl; } // Find program auto p = (is_dfs) ? dfs(max_length, Attribute(attr_), examples) : (is_none) ? dfs(max_length, Attribute(attr_), examples) : sort_and_add(max_length, Attribute(attr_), examples); if (p) { cout << p.value() << endl; return 0; } else { cout << "not found" << endl; return 1; } }
21.823077
68
0.476912
[ "vector" ]
33dd41dbf98c3301043e6f9f55af0be48cc63fda
36,521
cpp
C++
src/libraries/core/fvMatrices/solvers/isoAdvection/isoAdvection/isoAdvection.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/fvMatrices/solvers/isoAdvection/isoAdvection/isoAdvection.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/fvMatrices/solvers/isoAdvection/isoAdvection/isoAdvection.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2016-2017 OpenCFD Ltd Copyright (C) 2016-2017 DHI ------------------------------------------------------------------------------- License This file is part of Caelus. Caelus is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Caelus is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Caelus. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "isoAdvection.hpp" #include "volFields.hpp" #include "interpolationCellPoint.hpp" #include "volPointInterpolation.hpp" #include "fvcSurfaceIntegrate.hpp" #include "fvcGrad.hpp" #include "upwind.hpp" #include "cellSet.hpp" #include "meshTools.hpp" #include "OBJstream.hpp" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // namespace CML { defineTypeNameAndDebug(isoAdvection, 0); } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // CML::isoAdvection::isoAdvection ( volScalarField& alpha1, const surfaceScalarField& phi, const volVectorField& U ) : // General data mesh_(alpha1.mesh()), dict_(mesh_.solverDict(alpha1.name())), alpha1_(alpha1), alpha1In_(alpha1), phi_(phi), U_(U), dVf_ ( IOobject ( "dVf_", mesh_.time().timeName(), mesh_, IOobject::NO_READ, IOobject::NO_WRITE ), mesh_, dimensionedScalar("zero", dimVol, 0) ), advectionTime_(0), // Interpolation data ap_(mesh_.nPoints()), // Tolerances and solution controls nAlphaBounds_(dict_.lookupOrDefault<label>("nAlphaBounds", 3)), vof2IsoTol_(dict_.lookupOrDefault<scalar>("vof2IsoTol", 1e-8)), surfCellTol_(dict_.lookupOrDefault<scalar>("surfCellTol", 1e-8)), gradAlphaBasedNormal_ ( dict_.lookupOrDefault<bool>("gradAlphaNormal", false) ), writeIsoFacesToFile_ ( dict_.lookupOrDefault<bool>("writeIsoFaces", false) ), // Cell cutting data surfCells_(label(0.2*mesh_.nCells())), isoCutCell_(mesh_, ap_), isoCutFace_(mesh_, ap_), cellIsBounded_(mesh_.nCells(), false), checkBounding_(mesh_.nCells(), false), bsFaces_(label(0.2*(mesh_.nFaces() - mesh_.nInternalFaces()))), bsx0_(bsFaces_.size()), bsn0_(bsFaces_.size()), bsUn0_(bsFaces_.size()), bsf0_(bsFaces_.size()), // Parallel run data procPatchLabels_(mesh_.boundary().size()), surfaceCellFacesOnProcPatches_(0) { isoCutCell::debug = debug; isoCutFace::debug = debug; // Prepare lists used in parallel runs if (Pstream::parRun()) { // Force calculation of required demand driven data (else parallel // communication may crash) mesh_.cellCentres(); mesh_.cellVolumes(); mesh_.faceCentres(); mesh_.faceAreas(); mesh_.magSf(); mesh_.boundaryMesh().patchID(); mesh_.cellPoints(); mesh_.cellCells(); mesh_.cells(); // Get boundary mesh and resize the list for parallel comms const polyBoundaryMesh& patches = mesh_.boundaryMesh(); surfaceCellFacesOnProcPatches_.resize(patches.size()); // Append all processor patch labels to the list forAll(patches, patchi) { if ( isA<processorPolyPatch>(patches[patchi]) && patches[patchi].size() > 0 ) { procPatchLabels_.append(patchi); } } } } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // void CML::isoAdvection::timeIntegratedFlux() { // Get time step const scalar dt = mesh_.time().deltaTValue(); // Create object for interpolating velocity to isoface centres interpolationCellPoint<vector> UInterp(U_); // For each downwind face of each surface cell we "isoadvect" to find dVf label nSurfaceCells = 0; // Clear out the data for re-use and reset list containing information // whether cells could possibly need bounding clearIsoFaceData(); checkBounding_ = false; // Get necessary references const scalarField& phiIn = phi_.internalField(); const scalarField& magSfIn = mesh_.magSf().internalField(); scalarField& dVfIn = dVf_.internalField(); // Get necessary mesh data const labelListList& cellPoints = mesh_.cellPoints(); const labelListList& cellCells = mesh_.cellCells(); const cellList& cellFaces = mesh_.cells(); const labelList& own = mesh_.faceOwner(); const labelList& nei = mesh_.faceNeighbour(); const vectorField& cellCentres = mesh_.cellCentres(); const pointField& points = mesh_.points(); // Storage for isoFace points. Only used if writeIsoFacesToFile_ DynamicList<List<point> > isoFacePts; // Interpolating alpha1 cell centre values to mesh points (vertices) ap_ = volPointInterpolation::New(mesh_).interpolate(alpha1_); vectorField gradAlpha(mesh_.nPoints(), vector::zero); if (gradAlphaBasedNormal_) { // Calculate gradient of alpha1 and interpolate to vertices volVectorField gradA("gradA", fvc::grad(alpha1_)); gradAlpha = volPointInterpolation::New(mesh_).interpolate(gradA); } // Loop through cells forAll(alpha1In_, celli) { if (isASurfaceCell(celli)) { // This is a surface cell, increment counter, append and mark cell nSurfaceCells++; surfCells_.append(celli); checkBounding_[celli] = true; if (debug) Info << "\n------------ Cell " << celli << " with alpha1 = " << alpha1In_[celli] << " and 1-alpha1 = " << 1.0 - alpha1In_[celli] << " ------------" << endl; // Calculate isoFace centre x0, normal n0 at time t label maxIter = 100; // NOTE: make it a debug switch const labelList& cp = cellPoints[celli]; scalarField ap_org(cp.size(), 0); if (gradAlphaBasedNormal_) { // Calculating smoothed alpha gradient in surface cell in order // to use it as the isoface orientation. vector smoothedGradA = vector::zero; const point& cellCentre = cellCentres[celli]; scalar wSum = 0; forAll(cp, pointI) { point vertex = points[cp[pointI]]; scalar w = 1.0/mag(vertex - cellCentre); wSum += w; smoothedGradA += w*gradAlpha[cp[pointI]]; } smoothedGradA /= wSum; // Temporarily overwrite the interpolated vertex alpha values in // ap_ with the vertex-cell centre distance along smoothedGradA. forAll(ap_org, vi) { ap_org[vi] = ap_[cp[vi]]; const point& vertex = points[cp[vi]]; ap_[cp[vi]] = ( (vertex - cellCentre) & (smoothedGradA/mag(smoothedGradA)) ); } } // Calculate cell status (-1: cell is fully below the isosurface, 0: // cell is cut, 1: cell is fully above the isosurface) label cellStatus = isoCutCell_.vofCutCell ( celli, alpha1In_[celli], vof2IsoTol_, maxIter ); if (gradAlphaBasedNormal_) { // Restoring ap_ by putting the original values back into it. forAll(ap_org, vi) { ap_[cp[vi]] = ap_org[vi]; } } // Cell is cut if (cellStatus == 0) { const scalar f0 = isoCutCell_.isoValue(); const point& x0 = isoCutCell_.isoFaceCentre(); vector n0 = isoCutCell_.isoFaceArea(); n0 /= (mag(n0)); if (writeIsoFacesToFile_ && mesh_.time().outputTime()) { isoFacePts.append(isoCutCell_.isoFacePoints()); } // Get the speed of the isoface by interpolating velocity and // dotting it with isoface normal const scalar Un0 = UInterp.interpolate(x0, celli) & n0; if (debug) Info << "calcIsoFace gives initial surface: \nx0 = " << x0 << ", \nn0 = " << n0 << ", \nf0 = " << f0 << ", \nUn0 = " << Un0 << endl; // Estimate time integrated flux through each downwind face // Note: looping over all cell faces - in reduced-D, some of // these faces will be on empty patches const cell& celliFaces = cellFaces[celli]; forAll(celliFaces, fi) { const label facei = celliFaces[fi]; if (mesh_.isInternalFace(facei)) { bool isDownwindFace = false; label otherCell = -1; if (celli == own[facei]) { if (phiIn[facei] > 10*SMALL) { isDownwindFace = true; } otherCell = nei[facei]; } else { if (phiIn[facei] < -10*SMALL) { isDownwindFace = true; } otherCell = own[facei]; } if (isDownwindFace) { dVfIn[facei] = timeIntegratedFaceFlux ( facei, x0, n0, Un0, f0, dt, phiIn[facei], magSfIn[facei] ); } // We want to check bounding of neighbour cells to // surface cells as well: checkBounding_[otherCell] = true; // Also check neighbours of neighbours. // Note: consider making it a run time selectable // extension level (easily done with recursion): // 0 - only neighbours // 1 - neighbours of neighbours // 2 - ... const labelList& nNeighbourCells = cellCells[otherCell]; forAll(nNeighbourCells, ni) { checkBounding_[nNeighbourCells[ni]] = true; } } else { bsFaces_.append(facei); bsx0_.append(x0); bsn0_.append(n0); bsUn0_.append(Un0); bsf0_.append(f0); // Note: we must not check if the face is on the // processor patch here. } } } } } if (writeIsoFacesToFile_ && mesh_.time().outputTime()) { writeIsoFaces(isoFacePts); } // Get references to boundary fields const polyBoundaryMesh& boundaryMesh = mesh_.boundaryMesh(); const surfaceScalarField::GeometricBoundaryField& phib = phi_.boundaryField(); const surfaceScalarField::GeometricBoundaryField& magSfb = mesh_.magSf().boundaryField(); surfaceScalarField::GeometricBoundaryField& dVfb = dVf_.boundaryField(); const label nInternalFaces = mesh_.nInternalFaces(); // Loop through boundary surface faces forAll(bsFaces_, i) { // Get boundary face index (in the global list) const label facei = bsFaces_[i]; const label patchi = boundaryMesh.patchID()[facei - nInternalFaces]; const label start = boundaryMesh[patchi].start(); if (phib[patchi].size()) { const label patchFacei = facei - start; const scalar phiP = phib[patchi][patchFacei]; if (phiP > 10*SMALL) { const scalar magSf = magSfb[patchi][patchFacei]; dVfb[patchi][patchFacei] = timeIntegratedFaceFlux ( facei, bsx0_[i], bsn0_[i], bsUn0_[i], bsf0_[i], dt, phiP, magSf ); // Check if the face is on processor patch and append it to // the list if necessary checkIfOnProcPatch(facei); } } } Info<< "Number of isoAdvector surface cells = " << returnReduce(nSurfaceCells, sumOp<label>()) << endl; } CML::scalar CML::isoAdvection::timeIntegratedFaceFlux ( const label facei, const vector& x0, const vector& n0, const scalar Un0, const scalar f0, const scalar dt, const scalar phi, const scalar magSf ) { // Treating rare cases where isoface normal is not calculated properly if (mag(n0) < 0.5) { scalar alphaf = 0; scalar waterInUpwindCell = 0; if (phi > 10*SMALL || !mesh_.isInternalFace(facei)) { const label upwindCell = mesh_.faceOwner()[facei]; alphaf = alpha1In_[upwindCell]; waterInUpwindCell = alphaf*mesh_.cellVolumes()[upwindCell]; } else { const label upwindCell = mesh_.faceNeighbour()[facei]; alphaf = alpha1In_[upwindCell]; waterInUpwindCell = alphaf*mesh_.cellVolumes()[upwindCell]; } if (debug) { WarningInFunction << "mag(n0) = " << mag(n0) << " so timeIntegratedFlux calculates dVf from upwind" << " cell alpha value: " << alphaf << endl; } return min(alphaf*phi*dt, waterInUpwindCell); } // Find sorted list of times where the isoFace will arrive at face points // given initial position x0 and velocity Un0*n0 // Get points for this face const face& f = mesh_.faces()[facei]; const pointField fPts(f.points(mesh_.points())); const label nPoints = fPts.size(); scalarField pTimes(fPts.size()); if (mag(Un0) > 10*SMALL) // Note: tolerances { // Here we estimate time of arrival to the face points from their normal // distance to the initial surface and the surface normal velocity pTimes = ((fPts - x0) & n0)/Un0; scalar dVf = 0; // Check if pTimes changes direction more than twice when looping face label nShifts = 0; forAll(pTimes, pi) { const label oldEdgeSign = sign(pTimes[(pi + 1) % nPoints] - pTimes[pi]); const label newEdgeSign = sign(pTimes[(pi + 2) % nPoints] - pTimes[(pi + 1) % nPoints]); if (newEdgeSign != oldEdgeSign) { nShifts++; } } if (nShifts == 2) { dVf = phi/magSf *isoCutFace_.timeIntegratedArea(fPts, pTimes, dt, magSf, Un0); } else if (nShifts > 2) { // Triangle decompose the face pointField fPts_tri(3); scalarField pTimes_tri(3); fPts_tri[0] = mesh_.faceCentres()[facei]; pTimes_tri[0] = ((fPts_tri[0] - x0) & n0)/Un0; for (label pi = 0; pi < nPoints; pi++) { fPts_tri[1] = fPts[pi]; pTimes_tri[1] = pTimes[pi]; fPts_tri[2] = fPts[(pi + 1) % nPoints]; pTimes_tri[2] = pTimes[(pi + 1) % nPoints]; const scalar magSf_tri = mag ( 0.5 *(fPts_tri[2] - fPts_tri[0]) ^(fPts_tri[1] - fPts_tri[0]) ); const scalar phi_tri = phi*magSf_tri/magSf; dVf += phi_tri /magSf_tri *isoCutFace_.timeIntegratedArea ( fPts_tri, pTimes_tri, dt, magSf_tri, Un0 ); } } else { if (debug) { WarningInFunction << "Warning: nShifts = " << nShifts << " on face " << facei << " with pTimes = " << pTimes << " owned by cell " << mesh_.faceOwner()[facei] << endl; } } return dVf; } else { // Un0 is almost zero and isoFace is treated as stationary isoCutFace_.calcSubFace(facei, f0); const scalar alphaf = mag(isoCutFace_.subFaceArea()/magSf); if (debug) { WarningInFunction << "Un0 is almost zero (" << Un0 << ") - calculating dVf on face " << facei << " using subFaceFraction giving alphaf = " << alphaf << endl; } return phi*dt*alphaf; } } void CML::isoAdvection::setDownwindFaces ( const label celli, DynamicLabelList& downwindFaces ) const { if (debug) { InfoInFunction << endl; } // Get necessary mesh data and cell information const labelList& own = mesh_.faceOwner(); const cellList& cells = mesh_.cells(); const cell& c = cells[celli]; downwindFaces.clear(); // Check all faces of the cell forAll(c, fi) { // Get face and corresponding flux const label facei = c[fi]; const scalar phi = faceValue(phi_, facei); if (own[facei] == celli) { if (phi > 10*SMALL) { downwindFaces.append(facei); } } else if (phi < -10*SMALL) { downwindFaces.append(facei); } } downwindFaces.shrink(); } void CML::isoAdvection::limitFluxes() { if (debug) { InfoInFunction << endl; } // Get time step size const scalar dt = mesh_.time().deltaT().value(); // scalarField alphaNew = alpha1In_ - fvc::surfaceIntegrate(dVf_); const scalar aTol = 1.0e-12; // Note: tolerances const scalar maxAlphaMinus1 = 1; // max(alphaNew - 1); const scalar minAlpha = -1; // min(alphaNew); const label nUndershoots = 20; // sum(neg(alphaNew + aTol)); const label nOvershoots = 20; // sum(pos(alphaNew - 1 - aTol)); cellIsBounded_ = false; // Loop number of bounding steps for (label n = 0; n < nAlphaBounds_; n++) { Info<< "isoAdvection: bounding iteration " << n + 1 << endl; if (maxAlphaMinus1 > aTol) // Note: tolerances { if (debug) Info << "Bound from above... " << endl; surfaceScalarField dVfcorrected("dVfcorrected", dVf_); DynamicList<label> correctedFaces(3*nOvershoots); boundFromAbove(alpha1In_, dVfcorrected, correctedFaces); forAll(correctedFaces, fi) { label facei = correctedFaces[fi]; // Change to treat boundaries consistently setFaceValue(dVf_, facei, faceValue(dVfcorrected, facei)); } syncProcPatches(dVf_, phi_); } if (minAlpha < -aTol) // Note: tolerances { if (debug) Info << "Bound from below... " << endl; scalarField alpha2(1.0 - alpha1In_); surfaceScalarField dVfcorrected ( "dVfcorrected", phi_*dimensionedScalar("dt", dimTime, dt) - dVf_ ); // dVfcorrected -= dVf_; // phi_ and dVf_ have same sign and dVf_ is // the portion of phi_*dt that is water. // If phi_ > 0 then dVf_ > 0 and mag(phi_*dt-dVf_) < mag(phi_*dt) as // it should. // If phi_ < 0 then dVf_ < 0 and mag(phi_*dt-dVf_) < mag(phi_*dt) as // it should. DynamicList<label> correctedFaces(3*nUndershoots); boundFromAbove(alpha2, dVfcorrected, correctedFaces); forAll(correctedFaces, fi) { label facei = correctedFaces[fi]; // Change to treat boundaries consistently scalar phi = faceValue(phi_, facei); scalar dVcorr = faceValue(dVfcorrected, facei); setFaceValue(dVf_, facei, phi*dt - dVcorr); } syncProcPatches(dVf_, phi_); } if (debug) { // Check if still unbounded scalarField alphaNew(alpha1In_ - fvc::surfaceIntegrate(dVf_)()); label maxAlphaMinus1 = max(alphaNew - 1); scalar minAlpha = min(alphaNew); label nUndershoots = sum(neg(alphaNew + aTol)); label nOvershoots = sum(pos(alphaNew - 1 - aTol)); Info<< "After bounding number " << n + 1 << " of time " << mesh_.time().value() << ":" << endl; Info<< "nOvershoots = " << nOvershoots << " with max(alphaNew-1) = " << maxAlphaMinus1 << " and nUndershoots = " << nUndershoots << " with min(alphaNew) = " << minAlpha << endl; } } } void CML::isoAdvection::boundFromAbove ( const scalarField& alpha1, surfaceScalarField& dVf, DynamicList<label>& correctedFaces ) { if (debug) { InfoInFunction << endl; } correctedFaces.clear(); scalar aTol = 10*SMALL; // Note: tolerances const scalarField& meshV = mesh_.cellVolumes(); const scalar dt = mesh_.time().deltaTValue(); DynamicList<label> downwindFaces(10); DynamicList<label> facesToPassFluidThrough(downwindFaces.size()); DynamicList<scalar> dVfmax(downwindFaces.size()); DynamicList<scalar> phi(downwindFaces.size()); // Loop through alpha cell centred field forAll(alpha1, celli) { if (checkBounding_[celli]) { const scalar Vi = meshV[celli]; scalar alpha1New = alpha1[celli] - netFlux(dVf, celli)/Vi; scalar alphaOvershoot = alpha1New - 1.0; scalar fluidToPassOn = alphaOvershoot*Vi; label nFacesToPassFluidThrough = 1; bool firstLoop = true; // First try to pass surplus fluid on to neighbour cells that are // not filled and to which dVf < phi*dt while (alphaOvershoot > aTol && nFacesToPassFluidThrough > 0) { if (debug) { Info << "\n\nBounding cell " << celli << " with alpha overshooting " << alphaOvershoot << endl; } facesToPassFluidThrough.clear(); dVfmax.clear(); phi.clear(); cellIsBounded_[celli] = true; // Find potential neighbour cells to pass surplus phase to setDownwindFaces(celli, downwindFaces); scalar dVftot = 0; nFacesToPassFluidThrough = 0; forAll(downwindFaces, fi) { const label facei = downwindFaces[fi]; const scalar phif = faceValue(phi_, facei); const scalar dVff = faceValue(dVf, facei); const scalar maxExtraFaceFluidTrans = mag(phif*dt - dVff); // dVf has same sign as phi and so if phi>0 we have // mag(phi_[facei]*dt) - mag(dVf[facei]) = phi_[facei]*dt // - dVf[facei] // If phi < 0 we have mag(phi_[facei]*dt) - // mag(dVf[facei]) = -phi_[facei]*dt - (-dVf[facei]) > 0 // since mag(dVf) < phi*dt if (debug) { Info << "downwindFace " << facei << " has maxExtraFaceFluidTrans = " << maxExtraFaceFluidTrans << endl; } if (maxExtraFaceFluidTrans/Vi > aTol) { // if (maxExtraFaceFluidTrans/Vi > aTol && // mag(dVfIn[facei])/Vi > aTol) //Last condition may be // important because without this we will flux through uncut // downwind faces facesToPassFluidThrough.append(facei); phi.append(phif); dVfmax.append(maxExtraFaceFluidTrans); dVftot += mag(phif*dt); } } if (debug) { Info << "\nfacesToPassFluidThrough: " << facesToPassFluidThrough << ", dVftot = " << dVftot << " m3 corresponding to dalpha = " << dVftot/Vi << endl; } forAll(facesToPassFluidThrough, fi) { const label facei = facesToPassFluidThrough[fi]; scalar fluidToPassThroughFace = fluidToPassOn*mag(phi[fi]*dt)/dVftot; nFacesToPassFluidThrough += pos(dVfmax[fi] - fluidToPassThroughFace); fluidToPassThroughFace = min(fluidToPassThroughFace, dVfmax[fi]); scalar dVff = faceValue(dVf, facei); dVff += sign(phi[fi])*fluidToPassThroughFace; setFaceValue(dVf, facei, dVff); if (firstLoop) { checkIfOnProcPatch(facei); correctedFaces.append(facei); } } firstLoop = false; alpha1New = alpha1[celli] - netFlux(dVf, celli)/Vi; alphaOvershoot = alpha1New - 1.0; fluidToPassOn = alphaOvershoot*Vi; if (debug) Info<< "\nNew alpha for cell " << celli << ": "<< alpha1New << endl; } } } if (debug) Info << "correctedFaces = " << correctedFaces << endl; } CML::scalar CML::isoAdvection::netFlux ( const surfaceScalarField& dVf, const label celli ) const { scalar dV = 0; // Get face indices const cell& c = mesh_.cells()[celli]; // Get mesh data const labelList& own = mesh_.faceOwner(); forAll(c, fi) { const label facei = c[fi]; const scalar dVff = faceValue(dVf, facei); if (own[facei] == celli) { dV += dVff; } else { dV -= dVff; } } return dV; } void CML::isoAdvection::syncProcPatches ( surfaceScalarField& dVf, const surfaceScalarField& phi ) { const polyBoundaryMesh& patches = mesh_.boundaryMesh(); if (Pstream::parRun()) { // Send forAll(procPatchLabels_, i) { const label patchi = procPatchLabels_[i]; const processorPolyPatch& procPatch = refCast<const processorPolyPatch>(patches[patchi]); const scalarField& pFlux = dVf.boundaryField()[patchi]; const List<label>& surfCellFacesOnProcPatch = surfaceCellFacesOnProcPatches_[patchi]; const UIndirectList<scalar> dVfPatch ( pFlux, surfCellFacesOnProcPatch ); // Send data to neighbouring processor OPstream toNbr(Pstream::blocking, procPatch.neighbProcNo()); toNbr << surfCellFacesOnProcPatch << dVfPatch; } // Receive and combine forAll(procPatchLabels_, patchLabeli) { const label patchi = procPatchLabels_[patchLabeli]; const processorPolyPatch& procPatch = refCast<const processorPolyPatch>(patches[patchi]); List<label> faceIDs; List<scalar> nbrdVfs; IPstream fromNbr(Pstream::blocking, procPatch.neighbProcNo()); fromNbr >> faceIDs >> nbrdVfs; if (debug) { Pout<< "Received at time = " << mesh_.time().value() << ": surfCellFacesOnProcPatch = " << faceIDs << nl << "Received at time = " << mesh_.time().value() << ": dVfPatch = " << nbrdVfs << endl; } // Combine fluxes scalarField& localFlux = dVf.boundaryField()[patchi]; forAll(faceIDs, i) { const label facei = faceIDs[i]; localFlux[facei] = - nbrdVfs[i]; if (debug && mag(localFlux[facei] + nbrdVfs[i]) > 10*SMALL) { Pout<< "localFlux[facei] = " << localFlux[facei] << " and nbrdVfs[i] = " << nbrdVfs[i] << " for facei = " << facei << endl; } } } if (debug) { // Write out results for checking forAll(procPatchLabels_, patchLabeli) { const label patchi = procPatchLabels_[patchLabeli]; const scalarField& localFlux = dVf.boundaryField()[patchi]; Pout<< "time = " << mesh_.time().value() << ": localFlux = " << localFlux << endl; } } // Reinitialising list used for minimal parallel communication forAll(surfaceCellFacesOnProcPatches_, patchi) { surfaceCellFacesOnProcPatches_[patchi].clear(); } } } void CML::isoAdvection::checkIfOnProcPatch(const label facei) { if (!mesh_.isInternalFace(facei)) { const polyBoundaryMesh& pbm = mesh_.boundaryMesh(); const label patchi = pbm.patchID()[facei - mesh_.nInternalFaces()]; if (isA<processorPolyPatch>(pbm[patchi]) && pbm[patchi].size()) { const label patchFacei = pbm[patchi].whichFace(facei); surfaceCellFacesOnProcPatches_[patchi].append(patchFacei); } } } void CML::isoAdvection::advect() { if (debug) { InfoInFunction << endl; } scalar advectionStartTime = mesh_.time().elapsedCpuTime(); // Initialising dVf with upwind values // i.e. phi[facei]*alpha1[upwindCell[facei]]*dt dVf_ = upwind<scalar>(mesh_, phi_).flux(alpha1_)*mesh_.time().deltaT(); // Do the isoAdvection on surface cells timeIntegratedFlux(); // Synchronize processor patches syncProcPatches(dVf_, phi_); // Adjust dVf for unbounded cells limitFluxes(); // Advect the free surface alpha1_ -= fvc::surfaceIntegrate(dVf_); alpha1_.correctBoundaryConditions(); // Apply non-conservative bounding mechanisms (clipping and snapping) // Note: We should be able to write out alpha before this is done! applyBruteForceBounding(); // Write surface cell set and bound cell set if required by user writeSurfaceCells(); writeBoundedCells(); advectionTime_ += (mesh_.time().elapsedCpuTime() - advectionStartTime); } void CML::isoAdvection::applyBruteForceBounding() { bool alpha1Changed = false; scalar snapAlphaTol = dict_.lookupOrDefault<scalar>("snapTol", 0); if (snapAlphaTol > 0) { alpha1_ = alpha1_ *pos(alpha1_ - snapAlphaTol) *neg(alpha1_ - (1.0 - snapAlphaTol)) + pos(alpha1_ - (1.0 - snapAlphaTol)); alpha1Changed = true; } bool clip = dict_.lookupOrDefault<bool>("clip", true); if (clip) { alpha1_ = min(scalar(1.0), max(scalar(0.0), alpha1_)); alpha1Changed = true; } if (alpha1Changed) { alpha1_.correctBoundaryConditions(); } } void CML::isoAdvection::writeSurfaceCells() const { if (dict_.lookupOrDefault<bool>("writeSurfCells", false)) { cellSet cSet ( IOobject ( "surfCells", mesh_.time().timeName(), mesh_, IOobject::NO_READ ) ); forAll(surfCells_, i) { cSet.insert(surfCells_[i]); } cSet.write(); } } void CML::isoAdvection::writeBoundedCells() const { if (dict_.lookupOrDefault<bool>("writeBoundedCells", false)) { cellSet cSet ( IOobject ( "boundedCells", mesh_.time().timeName(), mesh_, IOobject::NO_READ ) ); forAll(cellIsBounded_, i) { if (cellIsBounded_[i]) { cSet.insert(i); } } cSet.write(); } } void CML::isoAdvection::writeIsoFaces ( const DynamicList<List<point> >& faces ) const { // Writing isofaces to obj file for inspection, e.g. in paraview const fileName dirName ( Pstream::parRun() ? mesh_.time().path()/".."/"isoFaces" : mesh_.time().path()/"isoFaces" ); const string fName ( "isoFaces_" + CML::name(mesh_.time().timeIndex()) ); if (Pstream::parRun()) { // Collect points from all the processors List<DynamicList<List<point> > > allProcFaces(Pstream::nProcs()); allProcFaces[Pstream::myProcNo()] = faces; Pstream::gatherList(allProcFaces); if (Pstream::master()) { mkDir(dirName); OBJstream os(dirName/fName + ".obj"); Info<< nl << "isoAdvection: writing iso faces to file: " << os.name() << nl << endl; face f; forAll(allProcFaces, proci) { const DynamicList<List<point> >& procFacePts = allProcFaces[proci]; forAll(procFacePts, i) { const List<point>& facePts = procFacePts[i]; if (facePts.size() != f.size()) { f = face(identity(facePts.size())); } os.write(f, facePts, false); } } } } else { mkDir(dirName); OBJstream os(dirName/fName + ".obj"); Info<< nl << "isoAdvection: writing iso faces to file: " << os.name() << nl << endl; face f; forAll(faces, i) { const List<point>& facePts = faces[i]; if (facePts.size() != f.size()) { f = face(identity(facePts.size())); } os.write(f, facePts, false); } } } // ************************************************************************* //
31.081702
95
0.501027
[ "mesh", "object", "vector" ]
33ddf3d533f7f2167d74873cedacdf6b99febc20
3,102
cpp
C++
aws-cpp-sdk-s3/source/model/SelectParameters.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-s3/source/model/SelectParameters.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-s3/source/model/SelectParameters.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/s3/model/SelectParameters.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace S3 { namespace Model { SelectParameters::SelectParameters() : m_inputSerializationHasBeenSet(false), m_expressionType(ExpressionType::NOT_SET), m_expressionTypeHasBeenSet(false), m_expressionHasBeenSet(false), m_outputSerializationHasBeenSet(false) { } SelectParameters::SelectParameters(const XmlNode& xmlNode) : m_inputSerializationHasBeenSet(false), m_expressionType(ExpressionType::NOT_SET), m_expressionTypeHasBeenSet(false), m_expressionHasBeenSet(false), m_outputSerializationHasBeenSet(false) { *this = xmlNode; } SelectParameters& SelectParameters::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode inputSerializationNode = resultNode.FirstChild("InputSerialization"); if(!inputSerializationNode.IsNull()) { m_inputSerialization = inputSerializationNode; m_inputSerializationHasBeenSet = true; } XmlNode expressionTypeNode = resultNode.FirstChild("ExpressionType"); if(!expressionTypeNode.IsNull()) { m_expressionType = ExpressionTypeMapper::GetExpressionTypeForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(expressionTypeNode.GetText()).c_str()).c_str()); m_expressionTypeHasBeenSet = true; } XmlNode expressionNode = resultNode.FirstChild("Expression"); if(!expressionNode.IsNull()) { m_expression = Aws::Utils::Xml::DecodeEscapedXmlText(expressionNode.GetText()); m_expressionHasBeenSet = true; } XmlNode outputSerializationNode = resultNode.FirstChild("OutputSerialization"); if(!outputSerializationNode.IsNull()) { m_outputSerialization = outputSerializationNode; m_outputSerializationHasBeenSet = true; } } return *this; } void SelectParameters::AddToNode(XmlNode& parentNode) const { Aws::StringStream ss; if(m_inputSerializationHasBeenSet) { XmlNode inputSerializationNode = parentNode.CreateChildElement("InputSerialization"); m_inputSerialization.AddToNode(inputSerializationNode); } if(m_expressionTypeHasBeenSet) { XmlNode expressionTypeNode = parentNode.CreateChildElement("ExpressionType"); expressionTypeNode.SetText(ExpressionTypeMapper::GetNameForExpressionType(m_expressionType)); } if(m_expressionHasBeenSet) { XmlNode expressionNode = parentNode.CreateChildElement("Expression"); expressionNode.SetText(m_expression); } if(m_outputSerializationHasBeenSet) { XmlNode outputSerializationNode = parentNode.CreateChildElement("OutputSerialization"); m_outputSerialization.AddToNode(outputSerializationNode); } } } // namespace Model } // namespace S3 } // namespace Aws
28.458716
176
0.759188
[ "model" ]
33e067a18b961ab7424a45acd8e9744d73bbb263
10,634
cc
C++
src/thor/map_matcher.cc
jendrusk/valhalla
e21b3160b25c3565ba0fe44e572b3d4945fed810
[ "MIT" ]
null
null
null
src/thor/map_matcher.cc
jendrusk/valhalla
e21b3160b25c3565ba0fe44e572b3d4945fed810
[ "MIT" ]
null
null
null
src/thor/map_matcher.cc
jendrusk/valhalla
e21b3160b25c3565ba0fe44e572b3d4945fed810
[ "MIT" ]
null
null
null
#include "midgard/logging.h" #include <algorithm> #include <exception> #include <vector> #include "baldr/datetime.h" #include "thor/map_matcher.h" using namespace valhalla::baldr; using namespace valhalla::sif; namespace valhalla { namespace thor { struct interpolation_t { baldr::GraphId edge; // edge id float total_distance; // distance along the path float edge_distance; // ratio of the distance along the edge size_t original_index; // index into the original measurements double epoch_time; // seconds from epoch }; std::list<std::vector<interpolation_t>> interpolate_matches(const std::vector<meili::MatchResult>& matches, const std::vector<meili::EdgeSegment>& edges, meili::MapMatcher* matcher) { // TODO: backtracking could have happened. maybe it really happened but maybe there were // positional inaccuracies. for now we should detect when there are backtracks and give up // otherwise the the timing reported here might be suspect // find each set of continuous edges std::list<std::vector<interpolation_t>> interpolations; size_t idx = 0; for (auto begin_edge = edges.cbegin(), end_edge = edges.cbegin() + 1; begin_edge != edges.cend(); begin_edge = end_edge, end_edge += 1) { // find the end of the this block while (end_edge != edges.cend()) { if (!matcher->graphreader().AreEdgesConnectedForward(std::prev(end_edge)->edgeid, end_edge->edgeid)) { break; } ++end_edge; } // go through each edge and each match keeping the distance each point is along the entire trace std::vector<interpolation_t> interpolated; size_t last_idx = idx; for (auto segment = begin_edge; segment != end_edge; ++segment) { float edge_length = matcher->graphreader() .GetGraphTile(segment->edgeid) ->directededge(segment->edgeid) ->length(); float total_length = segment == begin_edge ? -edges.front().source * edge_length : interpolated.back().total_distance; // get the distance and match result for the begin node of the edge interpolated.emplace_back(interpolation_t{segment->edgeid, total_length, 0.f, last_idx, -1}); // add distances for all the match points that happened on this edge for (; idx < matches.size(); ++idx) { // skip unroutable ones, we dont know what edge they were on if (!matches[idx].edgeid.Is_Valid()) { continue; // if its a valid one that doesnt match we move on } else if (matches[idx].edgeid != segment->edgeid) { break; } // it was the right thing we were looking for interpolated.emplace_back( interpolation_t{segment->edgeid, matches[idx].distance_along * edge_length + total_length, matches[idx].distance_along, idx, matches[idx].epoch_time}); last_idx = idx; } // add the end node of the edge interpolated.emplace_back( interpolation_t{segment->edgeid, edge_length + total_length, 1.f, last_idx, -1}); } // finally backfill the time information for those points that dont have it auto backfill = interpolated.begin(); while (backfill != interpolated.end()) { // this one is done already if (backfill->epoch_time != -1) { ++backfill; continue; } // find the range that have values (or the ends of the range auto left = backfill != interpolated.begin() ? std::prev(backfill) : backfill; auto right = std::next(backfill); for (; right != interpolated.end() && right->epoch_time == -1; ++right) { ; } // backfill between left and right while (backfill != right) { // if both indices are valid we interpolate if (left != interpolated.begin() && right != interpolated.end()) { double time_diff = right->epoch_time - left->epoch_time; float distance_diff = right->total_distance - left->total_distance; float distance_ratio = distance_diff > 0 ? (backfill->total_distance - left->total_distance) / distance_diff : 0.f; backfill->epoch_time = left->epoch_time + distance_ratio * time_diff; } // if left index is valid we carry it forward if we can else if (left != interpolated.begin() && backfill->total_distance == left->total_distance) { backfill->epoch_time = left->epoch_time; backfill->original_index = left->original_index; } // right index is valid we carry it forward if we can else if (right != interpolated.end() && backfill->total_distance == right->total_distance) { backfill->epoch_time = right->epoch_time; backfill->original_index = right->original_index; } // next backfill ++backfill; } } // keep this set of interpolations interpolations.emplace_back(std::move(interpolated)); } // give back the distances and updated match results return interpolations; } // Form the path from the map-matching results. This path gets sent to // TripLegBuilder. std::vector<PathInfo> MapMatcher::FormPath(meili::MapMatcher* matcher, const std::vector<meili::MatchResult>& results, const std::vector<meili::EdgeSegment>& edge_segments, const std::shared_ptr<sif::DynamicCost>* mode_costing, const sif::TravelMode mode, std::vector<std::pair<GraphId, GraphId>>& disconnected_edges, Options& options) { // Set costing based on the mode const auto& costing = mode_costing[static_cast<uint32_t>(mode)]; bool use_timestamps = options.use_timestamps(); // Iterate through the matched path. Form PathInfo - populate elapsed time // Return an empty path (or throw exception) if path is not connected. Cost elapsed; std::vector<PathInfo> path; GraphId prior_edge, prior_node; EdgeLabel pred; const GraphTile* tile = nullptr; const DirectedEdge* directededge = nullptr; const NodeInfo* nodeinfo = nullptr; // We support either the epoch timestamp that came with the trace point or // a local date time which we convert to epoch by finding the first timezone uint32_t origin_epoch = 0; for (const auto& s : edge_segments) { if (!s.edgeid.Is_Valid() || !matcher->graphreader().GetGraphTile(s.edgeid, tile)) continue; directededge = tile->directededge(s.edgeid); if (matcher->graphreader().GetGraphTile(directededge->endnode(), tile)) { // get the timezone nodeinfo = tile->node(directededge->endnode()); const auto* tz = DateTime::get_tz_db().from_index(nodeinfo->timezone()); // if its timestamp based need to signal that out to trip leg builder if (options.shape(0).time() != -1.0) { options.mutable_shape(0)->set_date_time( DateTime::seconds_to_date(options.shape(0).time(), tz, false)); } // remember where we are starting if (options.shape(0).has_date_time()) origin_epoch = DateTime::seconds_since_epoch(options.shape(0).date_time(), tz); break; } } // Interpolate match results if using timestamps for elapsed time std::list<std::vector<interpolation_t>> interpolations; size_t interpolated_index = 0; size_t last_interp_index = 0; if (use_timestamps) { interpolations = interpolate_matches(results, edge_segments, matcher); // This means there is a discontinuity. If so, fallback to using costing if (interpolations.size() != 1) use_timestamps = false; else last_interp_index = interpolations.front().back().original_index; } // Build the path for (const auto& edge_segment : edge_segments) { // Skip edges that are the same as the prior edge if (edge_segment.edgeid == prior_edge) { continue; } // Get the directed edge GraphId edge_id = edge_segment.edgeid; matcher->graphreader().GetGraphTile(edge_id, tile); directededge = tile->directededge(edge_id); // Check if connected to prior edge if (prior_edge.Is_Valid() && !matcher->graphreader().AreEdgesConnectedForward(prior_edge, edge_id)) { disconnected_edges.emplace_back(prior_edge, edge_id); } // Get seconds from beginning of the week accounting for any changes to timezone on the path uint32_t second_of_week = kInvalidSecondsOfWeek; if (origin_epoch != 0 && nodeinfo) { second_of_week = DateTime::second_of_week(origin_epoch + static_cast<uint32_t>(elapsed.secs), DateTime::get_tz_db().from_index(nodeinfo->timezone())); } // get the cost of traversing the node, there is no turn cost the first time if (elapsed.secs > 0) elapsed += costing->TransitionCost(directededge, nodeinfo, pred); // Get time along the edge, handling partial distance along the first and last edge. elapsed += costing->EdgeCost(directededge, tile, second_of_week) * (edge_segment.target - edge_segment.source); if (use_timestamps) { // Use timestamps to update elapsed time. Use the timestamp at the interpolation // that no longer matches the edge_id (or the last interpolation if the edge id // matches the rest of the interpolations). size_t idx = last_interp_index; for (size_t i = interpolated_index; i < interpolations.front().size(); ++i) { if (interpolations.front()[i].edge != edge_id) { // Set the index into the match results, update the interpolated index to // start search for next edge id idx = interpolations.front()[i].original_index; interpolated_index = i; break; } } elapsed.secs = results[idx].epoch_time - results[0].epoch_time; } // Update the prior_edge and nodeinfo. TODO (protect against invalid tile) prior_edge = edge_id; prior_node = directededge->endnode(); const GraphTile* end_tile = matcher->graphreader().GetGraphTile(prior_node); nodeinfo = end_tile->node(prior_node); // Create a predecessor EdgeLabel (for transition costing) pred = {kInvalidLabel, edge_id, directededge, {}, 0, 0, mode, 0}; // Add to the PathInfo path.emplace_back(mode, elapsed.secs, edge_id, 0, elapsed.cost); } return path; } } // namespace thor } // namespace valhalla
42.366534
102
0.649803
[ "shape", "vector" ]
33e19899f34385662a3e32259256fd7a51c62224
1,431
cpp
C++
aoc2020/day10/main.cpp
madfist/aoc2016
1e79c39506dd2cb5f4533c375f59005f5668cb93
[ "MIT" ]
1
2019-12-06T09:39:48.000Z
2019-12-06T09:39:48.000Z
aoc2020/day10/main.cpp
madfist/aoc2016
1e79c39506dd2cb5f4533c375f59005f5668cb93
[ "MIT" ]
null
null
null
aoc2020/day10/main.cpp
madfist/aoc2016
1e79c39506dd2cb5f4533c375f59005f5668cb93
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <vector> #include <algorithm> int task1(std::vector<int>& nums) { std::stable_sort(nums.begin(), nums.end()); nums.push_back(nums.back() + 3); int ones = 0; int twos = 0; int threes = 0; int prev = 0; for (auto i = nums.begin(); i != nums.end(); ++i) { switch (*i - prev) { case 1: ++ones; break; case 2: ++twos; break; case 3: ++threes; break; } prev = *i; } // std::cout << ones << '+' << twos << '+' << threes << '\n'; return ones * threes; } long task2(std::vector<int>& nums) { long perm = 1; int prev = 0; int ones = 0; for (auto i = nums.begin(); i != nums.end(); ++i) { switch (*i - prev) { case 1: ++ones; break; case 3: switch(ones) { case 2: perm *= 2; break; case 3: perm *= 4; break; case 4: perm *= 7; break; } std::cout << "ones " << ones << ' ' << perm << '\n'; ones = 0; break; } prev = *i; } std::cout << '\n'; return perm; } int main(int argc, char** argv) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " <input>\n"; } std::ifstream inf(argv[1]); std::vector<int> nums; int num; while(inf >> num) { nums.push_back(num); } std::cout << task1(nums) << '\n'; std::cout << task2(nums) << '\n'; return 0; }
20.442857
63
0.466108
[ "vector" ]
33e2a0ff1c86c5e8307b53300413184bff4e22c4
3,465
hh
C++
gazebo/common/CommonIface.hh
harderthan/gazebo
f00a0e4239ddb08b299dc21ab1ef106ecedb0fac
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/common/CommonIface.hh
harderthan/gazebo
f00a0e4239ddb08b299dc21ab1ef106ecedb0fac
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/common/CommonIface.hh
harderthan/gazebo
f00a0e4239ddb08b299dc21ab1ef106ecedb0fac
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2012-2015 Open Source Robotics 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. * */ #ifndef _COMMONIFACE_HH_ #define _COMMONIFACE_HH_ #include <string> #include <vector> #include <boost/version.hpp> #if BOOST_VERSION < 106700 #include <boost/uuid/sha1.hpp> #else #include <boost/uuid/detail/sha1.hpp> #endif #include <boost/filesystem.hpp> #include <iomanip> #include <sstream> #include "gazebo/util/system.hh" namespace gazebo { namespace common { /// \addtogroup gazebo_common /// \{ /// \brief Load the common library. GZ_COMMON_VISIBLE void load(); /// \brief add path sufix to common::SystemPaths /// \param[in] _suffix The suffix to add. GZ_COMMON_VISIBLE void add_search_path_suffix(const std::string &_suffix); /// \brief search for file in common::SystemPaths /// \param[in] _file Name of the file to find. /// \return The path containing the file. GZ_COMMON_VISIBLE std::string find_file(const std::string &_file); /// \brief search for file in common::SystemPaths /// \param[in] _file Name of the file to find. /// \param[in] _searchLocalPath True to search in the current working /// directory. /// \return The path containing the file. GZ_COMMON_VISIBLE std::string find_file(const std::string &_file, bool _searchLocalPath); /// \brief search for a file in common::SystemPaths /// \param[in] _file the file name to look for. /// \return The path containing the file. GZ_COMMON_VISIBLE std::string find_file_path(const std::string &_file); /// \brief Compute the SHA1 hash of an array of bytes. /// \param[in] _buffer Input sequence. The permitted data types for this /// function are std::string and any STL container. /// \return The string representation (40 character) of the SHA1 hash. template<typename T> std::string get_sha1(const T &_buffer); /// \brief Cross platform retrieval of an environment variable. /// \param[in] _name Name of the environment variable to get. /// \return Environment variable contents, or NULL on error. GZ_COMMON_VISIBLE const char *getEnv(const char *_name); /// \} } /////////////////////////////////////////////// // Implementation of get_sha1 template<typename T> std::string common::get_sha1(const T &_buffer) { boost::uuids::detail::sha1 sha1; unsigned int hash[5]; std::stringstream stream; if (_buffer.size() == 0) { sha1.process_bytes(NULL, 0); } else { sha1.process_bytes(&(_buffer[0]), _buffer.size() * sizeof(_buffer[0])); } sha1.get_digest(hash); for (std::size_t i = 0; i < sizeof(hash) / sizeof(hash[0]); ++i) { stream << std::setfill('0') << std::setw(sizeof(hash[0]) * 2) << std::hex << hash[i]; } return stream.str(); } } #endif
28.636364
77
0.652237
[ "vector" ]
33e9a894cc0fbe7c6feda56ce05b47a960ae309e
74,434
cpp
C++
src/mongo/dbtests/updatetests.cpp
stevelyall/mongol-db
d8046147bfe806f7acc0ec4aa70c132507b761fb
[ "Apache-2.0" ]
1
2018-03-16T09:49:05.000Z
2018-03-16T09:49:05.000Z
src/mongo/dbtests/updatetests.cpp
stevelyall/mongol-db
d8046147bfe806f7acc0ec4aa70c132507b761fb
[ "Apache-2.0" ]
null
null
null
src/mongo/dbtests/updatetests.cpp
stevelyall/mongol-db
d8046147bfe806f7acc0ec4aa70c132507b761fb
[ "Apache-2.0" ]
null
null
null
// updatetests.cpp : unit tests relating to update requests // /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #include "mongol/platform/basic.h" #include <iostream> #include "mongol/bson/mutable/mutable_bson_test_utils.h" #include "mongol/client/dbclientcursor.h" #include "mongol/db/db.h" #include "mongol/db/dbdirectclient.h" #include "mongol/db/json.h" #include "mongol/db/lasterror.h" #include "mongol/db/ops/update.h" #include "mongol/db/operation_context_impl.h" #include "mongol/dbtests/dbtests.h" namespace UpdateTests { using std::unique_ptr; using std::numeric_limits; using std::string; using std::stringstream; using std::vector; class ClientBase { public: ClientBase() : _client(&_txn) { mongol::LastError::get(_txn.getClient()).reset(); } virtual ~ClientBase() { mongol::LastError::get(_txn.getClient()).reset(); } protected: void insert(const char* ns, BSONObj o) { _client.insert(ns, o); } void update(const char* ns, BSONObj q, BSONObj o, bool upsert = 0) { _client.update(ns, Query(q), o, upsert); } bool error() { return !_client.getPrevError().getField("err").isNull(); } OperationContextImpl _txn; DBDirectClient _client; }; class Fail : public ClientBase { public: virtual ~Fail() {} void run() { prep(); ASSERT(!error()); doIt(); ASSERT(error()); } protected: const char* ns() { return "unittests.UpdateTests_Fail"; } virtual void prep() { insert(ns(), fromjson("{a:1}")); } virtual void doIt() = 0; }; class ModId : public Fail { void doIt() { update(ns(), BSONObj(), fromjson("{$set:{'_id':4}}")); } }; class ModNonmodMix : public Fail { void doIt() { update(ns(), BSONObj(), fromjson("{$set:{a:4},z:3}")); } }; class InvalidMod : public Fail { void doIt() { update(ns(), BSONObj(), fromjson("{$awk:{a:4}}")); } }; class ModNotFirst : public Fail { void doIt() { update(ns(), BSONObj(), fromjson("{z:3,$set:{a:4}}")); } }; class ModDuplicateFieldSpec : public Fail { void doIt() { update(ns(), BSONObj(), fromjson("{$set:{a:4},$inc:{a:1}}")); } }; class IncNonNumber : public Fail { void doIt() { update(ns(), BSONObj(), fromjson("{$inc:{a:'d'}}")); } }; class PushAllNonArray : public Fail { void doIt() { insert(ns(), fromjson("{a:[1]}")); update(ns(), BSONObj(), fromjson("{$pushAll:{a:'d'}}")); } }; class PullAllNonArray : public Fail { void doIt() { insert(ns(), fromjson("{a:[1]}")); update(ns(), BSONObj(), fromjson("{$pullAll:{a:'d'}}")); } }; class IncTargetNonNumber : public Fail { void doIt() { insert(ns(), BSON("a" << "a")); update(ns(), BSON("a" << "a"), fromjson("{$inc:{a:1}}")); } }; class SetBase : public ClientBase { public: ~SetBase() { _client.dropCollection(ns()); } protected: const char* ns() { return "unittests.updatetests.SetBase"; } }; class SetNum : public SetBase { public: void run() { _client.insert(ns(), BSON("a" << 1)); _client.update(ns(), BSON("a" << 1), BSON("$set" << BSON("a" << 4))); ASSERT(!_client.findOne(ns(), BSON("a" << 4)).isEmpty()); } }; class SetString : public SetBase { public: void run() { _client.insert(ns(), BSON("a" << "b")); _client.update(ns(), BSON("a" << "b"), BSON("$set" << BSON("a" << "c"))); ASSERT(!_client.findOne(ns(), BSON("a" << "c")).isEmpty()); } }; class SetStringDifferentLength : public SetBase { public: void run() { _client.insert(ns(), BSON("a" << "b")); _client.update(ns(), BSON("a" << "b"), BSON("$set" << BSON("a" << "cd"))); ASSERT(!_client.findOne(ns(), BSON("a" << "cd")).isEmpty()); } }; class SetStringToNum : public SetBase { public: void run() { _client.insert(ns(), BSON("a" << "b")); _client.update(ns(), Query(), BSON("$set" << BSON("a" << 5))); ASSERT(!_client.findOne(ns(), BSON("a" << 5)).isEmpty()); } }; class SetStringToNumInPlace : public SetBase { public: void run() { _client.insert(ns(), BSON("a" << "bcd")); _client.update(ns(), Query(), BSON("$set" << BSON("a" << 5.0))); ASSERT(!_client.findOne(ns(), BSON("a" << 5.0)).isEmpty()); } }; class SetOnInsertFromEmpty : public SetBase { public: void run() { // Try with upsert false first. _client.insert(ns(), BSONObj() /* empty document */); _client.update(ns(), Query(), BSON("$setOnInsert" << BSON("a" << 1)), false); ASSERT(_client.findOne(ns(), BSON("a" << 1)).isEmpty()); // Then with upsert true. _client.update(ns(), Query(), BSON("$setOnInsert" << BSON("a" << 1)), true); ASSERT(_client.findOne(ns(), BSON("a" << 1)).isEmpty()); } }; class SetOnInsertFromNonExistent : public SetBase { public: void run() { // Try with upsert false first. _client.update(ns(), Query(), BSON("$setOnInsert" << BSON("a" << 1)), false); ASSERT(_client.findOne(ns(), BSON("a" << 1)).isEmpty()); // Then with upsert true. _client.update(ns(), Query(), BSON("$setOnInsert" << BSON("a" << 1)), true); ASSERT(!_client.findOne(ns(), BSON("a" << 1)).isEmpty()); } }; class SetOnInsertFromNonExistentWithQuery : public SetBase { public: void run() { Query q("{a:1}"); // Try with upsert false first. _client.update(ns(), q, BSON("$setOnInsert" << BSON("b" << 1)), false); ASSERT(_client.findOne(ns(), BSON("a" << 1)).isEmpty()); // Then with upsert true. _client.update(ns(), q, BSON("$setOnInsert" << BSON("b" << 1)), true); ASSERT(!_client.findOne(ns(), BSON("a" << 1 << "b" << 1)).isEmpty()); } }; class SetOnInsertFromNonExistentWithQueryOverField : public SetBase { public: void run() { Query q("{a:1}"); // same field that we'll setOnInsert on // Try with upsert false first. _client.update(ns(), q, BSON("$setOnInsert" << BSON("a" << 2)), false); ASSERT(_client.findOne(ns(), BSON("a" << 1)).isEmpty()); // Then with upsert true. _client.update(ns(), q, BSON("$setOnInsert" << BSON("a" << 2)), true); ASSERT(!_client.findOne(ns(), BSON("a" << 2)).isEmpty()); } }; class SetOnInsertMissingField : public SetBase { public: void run() { BSONObj res = fromjson("{'_id':0, a:1}"); _client.insert(ns(), res); _client.update(ns(), Query(), BSON("$setOnInsert" << BSON("b" << 1))); ASSERT(_client.findOne(ns(), BSON("a" << 1)).woCompare(res) == 0); } }; class SetOnInsertExisting : public SetBase { public: void run() { _client.insert(ns(), BSON("a" << 1)); _client.update(ns(), Query(), BSON("$setOnInsert" << BSON("a" << 2))); ASSERT(!_client.findOne(ns(), BSON("a" << 1)).isEmpty()); } }; class SetOnInsertMixed : public SetBase { public: void run() { // Try with upsert false first. _client.update(ns(), Query(), BSON("$set" << BSON("a" << 1) << "$setOnInsert" << BSON("b" << 2)), false); ASSERT(_client.findOne(ns(), BSON("a" << 1 << "b" << 2)).isEmpty()); // Then with upsert true. _client.update(ns(), Query(), BSON("$set" << BSON("a" << 1) << "$setOnInsert" << BSON("b" << 2)), true); ASSERT(!_client.findOne(ns(), BSON("a" << 1 << "b" << 2)).isEmpty()); } }; class SetOnInsertMissingParent : public SetBase { public: void run() { // In a mod that uses dontApply, we should be careful not to create a // parent unneccesarily. BSONObj initial = fromjson("{'_id':0}"); BSONObj final = fromjson("{'_id':0, d:1}"); _client.insert(ns(), initial); _client.update( ns(), initial, BSON("$setOnInsert" << BSON("a.b" << 1) << "$set" << BSON("d" << 1))); ASSERT_EQUALS(_client.findOne(ns(), initial), final); } }; class ModDotted : public SetBase { public: void run() { _client.insert(ns(), fromjson("{a:{b:4}}")); _client.update(ns(), Query(), BSON("$inc" << BSON("a.b" << 10))); ASSERT(!_client.findOne(ns(), BSON("a.b" << 14)).isEmpty()); _client.update(ns(), Query(), BSON("$set" << BSON("a.b" << 55))); ASSERT(!_client.findOne(ns(), BSON("a.b" << 55)).isEmpty()); } }; class SetInPlaceDotted : public SetBase { public: void run() { _client.insert(ns(), fromjson("{a:{b:'cdef'}}")); _client.update(ns(), Query(), BSON("$set" << BSON("a.b" << "llll"))); ASSERT(!_client.findOne(ns(), BSON("a.b" << "llll")).isEmpty()); } }; class SetRecreateDotted : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:{b:'cdef'}}")); _client.update(ns(), Query(), BSON("$set" << BSON("a.b" << "lllll"))); ASSERT(_client.findOne(ns(), BSON("a.b" << "lllll")).woCompare(fromjson("{'_id':0,a:{b:'lllll'}}")) == 0); } }; class SetMissingDotted : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0}")); _client.update(ns(), BSONObj(), BSON("$set" << BSON("a.b" << "lllll"))); ASSERT(_client.findOne(ns(), BSON("a.b" << "lllll")).woCompare(fromjson("{'_id':0,a:{b:'lllll'}}")) == 0); } }; class SetAdjacentDotted : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:{c:4}}")); _client.update(ns(), Query(), BSON("$set" << BSON("a.b" << "lllll"))); ASSERT_EQUALS(mutablebson::unordered(_client.findOne(ns(), BSON("a.b" << "lllll"))), mutablebson::unordered(fromjson("{'_id':0,a:{b:'lllll',c:4}}"))); } }; class IncMissing : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0}")); _client.update(ns(), Query(), BSON("$inc" << BSON("f" << 3.0))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,f:3}")) == 0); } }; class MultiInc : public SetBase { public: string s() { stringstream ss; unique_ptr<DBClientCursor> cc = _client.query(ns(), Query().sort(BSON("_id" << 1))); bool first = true; while (cc->more()) { if (first) first = false; else ss << ","; BSONObj o = cc->next(); ss << o["x"].numberInt(); } return ss.str(); } void run() { _client.insert(ns(), BSON("_id" << 1 << "x" << 1)); _client.insert(ns(), BSON("_id" << 2 << "x" << 5)); ASSERT_EQUALS("1,5", s()); _client.update(ns(), BSON("_id" << 1), BSON("$inc" << BSON("x" << 1))); ASSERT_EQUALS("2,5", s()); _client.update(ns(), BSONObj(), BSON("$inc" << BSON("x" << 1))); ASSERT_EQUALS("3,5", s()); _client.update(ns(), BSONObj(), BSON("$inc" << BSON("x" << 1)), false, true); ASSERT_EQUALS("4,6", s()); } }; class UnorderedNewSet : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0}")); _client.update(ns(), Query(), BSON("$set" << BSON("f.g.h" << 3.0 << "f.g.a" << 2.0))); ASSERT_EQUALS(mutablebson::unordered(_client.findOne(ns(), Query())), mutablebson::unordered(fromjson("{'_id':0,f:{g:{a:2,h:3}}}"))); } }; class UnorderedNewSetAdjacent : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0}")); _client.update(ns(), BSONObj(), BSON("$set" << BSON("f.g.h.b" << 3.0 << "f.g.a.b" << 2.0))); ASSERT_EQUALS(mutablebson::unordered(_client.findOne(ns(), Query())), mutablebson::unordered(fromjson("{'_id':0,f:{g:{a:{b:2},h:{b:3}}}}"))); } }; class ArrayEmbeddedSet : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,z:[4,'b']}")); _client.update(ns(), Query(), BSON("$set" << BSON("z.0" << "a"))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,z:['a','b']}")); } }; class AttemptEmbedInExistingNum : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:1}")); _client.update(ns(), Query(), BSON("$set" << BSON("a.b" << 1))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:1}")) == 0); } }; class AttemptEmbedConflictsWithOtherSet : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0}")); _client.update(ns(), Query(), BSON("$set" << BSON("a" << 2 << "a.b" << 1))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0}")); } }; class ModMasksEmbeddedConflict : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:{b:2}}")); _client.update(ns(), Query(), BSON("$set" << BSON("a" << 2 << "a.b" << 1))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:{b:2}}")) == 0); } }; class ModOverwritesExistingObject : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:{b:2}}")); _client.update(ns(), Query(), BSON("$set" << BSON("a" << BSON("c" << 2)))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:{c:2}}")) == 0); } }; class InvalidEmbeddedSet : public Fail { public: virtual void doIt() { _client.update(ns(), Query(), BSON("$set" << BSON("a." << 1))); } }; class UpsertMissingEmbedded : public SetBase { public: void run() { _client.update(ns(), Query(), BSON("$set" << BSON("a.b" << 1)), true); ASSERT(!_client.findOne(ns(), QUERY("a.b" << 1)).isEmpty()); } }; class Push : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1]}")); _client.update(ns(), Query(), BSON("$push" << BSON("a" << 5))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[1,5]}")); } }; class PushInvalidEltType : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:1}")); _client.update(ns(), Query(), BSON("$push" << BSON("a" << 5))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:1}")) == 0); } }; class PushConflictsWithOtherMod : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1]}")); _client.update(ns(), Query(), BSON("$set" << BSON("a" << 1) << "$push" << BSON("a" << 5))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:[1]}")) == 0); } }; class PushFromNothing : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0}")); _client.update(ns(), Query(), BSON("$push" << BSON("a" << 5))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[5]}")); } }; class PushFromEmpty : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[]}")); _client.update(ns(), Query(), BSON("$push" << BSON("a" << 5))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:[5]}")) == 0); } }; class PushInsideNothing : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0}")); _client.update(ns(), Query(), BSON("$push" << BSON("a.b" << 5))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:{b:[5]}}")) == 0); } }; class CantPushInsideOtherMod : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0}")); _client.update( ns(), Query(), BSON("$set" << BSON("a" << BSONObj()) << "$push" << BSON("a.b" << 5))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0}")) == 0); } }; class CantPushTwice : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[]}")); _client.update(ns(), Query(), BSON("$push" << BSON("a" << 4) << "$push" << BSON("a" << 5))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:[]}")) == 0); } }; class SetEncapsulationConflictsWithExistingType : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:{b:4}}")); _client.update(ns(), Query(), BSON("$set" << BSON("a.b.c" << 4.0))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:{b:4}}")) == 0); } }; class CantPushToParent : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:{b:4}}")); _client.update(ns(), Query(), BSON("$push" << BSON("a" << 4.0))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:{b:4}}")) == 0); } }; class PushEachSimple : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1]}")); // { $push : { a : { $each : [ 2, 3 ] } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(2 << 3)); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[1,2,3]}")); } }; class PushEachFromEmpty : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[]}")); // { $push : { a : { $each : [ 1, 2, 3 ] } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(1 << 2 << 3)); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[1,2,3]}")); } }; class PushSliceBelowFull : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1]}")); // { $push : { a : { $each : [ 2 ] , $slice : -3 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(2) << "$slice" << -3); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[1,2]}")); } }; class PushSliceReachedFullExact : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1]}")); // { $push : { a : { $each : [ 2 ] , $slice : -2 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(2) << "$slice" << -2); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[1,2]}")); } }; class PushSliceReachedFullWithEach : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1]}")); // { $push : { a : { $each : [ 2 , 3 ] , $slice : -2 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(2 << 3) << "$slice" << -2); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[2,3]}")); } }; class PushSliceReachedFullWithBoth : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1,2]}")); // { $push : { a : { $each : [ 3 ] , $slice : -2 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(3) << "$slice" << -2); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[2,3]}")); } }; class PushSliceToZero : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1,2]}")); // { $push : { a : { $each : [ 3 ] , $slice : 0 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(3) << "$slice" << 0); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[]}")); } }; class PushSliceToZeroFromNothing : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0}")); // { $push : { a : { $each : [ 3 ] , $slice : 0 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(3) << "$slice" << 0); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[]}")); } }; class PushSliceFromNothing : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0}")); // { $push : { a : { $each : [ 1 , 2 ] , $slice : -3 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(1 << 2) << "$slice" << -3); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[1,2]}")); } }; class PushSliceLongerThanSliceFromNothing : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0}")); // { $push : { a : { $each : [ 1 , 2 , 3 ] , $slice : -2 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(1 << 2 << 3) << "$slice" << -2); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[2,3]}")); } }; class PushSliceFromEmpty : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[]}")); // { $push : { a : { $each : [ 1 ] , $slice : -3 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(1) << "$slice" << -3); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[1]}")); } }; class PushSliceLongerThanSliceFromEmpty : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[]}")); // { $push : { a : { $each : [ 1 , 2 , 3 ] , $slice : -2 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(1 << 2 << 3) << "$slice" << -2); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[2,3]}")); } }; class PushSliceTwoFields : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1,2],b:[3,4]}")); // { $push: { a: { $each: [ 5 ] , $slice : -2 }, { b: $each: [ 6 ] , $slice: -1 } } } BSONObj objA = BSON("$each" << BSON_ARRAY(5) << "$slice" << -2); BSONObj objB = BSON("$each" << BSON_ARRAY(6) << "$slice" << -1); _client.update(ns(), Query(), BSON("$push" << BSON("a" << objA << "b" << objB))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[2,5],b:[6]}")); } }; class PushSliceAndNormal : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1,2],b:[3]}")); // { $push : { a : { $each : [ 5 ] , $slice : -2 } , { b : 4 } } BSONObj objA = BSON("$each" << BSON_ARRAY(5) << "$slice" << -2); _client.update(ns(), Query(), BSON("$push" << BSON("a" << objA << "b" << 4))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[2,5],b:[3,4]}")); } }; class PushSliceTwoFieldsConflict : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1],b:[3]}")); // { $push: { a: { $each: [ 5 ] , $slice: -2 } , { a: $each: [ 6 ] , $slice: -1 } } } BSONObj objA = BSON("$each" << BSON_ARRAY(5) << "$slice" << -2); BSONObj other = BSON("$each" << BSON_ARRAY(6) << "$slice" << -1); _client.update(ns(), Query(), BSON("$push" << BSON("a" << objA << "a" << other))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:[1],b:[3]}")) == 0); } }; class PushSliceAndNormalConflict : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1],b:[3]}")); // { $push : { a : { $each : [ 5 ] , $slice : -2 } , { a : 4 } } } BSONObj objA = BSON("$each" << BSON_ARRAY(5) << "$slice" << -2); _client.update(ns(), Query(), BSON("$push" << BSON("a" << objA << "a" << 4))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:[1],b:[3]}")) == 0); } }; class PushSliceInvalidEachType : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1,2]}")); // { $push : { a : { $each : 3 , $slice : -2 } } } BSONObj pushObj = BSON("$each" << 3 << "$slice" << -2); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:[1,2]}")) == 0); } }; class PushSliceInvalidSliceType : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1,2]}")); // { $push : { a : { $each : [ 3 ], $slice : [ -2 ] } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(3) << "$slice" << BSON_ARRAY(-2)); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:[1,2]}")) == 0); } }; class PushSliceInvalidSliceValue : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1,2]}")); // { $push : { a : { $each : [ 3 ], $slice : 2 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(3) << "$slice" << 2); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:[1,2]}")) == 0); } }; class PushSliceInvalidSliceDouble : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1,2]}")); // { $push : { a : { $each : [ 3 ], $slice : -2.1 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(3) << "$slice" << -2.1); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:[1,2]}")) == 0); } }; class PushSliceValidSliceDouble : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1,2]}")); // { $push : { a : { $each : [ 3 ], $slice : -2.0 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(3) << "$slice" << -2.0); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT_EQUALS(_client.findOne(ns(), Query()), fromjson("{'_id':0,a:[2,3]}")); } }; class PushSliceInvalidSlice : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:[1,2]}")); // { $push : { a : { $each : [ 3 ], $xxxx : 2 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(3) << "$xxxx" << 2); _client.update(ns(), Query(), BSON("$push" << BSON("a" << pushObj))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:[1,2]}")) == 0); } }; // // We'd like to test the ability of $push with $sort in the following sequence of tests. We // try to enumerate all the possibilities of where the final element would come from: the // document, the $push itself, or both. // class PushSortBase : public ClientBase { public: ~PushSortBase() { _client.dropCollection(ns()); } protected: enum UpdateType { // Sorts ascending and slices the back of the array. TOPK_ASC = 0, // Sorts descending and slices the front of the array. TOPK_DESC = 1, // Sorts ascending and slices the back of the array. BOTTOMK_ASC = 2, // Sorts descending and slices the front of the array. BOTTOMK_DESC = 3 }; const char* ns() { return "unittest.updatetests.PushSortBase"; } void setParams(const BSONArray& fields, const BSONArray& values, const BSONArray& sort, int size) { _fieldNames = fields; _fieldValues = values; _sortFields = sort; _sliceSize = size; } /** * Generates the update expression portion of an update command given one of the * possible types of update. */ BSONObj getUpdate(int updateType) { BSONObjBuilder updateBuilder; BSONObjBuilder pushBuilder(updateBuilder.subobjStart("$push")); BSONObjBuilder fieldBuilder(pushBuilder.subobjStart("x")); // Builds $each: [ {a:1,b:1,...}, {a:2,b:2,...}, ... ] BSONArrayBuilder eachBuilder(fieldBuilder.subarrayStart("$each")); BSONObjIterator itVal(_fieldValues); while (itVal.more()) { BSONObjBuilder eachObjBuilder; BSONElement val = itVal.next(); BSONObjIterator itName(_fieldNames); while (itName.more()) { BSONElement name = itName.next(); eachObjBuilder.append(name.String(), val.Int()); } eachBuilder.append(eachObjBuilder.done()); } eachBuilder.done(); // Builds $slice portion. fieldBuilder.append("$slice", updateType < 2 ? -_sliceSize : _sliceSize); // Builds $sort: <sort pattern> portion BSONObjBuilder patternBuilder(fieldBuilder.subobjStart("$sort")); BSONObjIterator itSort(_sortFields); while (itSort.more()) { BSONElement sortField = itSort.next(); patternBuilder.append(sortField.String(), updateType % 2 ? -1 : 1); } patternBuilder.done(); fieldBuilder.done(); pushBuilder.done(); return updateBuilder.obj(); } void check(BSONObj expected) { std::cout << expected.toString() << std::endl; std::cout << _client.findOne(ns(), Query()) << std::endl; ASSERT(_client.findOne(ns(), Query()).woCompare(expected) == 0); } private: BSONArray _fieldNames; BSONArray _fieldValues; BSONArray _sortFields; int _sliceSize; }; class PushSortBelowFull : public PushSortBase { public: void run() { // With the following parameters // fields in values in // the each array each array field to sort size setParams(BSON_ARRAY("a" << "b"), BSON_ARRAY(2), BSON_ARRAY("b"), 3); // Generates the four variations below (but for now we're only using negative slice). // TOPK_ASC: $push: { x: { $each: [ {a:2,b:2} ], $slice:-3, $sort: { b:1 } } } // TOPK_DESC: $push: { x: { $each: [ {a:2,b:2} ], $slice:-3, $sort: { b:-1 } } } // BOTTOMK_ASC: $push: { x: { $each: [ {a:2,b:2} ], $slice:3, $sort: { b:1 } } } // BOTTOMK_DESC: $push: { x: { $each: [ {a:2,b:2} ], $slice:3, $sort: { b:-1 } } } for (int i = 0; i < 2; i++) { // i < 4 when we have positive $slice _client.dropCollection(ns()); _client.insert(ns(), fromjson("{'_id':0,x:[{a:1,b:1}]}")); BSONObj result; BSONObj expected; switch (i) { case TOPK_ASC: case BOTTOMK_ASC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:1,b:1},{a:2,b:2}]}"); ASSERT_EQUALS(result, expected); break; case TOPK_DESC: case BOTTOMK_DESC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:2,b:2},{a:1,b:1}]}"); ASSERT_EQUALS(result, expected); break; } } } }; class PushSortReachedFullExact : public PushSortBase { public: void run() { // With the following parameters // fields in values in // the each array each array field to sort size setParams(BSON_ARRAY("a" << "b"), BSON_ARRAY(2), BSON_ARRAY("b"), 2); // Generates the four variations below (but for now we're only using negative slice). // TOPK_ASC: $push: { x: { $each: [ {a:2,b:2} ], $slice:-2, $sort: { b:1 } } } // TOPK_DESC: $push: { x: { $each: [ {a:2,b:2} ], $slice:-2, $sort: { b:-1 } } } // BOTTOMK_ASC: $push: { x: { $each: [ {a:2,b:2} ], $slice:2, $sort: { b:1 } } } // BOTTOMK_DESC: $push: { x: { $each: [ {a:2,b:2} ], $slice:2, $sort: { b:-1 } } } for (int i = 0; i < 2; i++) { // i < 4 when we have positive $slice _client.dropCollection(ns()); _client.insert(ns(), fromjson("{'_id':0,x:[{a:1,b:1}]}")); BSONObj result; BSONObj expected; switch (i) { case TOPK_ASC: case BOTTOMK_ASC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:1,b:1},{a:2,b:2}]}"); ASSERT_EQUALS(result, expected); break; case TOPK_DESC: case BOTTOMK_DESC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:2,b:2},{a:1,b:1}]}"); ASSERT_EQUALS(result, expected); break; } } } }; class PushSortReachedFullWithBoth : public PushSortBase { public: void run() { // With the following parameters // fields in values in // the each array each array field to sort size setParams(BSON_ARRAY("a" << "b"), BSON_ARRAY(2), BSON_ARRAY("b"), 2); // Generates the four variations below (but for now we're only using negative slice). // TOPK_ASC: $push: { x: { $each: [ {a:2,b:2} ], $slice:-2, $sort: { b:1 } } } // TOPK_DESC: $push: { x: { $each: [ {a:2,b:2} ], $slice:-2, $sort: { b:-1 } } } // BOTTOMK_ASC: $push: { x: { $each: [ {a:2,b:2} ], $slice:2, $sort: { b:1 } } } // BOTTOMK_DESC: $push: { x: { $each: [ {a:2,b:2} ], $slice:2, $sort: { b:-1 } } } for (int i = 0; i < 2; i++) { // i < 4 when we have positive $slice _client.dropCollection(ns()); _client.insert(ns(), fromjson("{'_id':0,x:[{a:1,b:1},{a:3,b:3}]}")); BSONObj result; BSONObj expected; switch (i) { case TOPK_ASC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:2,b:2},{a:3,b:3}]}"); ASSERT_EQUALS(result, expected); break; case TOPK_DESC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:2,b:2},{a:1,b:1}]}"); ASSERT_EQUALS(result, expected); break; case BOTTOMK_ASC: case BOTTOMK_DESC: // Implement me. break; } } } }; class PushSortToZero : public PushSortBase { public: void run() { // With the following parameters // fields in values in // the each array each array field to sort size setParams(BSON_ARRAY("a" << "b"), BSON_ARRAY(2), BSON_ARRAY("b"), 0); // Generates the four variations below (but for now we're only using negative slice). // TOPK_ASC: $push: { x: { $each: [ {a:2,b:2} ], $slice:0, $sort: { b:1 } } } // TOPK_DESC: $push: { x: { $each: [ {a:2,b:2} ], $slice:0, $sort: { b:-1 } } } // BOTTOMK_ASC: $push: { x: { $each: [ {a:2,b:2} ], $slice:0, $sort: { b:1 } } } // BOTTOMK_DESC: $push: { x: { $each: [ {a:2,b:2} ], $slice:0, $sort: { b:-1 } } } for (int i = 0; i < 2; i++) { // i < 4 when we have positive $slice _client.dropCollection(ns()); _client.insert(ns(), fromjson("{'_id':0,x:[{a:1,b:1},{a:3,b:3}]}")); BSONObj result; BSONObj expected; _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[]}"); ASSERT_EQUALS(result, expected); } } }; class PushSortToZeroFromNothing : public PushSortBase { public: void run() { // With the following parameters // fields in values in // the each array each array field to sort size setParams(BSON_ARRAY("a" << "b"), BSON_ARRAY(2), BSON_ARRAY("b"), 0); // Generates the four variations below (but for now we're only using negative slice). // TOPK_ASC: $push: { x: { $each: [ {a:2,b:2} ], $slice:0, $sort: { b:1 } } } // TOPK_DESC: $push: { x: { $each: [ {a:2,b:2} ], $slice:0, $sort: { b:-1 } } } // BOTTOMK_ASC: $push: { x: { $each: [ {a:2,b:2} ], $slice:0, $sort: { b:1 } } } // BOTTOMK_DESC: $push: { x: { $each: [ {a:2,b:2} ], $slice:0, $sort: { b:-1 } } } for (int i = 0; i < 2; i++) { // i < 4 when we have positive $slice _client.dropCollection(ns()); _client.insert(ns(), fromjson("{'_id':0}")); BSONObj result; BSONObj expected; _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[]}"); ASSERT_EQUALS(result, expected); } } }; class PushSortFromNothing : public PushSortBase { public: void run() { // With the following parameters // fields in values in // the each array each array field to sort size setParams(BSON_ARRAY("a" << "b"), BSON_ARRAY(2 << 1), BSON_ARRAY("b"), 2); // Generates the four variations below (but for now we're only using negative slice). // <genarr> = [ {a:2,b:2}, {a:1,b:1} ] // Generates the four variations below // TOPK_ASC: $push: { x: { $each: [ <genarray> ], $slice:-2, $sort: { b:1 } } } // TOPK_DESC: $push: { x: { $each: [ <genarray> ], $slice:-2, $sort: { b:-1 } } } // BOTTOMK_ASC: $push: { x: { $each: [ <genarray> ], $slice:2, $sort: { b:1 } } } // BOTTOMK_DESC: $push: { x: { $each: [ <genarray> ], $slice:2, $sort: { b:-1 } } } for (int i = 0; i < 2; i++) { // i < 4 when we have positive $slice _client.dropCollection(ns()); _client.insert(ns(), fromjson("{'_id':0}")); BSONObj result; BSONObj expected; switch (i) { case TOPK_ASC: case BOTTOMK_ASC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:1,b:1},{a:2,b:2}]}"); ASSERT_EQUALS(result, expected); break; case TOPK_DESC: case BOTTOMK_DESC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:2,b:2},{a:1,b:1}]}"); ASSERT_EQUALS(result, expected); break; } } } }; class PushSortLongerThanSliceFromNothing : public PushSortBase { public: void run() { // With the following parameters // fields in values in // the each array each array field to sort size setParams(BSON_ARRAY("a" << "b"), BSON_ARRAY(2 << 1 << 3), BSON_ARRAY("b"), 2); // Generates the four variations below (but for now we're only using negative slice). // <genarr> = [ {a:2,b:2}, {a:1,b:1}, {a:3,b:3} ] // TOPK_ASC: $push: { x: { $each: [ <genarray> ], $slice:-2, $sort: { b:1 } } } // TOPK_DESC: $push: { x: { $each: [ <genarray> ], $slice:-2, $sort: { b:-1 } } } // BOTTOMK_ASC: $push: { x: { $each: [ <genarray> ], $slice:2, $sort: { b:1 } } } // BOTTOMK_DESC: $push: { x: { $each: [ <genarray> ], $slice:2, $sort: { b:-1 } } } for (int i = 0; i < 2; i++) { // i < 4 when we have positive $slice _client.dropCollection(ns()); _client.insert(ns(), fromjson("{'_id':0}")); BSONObj result; BSONObj expected; switch (i) { case TOPK_ASC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:2,b:2},{a:3,b:3}]}"); ASSERT_EQUALS(result, expected); break; case TOPK_DESC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:2,b:2},{a:1,b:1}]}"); ASSERT_EQUALS(result, expected); break; case BOTTOMK_ASC: case BOTTOMK_DESC: // Implement me. break; } } } }; class PushSortFromEmpty : public PushSortBase { public: void run() { // With the following parameters // fields in values in // the each array each array field to sort size setParams(BSON_ARRAY("a" << "b"), BSON_ARRAY(2 << 1), BSON_ARRAY("b"), 2); // Generates the four variations below (but for now we're only using negative slice). // <genarr> = [ {a:2,b:2}, {a:1,b:1} ] // TOPK_ASC: $push: { x: { $each: [ <genarray> ], $slice:-2, $sort: { b:1 } } } // TOPK_DESC: $push: { x: { $each: [ <genarray> ], $slice:-2, $sort: { b:-1 } } } // BOTTOMK_ASC: $push: { x: { $each: [ <genarray> ], $slice:2, $sort: { b:1 } } } // BOTTOMK_DESC: $push: { x: { $each: [ <genarray> ], $slice:2, $sort: { b:-1 } } } for (int i = 0; i < 2; i++) { // i < 4 when we have positive $slice _client.dropCollection(ns()); _client.insert(ns(), fromjson("{'_id':0,x:[]}")); BSONObj result; BSONObj expected; switch (i) { case TOPK_ASC: case BOTTOMK_ASC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:1,b:1},{a:2,b:2}]}"); ASSERT_EQUALS(result, expected); break; case TOPK_DESC: case BOTTOMK_DESC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:2,b:2},{a:1,b:1}]}"); ASSERT_EQUALS(result, expected); break; } } } }; class PushSortLongerThanSliceFromEmpty : public PushSortBase { public: void run() { // With the following parameters // fields in values in // the each array each array field to sort size setParams(BSON_ARRAY("a" << "b"), BSON_ARRAY(2 << 1 << 3), BSON_ARRAY("b"), 2); // Generates the four variations below (but for now we're only using negative slice). // <genarr> = [ {a:2,b:2}, {a:1,b:1}, {a:3,b:3} ] // TOPK_ASC: $push: { x: { $each: [ <genarray> ], $slice:-2, $sort: { b:1 } } } // TOPK_DESC: $push: { x: { $each: [ <genarray> ], $slice:-2, $sort: { b:-1 } } } // BOTTOMK_ASC: $push: { x: { $each: [ <genarray> ], $slice:2, $sort: { b:1 } } } // BOTTOMK_DESC: $push: { x: { $each: [ <genarray> ], $slice:2, $sort: { b:-1 } } } for (int i = 0; i < 2; i++) { // i < 4 when we have positive $slice _client.dropCollection(ns()); _client.insert(ns(), fromjson("{'_id':0,x:[]}")); BSONObj result; BSONObj expected; switch (i) { case TOPK_ASC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:2,b:2},{a:3,b:3}]}"); ASSERT_EQUALS(result, expected); break; case TOPK_DESC: _client.update(ns(), Query(), getUpdate(i)); result = _client.findOne(ns(), Query()); expected = fromjson("{'_id':0,x:[{a:2,b:2},{a:1,b:1}]}"); ASSERT_EQUALS(result, expected); break; case BOTTOMK_ASC: case BOTTOMK_DESC: // Implement me. break; } } } }; namespace { /** * Comparator between two BSONObjects that takes in consideration only the keys and * direction described in the sort pattern. * * TODO: This was pulled from update_internal.h, we should verify that these tests work * with the new update framework $push sorter. */ struct ProjectKeyCmp { BSONObj sortPattern; ProjectKeyCmp(BSONObj pattern) : sortPattern(pattern) {} int operator()(const BSONObj& left, const BSONObj& right) const { BSONObj keyLeft = left.extractFields(sortPattern, true); BSONObj keyRight = right.extractFields(sortPattern, true); return keyLeft.woCompare(keyRight, sortPattern) < 0; } }; } // namespace class PushSortSortMixed { public: void run() { BSONObj objs[3]; objs[0] = fromjson("{a:1, b:1}"); objs[1] = fromjson("{a:3, b:1}"); objs[2] = fromjson("{a:2, b:3}"); vector<BSONObj> workArea; for (int i = 0; i < 3; i++) { workArea.push_back(objs[i]); } sort(workArea.begin(), workArea.end(), ProjectKeyCmp(BSON("b" << 1 << "a" << -1))); ASSERT_EQUALS(workArea[0], objs[1]); ASSERT_EQUALS(workArea[1], objs[0]); ASSERT_EQUALS(workArea[2], objs[2]); } }; class PushSortSortOutOfOrderFields { public: void run() { BSONObj objs[3]; objs[0] = fromjson("{b:1, a:1}"); objs[1] = fromjson("{a:3, b:2}"); objs[2] = fromjson("{b:3, a:2}"); vector<BSONObj> workArea; for (int i = 0; i < 3; i++) { workArea.push_back(objs[i]); } sort(workArea.begin(), workArea.end(), ProjectKeyCmp(BSON("a" << 1 << "b" << 1))); ASSERT_EQUALS(workArea[0], objs[0]); ASSERT_EQUALS(workArea[1], objs[2]); ASSERT_EQUALS(workArea[2], objs[1]); } }; class PushSortSortExtraFields { public: void run() { BSONObj objs[3]; objs[0] = fromjson("{b:1, c:2, a:1}"); objs[1] = fromjson("{c:1, a:3, b:2}"); objs[2] = fromjson("{b:3, a:2}"); vector<BSONObj> workArea; for (int i = 0; i < 3; i++) { workArea.push_back(objs[i]); } sort(workArea.begin(), workArea.end(), ProjectKeyCmp(BSON("a" << 1 << "b" << 1))); ASSERT_EQUALS(workArea[0], objs[0]); ASSERT_EQUALS(workArea[1], objs[2]); ASSERT_EQUALS(workArea[2], objs[1]); } }; class PushSortSortMissingFields { public: void run() { BSONObj objs[3]; objs[0] = fromjson("{a:2, b:2}"); objs[1] = fromjson("{a:1}"); objs[2] = fromjson("{a:3, b:3, c:3}"); vector<BSONObj> workArea; for (int i = 0; i < 3; i++) { workArea.push_back(objs[i]); } sort(workArea.begin(), workArea.end(), ProjectKeyCmp(BSON("b" << 1 << "c" << 1))); ASSERT_EQUALS(workArea[0], objs[1]); ASSERT_EQUALS(workArea[1], objs[0]); ASSERT_EQUALS(workArea[2], objs[2]); } }; class PushSortSortNestedFields { public: void run() { BSONObj objs[3]; objs[0] = fromjson("{a:{b:{c:2, d:0}}}"); objs[1] = fromjson("{a:{b:{c:1, d:2}}}"); objs[2] = fromjson("{a:{b:{c:3, d:1}}}"); vector<BSONObj> workArea; for (int i = 0; i < 3; i++) { workArea.push_back(objs[i]); } sort(workArea.begin(), workArea.end(), ProjectKeyCmp(fromjson("{'a.b.d':-1}"))); ASSERT_EQUALS(workArea[0], objs[1]); ASSERT_EQUALS(workArea[1], objs[2]); ASSERT_EQUALS(workArea[2], objs[0]); sort(workArea.begin(), workArea.end(), ProjectKeyCmp(fromjson("{'a.b':1}"))); ASSERT_EQUALS(workArea[0], objs[1]); ASSERT_EQUALS(workArea[1], objs[0]); ASSERT_EQUALS(workArea[2], objs[2]); } }; class PushSortInvalidSortPattern : public SetBase { public: void run() { // Sort pattern validation is made during update command checking. Therefore, to // catch bad patterns, we have to write updated that use them. BSONObj expected = fromjson("{'_id':0,x:[{a:1}, {a:2}]}"); _client.insert(ns(), expected); // { $push : { x : { $each : [ {a:3} ], $slice:-2, $sort : {a..d:1} } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(BSON("a" << 3)) << "$slice" << -2 << "$sort" << BSON("a..d" << 1)); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); BSONObj result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); // { $push : { x : { $each : [ {a:3} ], $slice:-2, $sort : {a.:1} } } } pushObj = BSON("$each" << BSON_ARRAY(BSON("a" << 3)) << "$slice" << -2 << "$sort" << BSON("a." << 1)); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); // { $push : { x : { $each : [ {a:3} ], $slice:-2, $sort : {.b:1} } } } pushObj = BSON("$each" << BSON_ARRAY(BSON("a" << 3)) << "$slice" << -2 << "$sort" << BSON(".b" << 1)); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); // { $push : { x : { $each : [ {a:3} ], $slice:-2, $sort : {.:1} } } } pushObj = BSON("$each" << BSON_ARRAY(BSON("a" << 3)) << "$slice" << -2 << "$sort" << BSON("." << 1)); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); // { $push : { x : { $each : [ {a:3} ], $slice:-2, $sort : {'':1} } } } pushObj = BSON("$each" << BSON_ARRAY(BSON("a" << 3)) << "$slice" << -2 << "$sort" << BSON("" << 1)); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); } }; class PushSortInvalidEachType : public SetBase { public: void run() { BSONObj expected = fromjson("{'_id':0,x:[{a:1},{a:2}]}"); _client.insert(ns(), expected); // { $push : { x : { $each : [ 3 ], $slice:-2, $sort : {a:1} } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(3) << "$slice" << -2 << "$sort" << BSON("a" << 1)); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); BSONObj result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); } }; class PushSortInvalidSortType : public SetBase { public: void run() { BSONObj expected = fromjson("{'_id':0,x:[{a:1},{a:2}]}"); _client.insert(ns(), expected); // { $push : { x : { $each : [ {a:3} ], $slice:-2, $sort : 2} } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(BSON("a" << 3)) << "$slice" << -2 << "$sort" << 2); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); BSONObj result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); } }; class PushSortInvalidSortValue : public SetBase { public: void run() { BSONObj expected = fromjson("{'_id':0,x:[{a:1},{a:2}]}"); _client.insert(ns(), expected); // { $push : { x : { $each : [ {a:3} ], $slice:2, $sort : {a:1} } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(BSON("a" << 3)) << "$slice" << 2 << "$sort" << BSON("a" << 1)); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); BSONObj result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); } }; class PushSortInvalidSortDouble : public SetBase { public: void run() { BSONObj expected = fromjson("{'_id':0,x:[{a:1},{a:2}]}"); _client.insert(ns(), expected); // { $push : { x : { $each : [ {a:3} ], $slice:-2.1, $sort : {a:1} } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(BSON("a" << 3)) << "$slice" << -2.1 << "$sort" << BSON("a" << 1)); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); BSONObj result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); } }; class PushSortValidSortDouble : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,x:[{a:1},{a:2}]}")); // { $push : { x : { $each : [ {a:3} ], $slice:-2.0, $sort : {a:1} } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(BSON("a" << 3)) << "$slice" << -2.0 << "$sort" << BSON("a" << 1)); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); BSONObj expected = fromjson("{'_id':0,x:[{a:2},{a:3}]}"); BSONObj result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); } }; class PushSortInvalidSortSort : public SetBase { public: void run() { BSONObj expected = fromjson("{'_id':0,x:[{a:1},{a:2}]}"); _client.insert(ns(), expected); // { $push : { x : { $each : [ {a:3} ], $slice:-2.0, $sort : [2, 1] } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(BSON("a" << 3)) << "$slice" << -2.0 << "$sort" << BSON_ARRAY(2 << 1)); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); BSONObj result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); } }; class PushSortInvalidSortSortOrder : public SetBase { public: void run() { BSONObj expected = fromjson("{'_id':0,x:[{a:1},{a:2}]}"); _client.insert(ns(), expected); // { $push : { x : { $each : [ {a:3} ], $slice:-2, $sort : {a:10} } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(BSON("a" << 3)) << "$slice" << -2 << "$sort" << BSON("a" << 10)); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); BSONObj result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); } }; class PushSortInvertedSortAndSlice : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,x:[{a:1},{a:3}]}")); // { $push : { x : { $each : [ {a:2} ], $sort: {a:1}, $slice:-2 } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(BSON("a" << 2)) << "$sort" << BSON("a" << 1) << "$slice" << -2.0); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); BSONObj expected = fromjson("{'_id':0,x:[{a:2},{a:3}]}"); BSONObj result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); } }; class PushSortInvalidDuplicatedSort : public SetBase { public: void run() { BSONObj expected = fromjson("{'_id':0,x:[{a:1},{a:3}]}"); _client.insert(ns(), expected); // { $push : { x : { $each : [ {a:2} ], $sort : {a:1}, $sort: {a:1} } } } BSONObj pushObj = BSON("$each" << BSON_ARRAY(BSON("a" << 2)) << "$sort" << BSON("a" << 1) << "$sort" << BSON("a" << 1)); _client.update(ns(), Query(), BSON("$push" << BSON("x" << pushObj))); BSONObj result = _client.findOne(ns(), Query()); ASSERT_EQUALS(result, expected); } }; class CantIncParent : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:{b:4}}")); _client.update(ns(), Query(), BSON("$inc" << BSON("a" << 4.0))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:{b:4}}")) == 0); } }; class DontDropEmpty : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:{b:{}}}")); _client.update(ns(), Query(), BSON("$set" << BSON("a.c" << 4.0))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:{b:{},c:4}}")) == 0); } }; class InsertInEmpty : public SetBase { public: void run() { _client.insert(ns(), fromjson("{'_id':0,a:{b:{}}}")); _client.update(ns(), Query(), BSON("$set" << BSON("a.b.f" << 4.0))); ASSERT(_client.findOne(ns(), Query()).woCompare(fromjson("{'_id':0,a:{b:{f:4}}}")) == 0); } }; class IndexParentOfMod : public SetBase { public: void run() { ASSERT_OK(dbtests::createIndex(&_txn, ns(), BSON("a" << 1))); _client.insert(ns(), fromjson("{'_id':0}")); _client.update(ns(), Query(), fromjson("{$set:{'a.b':4}}")); ASSERT_EQUALS(fromjson("{'_id':0,a:{b:4}}"), _client.findOne(ns(), Query())); ASSERT_EQUALS(fromjson("{'_id':0,a:{b:4}}"), _client.findOne(ns(), fromjson("{'a.b':4}"))); // make sure the index works } }; class PreserveIdWithIndex : public SetBase { // Not using $set, but base class is still useful public: void run() { _client.insert(ns(), BSON("_id" << 55 << "i" << 5)); _client.update(ns(), BSON("i" << 5), BSON("i" << 6)); ASSERT(!_client.findOne(ns(), Query(BSON("_id" << 55)).hint("{\"_id\":1}")).isEmpty()); } }; class CheckNoMods : public SetBase { public: void run() { _client.update(ns(), BSONObj(), BSON("i" << 5 << "$set" << BSON("q" << 3)), true); ASSERT(error()); } }; class UpdateMissingToNull : public SetBase { public: void run() { _client.insert(ns(), BSON("a" << 5)); _client.update(ns(), BSON("a" << 5), fromjson("{$set:{b:null}}")); ASSERT_EQUALS(jstNULL, _client.findOne(ns(), QUERY("a" << 5)).getField("b").type()); } }; /** SERVER-4777 */ class TwoModsWithinDuplicatedField : public SetBase { public: void run() { _client.insert( ns(), BSON("_id" << 0 << "a" << 1 << "x" << BSONObj() << "x" << BSONObj() << "z" << 5)); _client.update(ns(), BSONObj(), BSON("$set" << BSON("x.b" << 1 << "x.c" << 1))); ASSERT_EQUALS(BSON("_id" << 0 << "a" << 1 << "x" << BSON("b" << 1 << "c" << 1) << "x" << BSONObj() << "z" << 5), _client.findOne(ns(), BSONObj())); } }; /** SERVER-4777 */ class ThreeModsWithinDuplicatedField : public SetBase { public: void run() { _client.insert( ns(), BSON("_id" << 0 << "x" << BSONObj() << "x" << BSONObj() << "x" << BSONObj())); _client.update( ns(), BSONObj(), BSON("$set" << BSON("x.b" << 1 << "x.c" << 1 << "x.d" << 1))); ASSERT_EQUALS(BSON("_id" << 0 << "x" << BSON("b" << 1 << "c" << 1 << "d" << 1) << "x" << BSONObj() << "x" << BSONObj()), _client.findOne(ns(), BSONObj())); } }; class TwoModsBeforeExistingField : public SetBase { public: void run() { _client.insert(ns(), BSON("_id" << 0 << "x" << 5)); _client.update(ns(), BSONObj(), BSON("$set" << BSON("a" << 1 << "b" << 1 << "x" << 10))); ASSERT_EQUALS(mutablebson::unordered(BSON("_id" << 0 << "a" << 1 << "b" << 1 << "x" << 10)), mutablebson::unordered(_client.findOne(ns(), BSONObj()))); } }; namespace basic { class Base : public ClientBase { protected: virtual const char* ns() = 0; virtual void dotest() = 0; void insert(const BSONObj& o) { _client.insert(ns(), o); } void update(const BSONObj& m) { _client.update(ns(), BSONObj(), m); } BSONObj findOne() { return _client.findOne(ns(), BSONObj()); } void test(const char* initial, const char* mod, const char* after) { test(fromjson(initial), fromjson(mod), fromjson(after)); } void test(const BSONObj& initial, const BSONObj& mod, const BSONObj& after) { _client.dropCollection(ns()); insert(initial); update(mod); ASSERT_EQUALS(after, findOne()); _client.dropCollection(ns()); } public: Base() {} virtual ~Base() {} void run() { _client.dropCollection(ns()); dotest(); _client.dropCollection(ns()); } }; class SingleTest : public Base { virtual BSONObj initial() = 0; virtual BSONObj mod() = 0; virtual BSONObj after() = 0; void dotest() { test(initial(), mod(), after()); } }; class inc1 : public SingleTest { virtual BSONObj initial() { return BSON("_id" << 1 << "x" << 1); } virtual BSONObj mod() { return BSON("$inc" << BSON("x" << 2)); } virtual BSONObj after() { return BSON("_id" << 1 << "x" << 3); } virtual const char* ns() { return "unittests.inc1"; } }; class inc2 : public SingleTest { virtual BSONObj initial() { return BSON("_id" << 1 << "x" << 1); } virtual BSONObj mod() { return BSON("$inc" << BSON("x" << 2.5)); } virtual BSONObj after() { return BSON("_id" << 1 << "x" << 3.5); } virtual const char* ns() { return "unittests.inc2"; } }; class inc3 : public SingleTest { virtual BSONObj initial() { return BSON("_id" << 1 << "x" << 537142123123LL); } virtual BSONObj mod() { return BSON("$inc" << BSON("x" << 2)); } virtual BSONObj after() { return BSON("_id" << 1 << "x" << 537142123125LL); } virtual const char* ns() { return "unittests.inc3"; } }; class inc4 : public SingleTest { virtual BSONObj initial() { return BSON("_id" << 1 << "x" << 537142123123LL); } virtual BSONObj mod() { return BSON("$inc" << BSON("x" << 2LL)); } virtual BSONObj after() { return BSON("_id" << 1 << "x" << 537142123125LL); } virtual const char* ns() { return "unittests.inc4"; } }; class inc5 : public SingleTest { virtual BSONObj initial() { return BSON("_id" << 1 << "x" << 537142123123LL); } virtual BSONObj mod() { return BSON("$inc" << BSON("x" << 2.0)); } virtual BSONObj after() { return BSON("_id" << 1 << "x" << 537142123125LL); } virtual const char* ns() { return "unittests.inc5"; } }; class inc6 : public Base { virtual const char* ns() { return "unittests.inc6"; } virtual BSONObj initial() { return BSONObj(); } virtual BSONObj mod() { return BSONObj(); } virtual BSONObj after() { return BSONObj(); } void dotest() { long long start = numeric_limits<int>::max() - 5; long long max = numeric_limits<int>::max() + 5ll; _client.insert(ns(), BSON("x" << (int)start)); ASSERT(findOne()["x"].type() == NumberInt); while (start < max) { update(BSON("$inc" << BSON("x" << 1))); start += 1; ASSERT_EQUALS(start, findOne()["x"].numberLong()); // SERVER-2005 } ASSERT(findOne()["x"].type() == NumberLong); } }; class bit1 : public Base { const char* ns() { return "unittests.bit1"; } void dotest() { test(BSON("_id" << 1 << "x" << 3), BSON("$bit" << BSON("x" << BSON("and" << 2))), BSON("_id" << 1 << "x" << (3 & 2))); test(BSON("_id" << 1 << "x" << 1), BSON("$bit" << BSON("x" << BSON("or" << 4))), BSON("_id" << 1 << "x" << (1 | 4))); test(BSON("_id" << 1 << "x" << 3), BSON("$bit" << BSON("x" << BSON("and" << 2 << "or" << 8))), BSON("_id" << 1 << "x" << ((3 & 2) | 8))); test(BSON("_id" << 1 << "x" << 3), BSON("$bit" << BSON("x" << BSON("or" << 2 << "and" << 8))), BSON("_id" << 1 << "x" << ((3 | 2) & 8))); } }; class unset : public Base { const char* ns() { return "unittests.unset"; } void dotest() { test("{_id:1,x:1}", "{$unset:{x:1}}", "{_id:1}"); } }; class setswitchint : public Base { const char* ns() { return "unittests.int1"; } void dotest() { test(BSON("_id" << 1 << "x" << 1), BSON("$set" << BSON("x" << 5.6)), BSON("_id" << 1 << "x" << 5.6)); test(BSON("_id" << 1 << "x" << 5.6), BSON("$set" << BSON("x" << 1)), BSON("_id" << 1 << "x" << 1)); } }; }; class All : public Suite { public: All() : Suite("update") {} void setupTests() { add<ModId>(); add<ModNonmodMix>(); add<InvalidMod>(); add<ModNotFirst>(); add<ModDuplicateFieldSpec>(); add<IncNonNumber>(); add<PushAllNonArray>(); add<PullAllNonArray>(); add<IncTargetNonNumber>(); add<SetNum>(); add<SetString>(); add<SetStringDifferentLength>(); add<SetStringToNum>(); add<SetStringToNumInPlace>(); add<SetOnInsertFromEmpty>(); add<SetOnInsertFromNonExistent>(); add<SetOnInsertFromNonExistentWithQuery>(); add<SetOnInsertFromNonExistentWithQueryOverField>(); add<SetOnInsertMissingField>(); add<SetOnInsertExisting>(); add<SetOnInsertMixed>(); add<SetOnInsertMissingParent>(); add<ModDotted>(); add<SetInPlaceDotted>(); add<SetRecreateDotted>(); add<SetMissingDotted>(); add<SetAdjacentDotted>(); add<IncMissing>(); add<MultiInc>(); add<UnorderedNewSet>(); add<UnorderedNewSetAdjacent>(); add<ArrayEmbeddedSet>(); add<AttemptEmbedInExistingNum>(); add<AttemptEmbedConflictsWithOtherSet>(); add<ModMasksEmbeddedConflict>(); add<ModOverwritesExistingObject>(); add<InvalidEmbeddedSet>(); add<UpsertMissingEmbedded>(); add<Push>(); add<PushInvalidEltType>(); add<PushConflictsWithOtherMod>(); add<PushFromNothing>(); add<PushFromEmpty>(); add<PushInsideNothing>(); add<CantPushInsideOtherMod>(); add<CantPushTwice>(); add<SetEncapsulationConflictsWithExistingType>(); add<CantPushToParent>(); add<PushEachSimple>(); add<PushEachFromEmpty>(); add<PushSliceBelowFull>(); add<PushSliceReachedFullExact>(); add<PushSliceReachedFullWithEach>(); add<PushSliceReachedFullWithBoth>(); add<PushSliceToZero>(); add<PushSliceToZeroFromNothing>(); add<PushSliceFromNothing>(); add<PushSliceLongerThanSliceFromNothing>(); add<PushSliceFromEmpty>(); add<PushSliceLongerThanSliceFromEmpty>(); add<PushSliceTwoFields>(); add<PushSliceAndNormal>(); add<PushSliceTwoFieldsConflict>(); add<PushSliceAndNormalConflict>(); add<PushSliceInvalidEachType>(); add<PushSliceInvalidSliceType>(); add<PushSliceInvalidSliceValue>(); add<PushSliceInvalidSliceDouble>(); add<PushSliceValidSliceDouble>(); add<PushSliceInvalidSlice>(); add<PushSortBelowFull>(); add<PushSortReachedFullExact>(); add<PushSortReachedFullWithBoth>(); add<PushSortToZero>(); add<PushSortToZeroFromNothing>(); add<PushSortFromNothing>(); add<PushSortLongerThanSliceFromNothing>(); add<PushSortFromEmpty>(); add<PushSortLongerThanSliceFromEmpty>(); add<PushSortSortMixed>(); add<PushSortSortOutOfOrderFields>(); add<PushSortSortExtraFields>(); add<PushSortSortMissingFields>(); add<PushSortSortNestedFields>(); add<PushSortInvalidSortPattern>(); add<PushSortInvalidEachType>(); add<PushSortInvalidSortType>(); add<PushSortInvalidSortValue>(); add<PushSortInvalidSortDouble>(); add<PushSortValidSortDouble>(); add<PushSortInvalidSortSort>(); add<PushSortInvalidSortSortOrder>(); add<PushSortInvertedSortAndSlice>(); add<PushSortInvalidDuplicatedSort>(); add<CantIncParent>(); add<DontDropEmpty>(); add<InsertInEmpty>(); add<IndexParentOfMod>(); add<PreserveIdWithIndex>(); add<CheckNoMods>(); add<UpdateMissingToNull>(); add<TwoModsWithinDuplicatedField>(); add<ThreeModsWithinDuplicatedField>(); add<TwoModsBeforeExistingField>(); add<basic::inc1>(); add<basic::inc2>(); add<basic::inc3>(); add<basic::inc4>(); add<basic::inc5>(); add<basic::inc6>(); add<basic::bit1>(); add<basic::unset>(); add<basic::setswitchint>(); } }; SuiteInstance<All> myall; } // namespace UpdateTests
35.293504
100
0.496668
[ "vector" ]
33ea3ba775399e55cca3dde14a03e0a9103574f8
16,897
cc
C++
src/backends/tensorrt/autofill.cc
luckrats/server
bdbb4bcb27034e5a54dcba4e5af692138384570e
[ "BSD-3-Clause" ]
1
2021-07-21T09:53:02.000Z
2021-07-21T09:53:02.000Z
src/backends/tensorrt/autofill.cc
V1oletM/server
0b01ff2397c00f08ce4c80c7543b3bcc1d942624
[ "BSD-3-Clause" ]
null
null
null
src/backends/tensorrt/autofill.cc
V1oletM/server
0b01ff2397c00f08ce4c80c7543b3bcc1d942624
[ "BSD-3-Clause" ]
1
2021-07-26T13:00:08.000Z
2021-07-26T13:00:08.000Z
// Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION 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 ``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 "src/backends/tensorrt/autofill.h" #include <NvInfer.h> #include <vector> #include "src/backends/tensorrt/loader.h" #include "src/backends/tensorrt/plan_utils.h" #include "src/core/autofill.h" #include "src/core/constants.h" #include "src/core/filesystem.h" #include "src/core/logging.h" #include "src/core/model_config.h" #include "src/core/model_config_utils.h" namespace nvidia { namespace inferenceserver { class AutoFillPlanImpl : public AutoFill { public: AutoFillPlanImpl( const std::string& model_name, const std::string& plan_filename, nvinfer1::ICudaEngine* engine, nvinfer1::IRuntime* runtime) : AutoFill(model_name), plan_filename_(plan_filename), engine_(engine), runtime_(runtime), max_batch_size_(0), num_profile_bindings_(0) { if (!UseTensorRTv2API(engine_)) { num_profile_bindings_ = engine_->getNbBindings(); } } ~AutoFillPlanImpl() { if (engine_ != nullptr) { engine_->destroy(); } if (runtime_ != nullptr) { runtime_->destroy(); } } Status Fix(inference::ModelConfig* config) override; private: template <class ModelIO> using IOList = ::google::protobuf::RepeatedPtrField<ModelIO>; using DimsList = ::google::protobuf::RepeatedField<int64_t>; Status Init(inference::ModelConfig* config); Status GetMaxSupportedBatchSize(inference::ModelConfig* config); Status GetProfileMaxBatchSize( const int profile_index, int* max_profile_batch_size); Status GetProfileIndices( inference::ModelConfig* config, std::set<int>* config_profiles); Status ExtractBatchHintFromIOConfig( const std::string& tensor_name, const DimsList& dims, bool* config_batch_hint); Status FixBatchingSupport(inference::ModelConfig* config); void InitIOLists(); template <class IO> void InitIODims(nvinfer1::Dims& dims, bool is_shape_binding, IO* config_io); template <class IO> Status FixIO(const IOList<IO>& reference_list, IOList<IO>* mutable_list); const std::string plan_filename_; inference::ModelConfig config_; nvinfer1::ICudaEngine* engine_; nvinfer1::IRuntime* runtime_; int max_batch_size_; int num_profile_bindings_; }; Status AutoFillPlanImpl::Fix(inference::ModelConfig* config) { config->set_platform(kTensorRTPlanPlatform); // Set name if not already set. if (config->name().empty()) { config->set_name(model_name_); } if (config->default_model_filename().empty()) { config->set_default_model_filename(plan_filename_); } // Initialize the autofiller RETURN_IF_ERROR(Init(config)); // fix batching support RETURN_IF_ERROR(FixBatchingSupport(config)); // Get the reference IO lists InitIOLists(); // Inputs RETURN_IF_ERROR(FixIO(config_.input(), config->mutable_input())); // Outputs RETURN_IF_ERROR(FixIO(config_.output(), config->mutable_output())); return Status::Success; } Status AutoFillPlanImpl::Init(inference::ModelConfig* config) { if (engine_->hasImplicitBatchDimension()) { // If engine has implicit batch dimension then retrieve the value and exit max_batch_size_ = engine_->getMaxBatchSize(); return Status::Success; } else { // Assuming the first dimension to be batch dimension, until and unless // proven otherwise. RETURN_IF_ERROR(GetMaxSupportedBatchSize(config)); } // For batching support, the number of dimensions specified in model config // match should be 1 less than the number of dimensions specified in engine. // Will use that as a hint to ascertain whether or not to enable batching. bool config_batch_hint = false; // The number of IO Tensors with shape specification in config int tensors_with_config_shape_cnt = 0; if ((config->input_size() != 0) || (config->output_size() != 0)) { for (const auto& config_io : config->input()) { if (!config_io.dims().empty()) { tensors_with_config_shape_cnt++; RETURN_IF_ERROR(ExtractBatchHintFromIOConfig( config_io.name(), config_io.dims(), &config_batch_hint)); } } for (const auto& config_io : config->output()) { if (!config_io.dims().empty()) { tensors_with_config_shape_cnt++; RETURN_IF_ERROR(ExtractBatchHintFromIOConfig( config_io.name(), config_io.dims(), &config_batch_hint)); } } } // Validate cases with incomplete input and output shapes if (tensors_with_config_shape_cnt != 0 && tensors_with_config_shape_cnt != num_profile_bindings_) { return Status( Status::Code::INTERNAL, "unable to autofill for '" + model_name_ + "', either all model tensor configuration should specify their " "dims or none."); } if (config_batch_hint && max_batch_size_ == 0) { return Status( Status::Code::INTERNAL, "unable to autofill for '" + model_name_ + "', model tensor shape configuration hints for dynamic batching " "but the underlying engine doesn't support batching."); } else if (tensors_with_config_shape_cnt != 0 && !config_batch_hint) { // if no hint for batching in config io LOG_WARNING << "The specified dimensions in model config for " << model_name_ << " hints that batching is unavailable"; max_batch_size_ = 0; } return Status::Success; } Status AutoFillPlanImpl::GetMaxSupportedBatchSize(inference::ModelConfig* config) { std::set<int> profile_indices; RETURN_IF_ERROR(GetProfileIndices(config, &profile_indices)); int running_max = 0; for (const auto profile_index : profile_indices) { int max_profile_batch_size; RETURN_IF_ERROR( GetProfileMaxBatchSize(profile_index, &max_profile_batch_size)); if (max_profile_batch_size > running_max) { running_max = max_profile_batch_size; } } max_batch_size_ = running_max; return Status::Success; } Status AutoFillPlanImpl::GetProfileIndices( inference::ModelConfig* config, std::set<int>* config_profiles) { int num_profiles = engine_->getNbOptimizationProfiles(); num_profile_bindings_ = engine_->getNbBindings() / num_profiles; for (const auto& group : config->instance_group()) { for (const auto& profile : group.profile()) { int profile_idx; RETURN_IF_ERROR(GetProfileIndex(profile, &profile_idx)); if (profile_idx < 0 || profile_idx >= num_profiles) { return Status( Status::Code::INTERNAL, "unable to autofill for '" + model_name_ + "', configuration specified invalid profile " + profile + " . Number of profiles supported by TensorRT engine: " + std::to_string(num_profiles)); } config_profiles->insert(profile_idx); } } if (config_profiles->empty()) { // If not specified then use the default. config_profiles->insert(0); } return Status::Success; } Status AutoFillPlanImpl::GetProfileMaxBatchSize( int profile_index, int* max_profile_batch_size) { *max_profile_batch_size = INT_MAX; // Visit all the bindings of the profile to capture the maximum and // minimum batch size supported. for (int binding_index = 0; binding_index < num_profile_bindings_; binding_index++) { int effective_binding_index = (profile_index * num_profile_bindings_) + binding_index; if (engine_->bindingIsInput(effective_binding_index)) { if (!engine_->isShapeBinding(effective_binding_index)) { nvinfer1::Dims max_shape = engine_->getProfileDimensions( effective_binding_index, profile_index, nvinfer1::OptProfileSelector::kMAX); if (*max_profile_batch_size > max_shape.d[0]) { *max_profile_batch_size = max_shape.d[0]; } } else { const int32_t* max_shapes = engine_->getProfileShapeValues( effective_binding_index, profile_index, nvinfer1::OptProfileSelector::kMAX); if (*max_profile_batch_size > *max_shapes) { *max_profile_batch_size = *max_shapes; } } } } return Status::Success; } Status AutoFillPlanImpl::ExtractBatchHintFromIOConfig( const std::string& tensor_name, const DimsList& dims, bool* config_batch_hint) { // look up corresponding io info from model for (int binding_index = 0; binding_index < num_profile_bindings_; binding_index++) { if (tensor_name == engine_->getBindingName(binding_index)) { nvinfer1::Dims shape = engine_->getBindingDimensions(binding_index); bool should_batch; if (!engine_->isShapeBinding(binding_index)) { should_batch = (shape.nbDims == (dims.size() + 1)); } else { should_batch = (shape.d[0] == (dims[0] + 1)); } if (should_batch) { *config_batch_hint = true; } if (*config_batch_hint && (!should_batch)) { return Status( Status::Code::INTERNAL, "unable to autofill for '" + model_name_ + "', model tensor configurations are contradicting " + "each other in terms of whether batching is supported"); } } } return Status::Success; } Status AutoFillPlanImpl::FixBatchingSupport(inference::ModelConfig* config) { if (config->max_batch_size() == 0) { config->set_max_batch_size(max_batch_size_); } else if (config->max_batch_size() > max_batch_size_) { return Status( Status::Code::INTERNAL, "unable to autofill for '" + model_name_ + "', configuration specified max-batch " + std::to_string(config->max_batch_size()) + " but TensorRT engine only supports max-batch " + std::to_string(max_batch_size_)); } return Status::Success; } void AutoFillPlanImpl::InitIOLists() { for (int i = 0; i < num_profile_bindings_; ++i) { nvinfer1::Dims dims = engine_->getBindingDimensions(i); bool is_shape_binding = engine_->isShapeBinding(i); if (engine_->bindingIsInput(i)) { inference::ModelInput* config_input = config_.add_input(); std::string input_name{engine_->getBindingName(i)}; config_input->set_name(input_name.substr(0, input_name.find(" "))); config_input->set_data_type( ConvertTrtTypeToDataType(engine_->getBindingDataType(i))); InitIODims(dims, is_shape_binding, config_input); config_input->set_is_shape_tensor(is_shape_binding); } else { inference::ModelOutput* config_output = config_.add_output(); std::string output_name{engine_->getBindingName(i)}; config_output->set_name(output_name.substr(0, output_name.find(" "))); config_output->set_data_type( ConvertTrtTypeToDataType(engine_->getBindingDataType(i))); InitIODims(dims, is_shape_binding, config_output); config_output->set_is_shape_tensor(is_shape_binding); } } } template <class IO> void AutoFillPlanImpl::InitIODims( nvinfer1::Dims& dims, bool is_shape_binding, IO* config_io) { bool skip_first = (max_batch_size_ != 0) && (!engine_->hasImplicitBatchDimension()); auto config_dims = config_io->mutable_dims(); if (!is_shape_binding) { for (int didx = (skip_first ? 1 : 0); didx < dims.nbDims; ++didx) { config_dims->Add(dims.d[didx]); } // If tensor dims are empty then must use a reshape for the // tensor, since 'dims' is not allowed to be empty. if (config_io->dims_size() == 0) { config_io->mutable_dims()->Add(1); config_io->mutable_reshape(); } } else { if (dims.nbDims != 0) { if (skip_first) { config_dims->Add(dims.d[0] - 1); } else { config_dims->Add(dims.d[0]); } } } } template <class IO> Status AutoFillPlanImpl::FixIO( const IOList<IO>& reference_list, IOList<IO>* mutable_list) { if (mutable_list->size() == 0) { mutable_list->CopyFrom(reference_list); } else { for (auto& io : *mutable_list) { for (const auto& io_ref : reference_list) { if (io.name() == io_ref.name()) { // only set type and shape if they are not set if (io.data_type() == inference::DataType::TYPE_INVALID) { io.set_data_type(io_ref.data_type()); } if (io.dims_size() == 0) { io.mutable_dims()->CopyFrom(io_ref.dims()); if (io_ref.has_reshape()) { io.mutable_reshape()->CopyFrom(io_ref.reshape()); } } // Check if the IO is a shape tensor. bool is_shape_tensor = false; int io_index = engine_->getBindingIndex(io.name().c_str()); if (io_index == -1) { return Status( Status::Code::INVALID_ARG, "binding for '" + io.name() + "' not found in the model."); } is_shape_tensor = engine_->isShapeBinding(io_index); if (io.is_shape_tensor() && (!is_shape_tensor)) { return Status( Status::Code::INVALID_ARG, "'" + io.name() + "' is incorrectly specified as a shape tensor."); } io.set_is_shape_tensor(is_shape_tensor); break; } } } } return Status::Success; } Status AutoFillPlan::Create( const std::string& model_name, const std::string& model_path, std::unique_ptr<AutoFill>* autofill) { std::set<std::string> version_dirs; RETURN_IF_ERROR(GetDirectorySubdirs(model_path, &version_dirs)); // There must be at least one version directory that we can inspect to // attempt to determine the platform. For now we allow multiple versions // and only inspect the first verison directory to ensure it is valid. // We can add more aggressive checks later. if (version_dirs.size() == 0) { return Status( Status::Code::INTERNAL, "unable to autofill for '" + model_name + "' due to no version directories"); } // The model configuration will be the same across all the version directories const auto version_path = JoinPath({model_path, *(version_dirs.begin())}); std::set<std::string> plan_files; RETURN_IF_ERROR(GetDirectoryFiles( version_path, true /* skip_hidden_files */, &plan_files)); nvinfer1::IRuntime* runtime = nullptr; nvinfer1::ICudaEngine* engine = nullptr; std::string plan_file; Status status; bool found = false; for (auto file : plan_files) { const auto plan_path = JoinPath({version_path, file}); std::string plan_data_str; status = ReadTextFile(plan_path, &plan_data_str); if (!status.IsOk()) { continue; } std::vector<char> plan_data(plan_data_str.begin(), plan_data_str.end()); if (!LoadPlan(plan_data, -1 /* dla_core_id */, &runtime, &engine).IsOk()) { if (engine != nullptr) { engine->destroy(); engine = nullptr; } if (runtime != nullptr) { runtime->destroy(); runtime = nullptr; } } else { plan_file = file; found = true; break; } } if (!found) { return Status( Status::Code::INTERNAL, "unable to autofill for '" + model_name + "', unable to find a compatible plan file."); } autofill->reset(new AutoFillPlanImpl(model_name, plan_file, engine, runtime)); return Status::Success; } }} // namespace nvidia::inferenceserver
33.592445
80
0.670948
[ "shape", "vector", "model" ]
33ecf808e19dc6822d94fabe55b363077471dbd1
1,009
cpp
C++
src/ADT/APFloat.cpp
YiraSan/llvm-bindings
9fdae3c836eb329d42f8253adadf09ecaa44e2ee
[ "MIT" ]
155
2021-03-25T09:21:47.000Z
2022-03-30T01:51:40.000Z
src/ADT/APFloat.cpp
YiraSan/llvm-bindings
9fdae3c836eb329d42f8253adadf09ecaa44e2ee
[ "MIT" ]
13
2021-03-31T01:54:34.000Z
2022-03-19T05:43:45.000Z
src/ADT/APFloat.cpp
YiraSan/llvm-bindings
9fdae3c836eb329d42f8253adadf09ecaa44e2ee
[ "MIT" ]
20
2021-04-11T05:27:43.000Z
2022-03-06T04:48:15.000Z
#include "ADT/index.h" #include "Util/index.h" void APFloat::Init(Napi::Env env, Napi::Object &exports) { Napi::HandleScope scope(env); Napi::Function func = DefineClass(env, "APFloat", {}); constructor = Napi::Persistent(func); constructor.SuppressDestruct(); exports.Set("APFloat", func); } bool APFloat::IsClassOf(const Napi::Value &value) { return value.IsNull() || value.As<Napi::Object>().InstanceOf(constructor.Value()); } llvm::APFloat &APFloat::Extract(const Napi::Value &value) { return Unwrap(value.As<Napi::Object>())->getLLVMPrimitive(); } APFloat::APFloat(const Napi::CallbackInfo &info) : ObjectWrap(info) { Napi::Env env = info.Env(); if (!info.IsConstructCall() || info.Length() == 0 || !info[0].IsNumber()) { throw Napi::TypeError::New(env, ErrMsg::Class::APFloat::constructor); } double value = info[0].As<Napi::Number>(); apFloat = new llvm::APFloat(value); } llvm::APFloat &APFloat::getLLVMPrimitive() { return *apFloat; }
31.53125
86
0.663033
[ "object" ]
33f143cce913d7acb7442e008f970714539698f2
5,224
cpp
C++
mediaPlayer/MediaPlayerUtil.cpp
ZhouGuixin/CicadaPlayer
ef1c21181af2a161bfd930cbea2c3fc91714e636
[ "MIT" ]
448
2020-01-13T07:21:10.000Z
2022-03-31T09:03:03.000Z
mediaPlayer/MediaPlayerUtil.cpp
ZhouGuixin/CicadaPlayer
ef1c21181af2a161bfd930cbea2c3fc91714e636
[ "MIT" ]
370
2020-01-13T08:12:15.000Z
2022-03-24T15:46:02.000Z
mediaPlayer/MediaPlayerUtil.cpp
ZhouGuixin/CicadaPlayer
ef1c21181af2a161bfd930cbea2c3fc91714e636
[ "MIT" ]
124
2020-01-13T10:56:55.000Z
2022-03-31T06:25:55.000Z
// // MediaPlayerUtil.cpp // ApsaraPlayer // // Created by huang_jiafa on 2010/01/30. // Copyright (c) 2019 Aliyun. All rights reserved. // #define LOG_TAG "MeidaPlayerUtil" #include "utils/frame_work_log.h" #include "MediaPlayerUtil.h" #include "utils/timer.h" #include "utils/CicadaJSON.h" using namespace std; namespace Cicada { void MediaPlayerUtil::notifyPlayerLoop(int64_t time) { mLoopIndex++; if (mLastLoopTime == 0) { mLastLoopTime = time; } else { float timeS = float(time - mLastLoopTime) / 1000000; if (timeS > 1.0) { AF_LOGD("loop index is %f\n", (float) mLoopIndex / timeS); mLoopIndex = 0; mLastLoopTime = time; } } } void MediaPlayerUtil::render(int64_t pts) { ++mTotalRenderCount; if (1 == mTotalRenderCount) { mFirstRenderTime = af_getsteady_ms(); mLastRenderTime = af_getsteady_ms(); mLastRenderCount = 1; } else { int64_t diff = af_getsteady_ms() - mLastRenderTime; if (1000 <= diff) { mVideoRenderFps = (float) (mTotalRenderCount - mLastRenderCount) * 1000 / diff; AF_LOGD("KPI test total fps:%0.1f, Current FPS:%0.1f", (float) (mTotalRenderCount - 1) * 1000 / (af_getsteady_ms() - mFirstRenderTime), mVideoRenderFps); mLastRenderCount = mTotalRenderCount; mLastRenderTime = af_getsteady_ms(); } } } void MediaPlayerUtil::reset() { int64_t diff = (af_getsteady_ms() - mFirstRenderTime); if ((0 < diff) && (0 < mFirstRenderTime)) { AF_LOGI("KPI test finish: total fps:%0.1f", (float) (mTotalRenderCount - 1) * 1000 / diff); } mTotalRenderCount = 0; mLastRenderCount = 0; mFirstRenderTime = 0; mLastRenderTime = 0; mLastLoopTime = 0; mLoopIndex = 0; mVideoRenderFps = 0; } void MediaPlayerUtil::getPropertyJSONStr(const std::string &name, CicadaJSONArray &array, bool isArray, std::deque<StreamInfo *> &streamInfoQueue, demuxer_service *service) { if (nullptr == service) { return; } for (auto &it : streamInfoQueue) { std::string str = service->GetProperty(it->streamIndex, name); if (str.empty()) { continue; } if (isArray) { CicadaJSONArray subArray(str); for (int i = 0; i < subArray.getSize(); ++i) { CicadaJSONItem &tempItem = subArray.getItem(i); addPropertyType(tempItem, it->type); array.addJSON(tempItem); } } else { CicadaJSONItem loopItem(str); addPropertyType(loopItem, it->type); array.addJSON(loopItem); } } } void MediaPlayerUtil::addPropertyType(CicadaJSONItem &item, StreamType type) { switch (type) { case ST_TYPE_VIDEO: item.addValue("type", "video"); break; case ST_TYPE_AUDIO: item.addValue("type", "audio"); break; case ST_TYPE_SUB: item.addValue("type", "subtitle"); break; default: item.addValue("type", "unknown"); break; } } void MediaPlayerUtil::addURLProperty(const std::string &name, CicadaJSONArray &array, IDataSource *dataSource) { if (dataSource) { string str = dataSource->GetOption(name); if (str.empty()) { return; } CicadaJSONItem item(str); item.addValue("type", "url"); array.addJSON(item); } } void MediaPlayerUtil::notifyRead(enum readEvent event) { switch (event) { case readEvent_Again: mReadAgainIndex++; break; case readEvent_Got: mReadGotIndex++; break; case readEvent_timeOut: mReadTimeOutIndex++; break; case readEvent_Loop: mReadLoopIndex++; break; } int64_t time = af_gettime_relative(); if (mLastReadTime == 0) { mLastReadTime = time; } else { float timeS = float(time - mLastReadTime) / 1000000; if (timeS > 1.0) { AF_LOGD("mReadLoopIndex is \t %f\n", (float) mReadLoopIndex / timeS); AF_LOGD("mReadAgainIndex is\t %f\n", (float) mReadAgainIndex / timeS); AF_LOGD("mReadGotIndex is\t %f\n", (float) mReadGotIndex / timeS); AF_LOGD("mReadTimeOutIndex\t is %f\n", (float) mReadTimeOutIndex / timeS); AF_LOGD("\n"); mLastReadTime = time; mReadLoopIndex = mReadAgainIndex = mReadGotIndex = mReadTimeOutIndex = 0; } } } }
29.022222
114
0.517228
[ "render" ]
33f2c288791426298204674f3b8adcc9b2c4c873
1,888
cpp
C++
DP/BurstBalloons/BurstBalloons.cpp
yijingbai/LeetCode
6ae6dbdf3a720b4206323401a0ed16ac2066031e
[ "MIT" ]
2
2015-08-28T03:52:05.000Z
2015-09-03T09:54:40.000Z
DP/BurstBalloons/BurstBalloons.cpp
yijingbai/LeetCode
6ae6dbdf3a720b4206323401a0ed16ac2066031e
[ "MIT" ]
null
null
null
DP/BurstBalloons/BurstBalloons.cpp
yijingbai/LeetCode
6ae6dbdf3a720b4206323401a0ed16ac2066031e
[ "MIT" ]
null
null
null
// Source : https://leetcode.com/problems/burst-balloons/ // Author : Yijing Bai // Date : 2016-03-24 /********************************************************************************** * * Given n balloons, indexed from 0 to n-1. Each balloon is painted with a * number on it represented by array nums. * * You are asked to burst all the balloons. If the you burst * balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left * and right are adjacent indices of i. After the burst, the left and right * then becomes adjacent. * * Find the maximum coins you can collect by bursting the balloons wisely. * * Note: * (1) You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can * not burst them. * (2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100 * * Example: * * Given [3, 1, 5, 8] * * Return 167 * * nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] * coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 * * Credits:Special thanks to @dietpepsi for adding this problem and creating all test * cases. * **********************************************************************************/ class Solution { public: int maxCoins(vector<int>& iNums) { int nums[iNums.size() + 2]; int n = 1; for (int x : iNums) if (x > 0) nums[n++] = x; nums[0] = nums[n++] = 1; int dp[n][n] = {}; for (int k = 2; k < n; ++k) { for (int left = 0; left < n - k; ++left) { int right = left + k; for (int i = left + 1; i < right; ++i) { dp[left][right] = max(dp[left][right], nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right] ); } } } return dp[0][n - 1]; } };
32
87
0.450742
[ "vector" ]
33fcf271388433d77a8a19990eb5fcd57d4b52a4
10,907
cc
C++
deepmath/guidance/sequence_op.cc
LaudateCorpus1/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
[ "Apache-2.0" ]
830
2016-11-07T21:46:27.000Z
2022-03-23T08:01:03.000Z
deepmath/guidance/sequence_op.cc
LaudateCorpus1/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
[ "Apache-2.0" ]
26
2016-11-07T22:06:31.000Z
2022-02-16T00:18:29.000Z
deepmath/guidance/sequence_op.cc
LaudateCorpus1/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
[ "Apache-2.0" ]
168
2016-11-07T21:48:55.000Z
2022-03-19T02:47:14.000Z
/* Copyright 2017 Google Inc. 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. ==============================================================================*/ // Serialize clause examples as sequences #include "tensorflow/core/framework/numeric_op.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/shape_inference.h" #include "deepmath/guidance/clause_utils.h" #include "deepmath/guidance/make_fast_clause.h" #include "deepmath/guidance/serialize.h" #include "deepmath/guidance/vocabulary.h" #include "deepmath/eprover/clause.pb.h" #include "deepmath/eprover/fol_formula.pb.h" #include "deepmath/eprover/prover_clause_examples.pb.h" using deepmath::FastClause; using deepmath::FirstOrderLogicTerm; using deepmath::FirstOrderLogicClause; namespace errors = tensorflow::errors; using tensorflow::OpKernel; using tensorflow::OpKernelConstruction; using tensorflow::OpKernelContext; using tensorflow::Status; using tensorflow::Tensor; using tensorflow::TensorShape; using tensorflow::TensorShapeUtils; using tensorflow::shape_inference::InferenceContext; using tensorflow::shape_inference::ShapeHandle; using tensorflow::int64; namespace deepmath { namespace { REGISTER_OP("RandomClausesAsSequence") .Input("examples: string") .Output("key: string") .Output("negated_conjecture: string") .Output("clauses: string") .Output("labels: bool") .Attr("vocab: string") .Attr("seed: int = 0") .Attr("seed2: int = 0") .Doc(R"doc( Select one positive and one negative clause from a ProverClauseExamples. If the ProverClauseExamples doesn't have both positives and negatives, clauses and labels will be empty. examples: Serialized ProverClauseExamples. key: Key field of ProverClauseExamples. negated_conjecture: 0-D `int32` negated conjecture encoded as `string`. clauses: 1-D `int32` clauses encoded as `string`: one positive, one negative. labels: 1-D labels (true for positive, false for negative). vocab: Path to vocabulary file. seed: If either `seed` or `seed2` are set to be non-zero, the random number generator is seeded by the given seed. Otherwise, it is seeded by a random seed. seed2: A second seed to avoid seed collision. )doc"); REGISTER_OP("FastClausesAsSequence") .Input("fast_clauses: string") .Output("ids: int32") .Attr("conjunction: bool = false") .SetShapeFn([](InferenceContext* c) { ShapeHandle fast_clauses; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &fast_clauses)); bool conjunction; TF_RETURN_IF_ERROR(c->GetAttr("conjunction", &conjunction)); if (conjunction) { c->set_output(0, c->UnknownShapeOfRank(1)); } else { c->set_output(0, c->Matrix(c->Dim(fast_clauses, 0), c->UnknownDim())); } return Status::OK(); }) .Doc(R"doc( Serialize FastClauses as sequences of ids. fast_clauses: Serialized FastClause protos. conjunction: Whether to interpret the last dimension as a conjunction. ids: Vocab id sequences, padded on the right. )doc"); REGISTER_OP("FastClausesAsSequenceJagged") .Input("fast_clauses: string") .Output("sizes: int32") .Output("flat: int32") .SetShapeFn([](InferenceContext* c) { ShapeHandle fast_clauses; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &fast_clauses)); c->set_output(0, fast_clauses); c->set_output(1, c->UnknownShapeOfRank(1)); return Status::OK(); }) .Doc(R"doc( Serialize FastClauses as sequences of ids. fast_clauses: Serialized FastClause protos. sizes: Length of each clause. flat: Concatenated tokens ids from each clause. )doc"); class RandomClausesAsSequence : public OpKernel { public: explicit RandomClausesAsSequence(OpKernelConstruction* context) : OpKernel(context), helper_(context) {} void Compute(OpKernelContext* context) override { // Parse and choose positive and negative const Tensor& serialized = context->input(0); OP_REQUIRES(context, TensorShapeUtils::IsScalar(serialized.shape()), errors::InvalidArgument("Need scalar examples, got shape ", serialized.shape().DebugString())); ProverClauseExamples examples; OP_REQUIRES_OK(context, ParseExamples(serialized.scalar<string>()(), &examples)); const ProverClause *positive, *negative; const bool valid = helper_.Choose(examples, &positive, &negative); // Allocate outputs Tensor* key = nullptr; Tensor* negated_conjecture = nullptr; Tensor* clauses = nullptr; Tensor* labels = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({}), &key)); OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape({}), &negated_conjecture)); OP_REQUIRES_OK(context, context->allocate_output( 2, TensorShape({2 * valid}), &clauses)); OP_REQUIRES_OK(context, context->allocate_output( 3, TensorShape({2 * valid}), &labels)); // Grab key key->scalar<string>()() = examples.key(); // Serialize negative conjecture SerializeToString(&SerializeClauses, examples.cnf().negated_conjecture(), &negated_conjecture->scalar<string>()()); // If possible, serialize positive and negative examples if (valid) { SerializeToString(&SerializeClause, positive->clause(), &clauses->vec<string>()(0)); SerializeToString(&SerializeClause, negative->clause(), &clauses->vec<string>()(1)); labels->vec<bool>()(0) = true; labels->vec<bool>()(1) = false; } } private: RandomClausesHelper helper_; template <class T> void SerializeToString(void (*serialize)(SlowSerializeContext*, const T&), const T& data, string* output) { SlowSerializeContext context(helper_.vocab()); serialize(&context, data); output->insert(0, reinterpret_cast<const char*>(context.output().data()), context.output().size() * sizeof(int)); } }; class FastClausesAsSequence : public OpKernel { public: explicit FastClausesAsSequence(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("conjunction", &conjunction_)); } void Compute(OpKernelContext* context) override { // Check input const Tensor& protos = context->input(0); OP_REQUIRES(context, protos.dims() == 1, errors::InvalidArgument("Expected 1-D input, got ", protos.shape().DebugString())); const auto protos_vec = protos.vec<string>(); const int64 n = protos_vec.dimension(0); if (conjunction_) { // Parse all clauses std::vector<FastClause> clauses(n); for (int64 i = 0; i < n; i++) { OP_REQUIRES_OK(context, ParseFastClause(protos_vec(i), &clauses[i])); } // Convert to id sequence FastSerializeContext fast; SerializeClauses(&fast, clauses); const std::vector<int>& sequence = fast.output(); const int64 length = sequence.size(); // Copy to output Tensor* output = nullptr; OP_REQUIRES_OK( context, context->allocate_output(0, TensorShape({length}), &output)); memcpy(output->vec<int>().data(), sequence.data(), length * sizeof(int)); } else { // Parse all clauses and convert to sequences std::vector<FastSerializeContext> fasts(n); int64 max_size = 0; { FastClause clause; for (int64 i = 0; i < n; i++) { OP_REQUIRES_OK(context, ParseFastClause(protos_vec(i), &clause)); SerializeClause(&fasts[i], clause); max_size = std::max(max_size, static_cast<int64>(fasts[i].output().size())); } } // Pad and copy to output Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output( 0, TensorShape({n, max_size}), &output)); auto output_flat = output->flat<int>(); output_flat.setZero(); for (int64 i = 0; i < n; i++) { const std::vector<int>& seq = fasts[i].output(); memcpy(output_flat.data() + i * max_size, seq.data(), seq.size() * sizeof(int)); } } } private: bool conjunction_; }; class FastClausesAsSequenceJagged : public OpKernel { public: explicit FastClausesAsSequenceJagged(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { // Check input const Tensor& protos_t = context->input(0); OP_REQUIRES(context, protos_t.dims() == 1, errors::InvalidArgument("Expected 1-D input, got ", protos_t.shape().DebugString())); const auto protos = protos_t.vec<string>(); // Allocate sizes Tensor* sizes_t = nullptr; OP_REQUIRES_OK( context, context->allocate_output(0, TensorShape({protos.dimension(0)}), &sizes_t)); auto sizes = sizes_t->vec<int>(); // Parse all clauses and convert to sequences FastSerializeContext fast; { FastClause clause; for (int64 i = 0; i < protos.dimension(0); i++) { OP_REQUIRES_OK(context, ParseFastClause(protos(i), &clause)); const int before = fast.output().size(); SerializeClause(&fast, clause); sizes(i) = fast.output().size() - before; } } // Copy flat to output Tensor* flat_t = nullptr; OP_REQUIRES_OK( context, context->allocate_output( 1, TensorShape({static_cast<int64>(fast.output().size())}), &flat_t)); auto flat = flat_t->vec<int>(); memcpy(flat.data(), fast.output().data(), fast.output().size() * sizeof(int)); } }; REGISTER_KERNEL_BUILDER( Name("RandomClausesAsSequence").Device(tensorflow::DEVICE_CPU), RandomClausesAsSequence); REGISTER_KERNEL_BUILDER( Name("FastClausesAsSequence").Device(tensorflow::DEVICE_CPU), FastClausesAsSequence); REGISTER_KERNEL_BUILDER( Name("FastClausesAsSequenceJagged").Device(tensorflow::DEVICE_CPU), FastClausesAsSequenceJagged); } // namespace } // namespace deepmath
36.115894
80
0.656001
[ "shape", "vector" ]
33fdc997de5a022210f6c12a78602b08078952e7
28,122
cc
C++
tensorflow/lite/delegates/gpu/common/selectors/operation_selector.cc
ashutom/tensorflow-upstream
c16069c19de9e286dd664abb78d0ea421e9f32d4
[ "Apache-2.0" ]
675
2019-02-07T01:23:19.000Z
2022-03-28T05:45:10.000Z
tensorflow/lite/delegates/gpu/common/selectors/operation_selector.cc
CaptainGizzy21/tensorflow
3457a2b122e50b4d44ceaaed5a663d635e5c22df
[ "Apache-2.0" ]
843
2019-01-25T01:06:46.000Z
2022-03-16T11:15:53.000Z
tensorflow/lite/delegates/gpu/common/selectors/operation_selector.cc
CaptainGizzy21/tensorflow
3457a2b122e50b4d44ceaaed5a663d635e5c22df
[ "Apache-2.0" ]
83
2019-02-20T06:18:46.000Z
2022-03-20T09:36:09.000Z
/* Copyright 2020 The TensorFlow Authors. 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 "tensorflow/lite/delegates/gpu/common/selectors/operation_selector.h" #include "absl/strings/str_cat.h" #include "absl/types/any.h" #include "tensorflow/lite/delegates/gpu/common/data_type.h" #include "tensorflow/lite/delegates/gpu/common/gpu_info.h" #include "tensorflow/lite/delegates/gpu/common/operations.h" #include "tensorflow/lite/delegates/gpu/common/selectors/convolution_selector.h" #include "tensorflow/lite/delegates/gpu/common/selectors/convolution_transposed_selector.h" #include "tensorflow/lite/delegates/gpu/common/selectors/default_selector.h" #include "tensorflow/lite/delegates/gpu/common/selectors/dw_convolution_selector.h" #include "tensorflow/lite/delegates/gpu/common/selectors/fully_connected_selector.h" #include "tensorflow/lite/delegates/gpu/common/selectors/simple_selectors.h" #include "tensorflow/lite/delegates/gpu/common/shape.h" #include "tensorflow/lite/delegates/gpu/common/status.h" #include "tensorflow/lite/delegates/gpu/common/task/storage_type_util.h" #include "tensorflow/lite/delegates/gpu/common/task/tensor_desc.h" #include "tensorflow/lite/delegates/gpu/common/task/weights_conversion.h" #include "tensorflow/lite/delegates/gpu/common/tasks/elementwise.h" #include "tensorflow/lite/delegates/gpu/common/tasks/mean_stddev_normalization.h" #include "tensorflow/lite/delegates/gpu/common/tasks/transpose.h" #include "tensorflow/lite/delegates/gpu/common/tensor.h" #include "tensorflow/lite/delegates/gpu/common/winograd_util.h" namespace tflite { namespace gpu { namespace { bool IsRecommendedForWinograd4x4To6x6(const Convolution2DAttributes& attr, const GpuInfo& gpu_info, const BHWC& dst_shape) { const int tiles_x = DivideRoundUp(dst_shape.w, 4); const int tiles_y = DivideRoundUp(dst_shape.h, 4); const int total_tiles = tiles_x * tiles_y; const int src_depth = DivideRoundUp(attr.weights.shape.i, 4); const int dst_depth = DivideRoundUp(attr.weights.shape.o, 4); int min_depth = 16; if (gpu_info.IsAdreno() || gpu_info.IsAMD()) { min_depth = 32; } int min_tiles = 32; if (gpu_info.IsAdreno()) { if (gpu_info.adreno_info.IsAdreno6xx()) { min_tiles = 128; } else { min_tiles = 64; } } if (gpu_info.IsAMD()) { min_tiles = 64; } if (total_tiles >= min_tiles * 8) { min_depth /= 4; min_depth = std::max(min_depth, 8); } else if (total_tiles >= min_tiles * 4) { min_depth /= 2; min_depth = std::max(min_depth, 8); } const bool recommended_channels = src_depth >= min_depth && dst_depth >= min_depth; const bool recommended_hw = total_tiles >= min_tiles; return recommended_channels && recommended_hw; } absl::Status WinogradFromNode(const GpuInfo& gpu_info, const std::vector<Value*>& inputs, const std::vector<Value*>& outputs, const OperationDef& op_def, ModelHints hints, const BHWC& input_shape, const BHWC& output_shape, const Convolution2DAttributes& attr, GPUOperationsSubgraph* gpu_subgraph) { if (!IsSuitableForWinograd4x4To6x6(attr)) { return absl::UnimplementedError("No implementation for this case."); } if (!IsRecommendedForWinograd4x4To6x6(attr, gpu_info, output_shape)) { return absl::UnimplementedError("Not recommended for this case."); } const int tiles_x = DivideRoundUp(output_shape.w, 4); const int tiles_y = DivideRoundUp(output_shape.h, 4); const BHWC shape_0{input_shape.b, 36, tiles_x * tiles_y, input_shape.c}; const BHWC shape_1{input_shape.b, 36, tiles_x * tiles_y, output_shape.c}; TensorDescriptor td_0; RETURN_IF_ERROR(SelectBestStorageType( gpu_info, shape_0, op_def.src_tensors[0].storage_type, op_def.src_tensors[0].data_type, op_def.src_tensors[0].layout, &td_0.storage_type)); td_0.data_type = op_def.src_tensors[0].data_type; td_0.layout = op_def.src_tensors[0].layout; TensorDescriptor td_1; RETURN_IF_ERROR(SelectBestStorageType( gpu_info, shape_1, op_def.src_tensors[0].storage_type, op_def.src_tensors[0].data_type, op_def.src_tensors[0].layout, &td_1.storage_type)); td_1.data_type = op_def.src_tensors[0].data_type; td_1.layout = op_def.src_tensors[0].layout; gpu_subgraph->new_tensors = {{shape_0, td_0}, {shape_1, td_1}}; gpu_subgraph->operations.clear(); gpu_subgraph->operations.resize(3); OperationDef winograd_up_def; winograd_up_def.precision = op_def.precision; winograd_up_def.src_tensors.push_back(op_def.src_tensors[0]); winograd_up_def.dst_tensors.push_back(td_0); auto& winograd_up = gpu_subgraph->operations[0]; winograd_up.operation = SelectWinograd4x4To36(gpu_info, attr.padding, winograd_up_def); winograd_up.input_ids = {static_cast<int>(inputs[0]->id)}; winograd_up.output_ids = {-1}; OperationDef conv_def; conv_def.precision = op_def.precision; conv_def.src_tensors.push_back(td_0); conv_def.dst_tensors.push_back(td_1); auto& conv = gpu_subgraph->operations[1]; conv.input_ids = {-1}; conv.output_ids = {-2}; conv.operation = SelectConvolutionForWinograd(attr, input_shape, gpu_info, conv_def, hints); OperationDef winograd_down_def; winograd_down_def.precision = op_def.precision; winograd_down_def.src_tensors.push_back(td_1); winograd_down_def.dst_tensors.push_back(op_def.dst_tensors[0]); auto& winograd_down = gpu_subgraph->operations[2]; winograd_down.input_ids = {-2}; winograd_down.output_ids = {static_cast<int>(outputs[0]->id)}; auto bias_copy = attr.bias; if (bias_copy.shape.v < attr.weights.shape.o) { bias_copy.shape = Linear(attr.weights.shape.o); bias_copy.data.resize(attr.weights.shape.o); } winograd_down.operation = SelectWinograd36To4x4(gpu_info, winograd_down_def, bias_copy); return absl::OkStatus(); } } // namespace absl::Status GPUOperationFromNode(const GpuInfo& gpu_info, const OperationDef& op_def, ModelHints hints, const std::vector<Value*>& inputs, const std::vector<Value*>& outputs, const Node& node, GPUOperationsSubgraph* gpu_subgraph) { std::unique_ptr<GPUOperation>* gpu_op = InitSingleOpSubgraph(inputs, outputs, gpu_subgraph); auto op_type = OperationTypeFromString(node.operation.type); switch (op_type) { case OperationType::ADD: { if (inputs.size() == 2 && (inputs[0]->tensor.shape.c == inputs[1]->tensor.shape.c || inputs[1]->tensor.shape.c == 1)) { GPUOperation operation = CreateElementwiseTwoInput(op_def, op_type, inputs[1]->tensor.shape); *gpu_op = absl::make_unique<GPUOperation>(std::move(operation)); return absl::OkStatus(); } else if (inputs.size() >= 2) { auto output = outputs[0]; std::vector<int> channels(inputs.size()); for (int i = 0; i < inputs.size(); ++i) { channels[i] = inputs[i]->tensor.shape.c; } SelectAdd(op_def, channels, output->tensor.shape.c, gpu_op); return absl::OkStatus(); } else if (inputs.size() == 1 && node.operation.attributes.has_value()) { auto attr = absl::any_cast<ElementwiseAttributes>(node.operation.attributes); GPUOperation operation = CreateElementwise(gpu_info, op_def, op_type, attr); *gpu_op = absl::make_unique<GPUOperation>(std::move(operation)); return absl::OkStatus(); } return absl::UnimplementedError(absl::StrCat( "No support of ", node.operation.type, " with this parameters")); } case OperationType::BATCHED_MATMUL: { // Currently only batch = 1 is supported. // Matmul replaced with this sequence: // 1) Transpose second tensor(weights). (1x1xHxW)->(Wx1x1xH) // 2) Convert second tensor(weights) from 1) to Convolution weights // 3) Run usual convolution auto second_shape = inputs[1]->tensor.shape; auto dst_shape = outputs[0]->tensor.shape; if (dst_shape.b != 1) { return absl::UnimplementedError( "Currently only batch = 1 supported for BATCHED_MATMUL."); } BHWC weights_shape(second_shape.c, 1, 1, second_shape.w); Convolution2DAttributes attr; attr.strides = HW(1, 1); attr.dilations = HW(1, 1); attr.padding.appended = HW(0, 0); attr.padding.prepended = HW(0, 0); attr.bias.shape = Linear(weights_shape.b); attr.bias.data.resize(weights_shape.b, 0.0f); TensorDescriptor transposed_desc = {op_def.src_tensors[1].data_type, op_def.src_tensors[1].storage_type, Layout::BHWC}; RETURN_IF_ERROR(SelectBestStorageType( gpu_info, weights_shape, transposed_desc.storage_type, transposed_desc.data_type, transposed_desc.layout, &transposed_desc.storage_type)); TensorDescriptor weights_desc = {op_def.src_tensors[1].data_type, TensorStorageType::BUFFER, Layout::BHWC}; gpu_subgraph->operations.clear(); gpu_subgraph->operations.resize(3); auto& transpose_op = gpu_subgraph->operations[0]; auto& converter_op = gpu_subgraph->operations[1]; auto& conv_op = gpu_subgraph->operations[2]; conv_op.input_ids = {static_cast<int>(inputs[0]->id), -1}; conv_op.output_ids = {static_cast<int>(outputs[0]->id)}; OperationDef conv_def = op_def; conv_def.src_tensors[1] = weights_desc; WeightsDescription conv_weights_desc; conv_op.operation = SelectConvolutionWithDynamicWeights( attr, weights_shape, dst_shape, gpu_info, conv_def, hints, &conv_weights_desc); int aligned_output = AlignByN(weights_shape.b, conv_weights_desc.GetOutputGroupSize() * 4); int aligned_input = AlignByN(weights_shape.c, 4); gpu_subgraph->new_tensors = {{BHWC(1, 1, 1, aligned_output * aligned_input * weights_shape.h * weights_shape.w), weights_desc}, {weights_shape, transposed_desc}}; OperationDef converter_def; converter_def.precision = op_def.precision; converter_def.src_tensors.push_back(transposed_desc); converter_def.dst_tensors.push_back(weights_desc); converter_op.input_ids = {-2}; converter_op.output_ids = {-1}; converter_op.operation = SelectConverterToConvWeights(conv_weights_desc, converter_def, hints); OperationDef transpose_def; transpose_def.precision = op_def.precision; transpose_def.src_tensors.push_back(op_def.src_tensors[1]); transpose_def.dst_tensors.push_back(transposed_desc); transpose_op.input_ids = {static_cast<int>(inputs[1]->id)}; transpose_op.output_ids = {-2}; TransposeAttributes transpose_attr; transpose_attr.perm = BHWC(3, 0, 1, 2); transpose_op.operation = absl::make_unique<GPUOperation>( CreateTranspose(transpose_def, transpose_attr)); return absl::OkStatus(); } case OperationType::CONCAT: { auto attr = absl::any_cast<ConcatAttributes>(node.operation.attributes); const int max_inputs = gpu_info.GetMaxImageArguments() - 8; if (inputs.size() >= max_inputs) { int groups = DivideRoundUp(inputs.size(), max_inputs); gpu_subgraph->operations.clear(); gpu_subgraph->operations.resize(groups); BHWC concatenated_shape = inputs[0]->tensor.shape; concatenated_shape.set(attr.axis, 0); for (int g = 0; g < groups; ++g) { std::vector<int> channels; auto& concat_op = gpu_subgraph->operations[g]; OperationDef new_def; new_def.precision = op_def.precision; if (g != 0) { // concatenated tensor from previos concats new_def.src_tensors.push_back(op_def.dst_tensors[0]); concat_op.input_ids = {-g}; channels.push_back(concatenated_shape.c); } for (int i = 0; i < max_inputs; ++i) { int src_index = g * max_inputs + i; if (src_index >= op_def.src_tensors.size()) { break; } new_def.src_tensors.push_back(op_def.src_tensors[src_index]); concat_op.input_ids.push_back(inputs[src_index]->id); channels.push_back(inputs[src_index]->tensor.shape.c); int current_size = concatenated_shape.get(attr.axis); concatenated_shape.set( attr.axis, current_size + inputs[src_index]->tensor.shape.get(attr.axis)); } new_def.dst_tensors.push_back(op_def.dst_tensors[0]); if (g == groups - 1) { // last concat concat_op.output_ids = {static_cast<int>(outputs[0]->id)}; } else { // intermediate concat, create new tensor for it concat_op.output_ids = {-(g + 1)}; gpu_subgraph->new_tensors.push_back( {concatenated_shape, op_def.dst_tensors[0]}); } RETURN_IF_ERROR(SelectConcat(attr, channels, new_def, gpu_info, &concat_op.operation)); } return absl::OkStatus(); } else { std::vector<int> channels(inputs.size()); for (int i = 0; i < inputs.size(); ++i) { channels[i] = inputs[i]->tensor.shape.c; } return SelectConcat(attr, channels, op_def, gpu_info, gpu_op); } } case OperationType::CONVOLUTION_2D: { auto attr = absl::any_cast<Convolution2DAttributes>(node.operation.attributes); auto input_shape = inputs[0]->tensor.shape; auto output_shape = outputs[0]->tensor.shape; if (inputs.size() == 1) { if (!hints.Check(ModelHints::kNoWinogradOptimizations) && WinogradFromNode(gpu_info, inputs, outputs, op_def, hints, input_shape, output_shape, attr, gpu_subgraph) .ok()) { return absl::OkStatus(); } else { gpu_op = InitSingleOpSubgraph(inputs, outputs, gpu_subgraph); *gpu_op = SelectConvolution(attr, output_shape, gpu_info, op_def, hints); return absl::OkStatus(); } } else { auto weights_shape = inputs[1]->tensor.shape; if (attr.bias.data.empty()) { attr.bias.shape = Linear(weights_shape.b); attr.bias.data.resize(weights_shape.b, 0.0f); } TensorDescriptor weights_desc = {op_def.src_tensors[1].data_type, TensorStorageType::BUFFER, Layout::BHWC}; gpu_subgraph->operations.clear(); gpu_subgraph->operations.resize(2); auto& converter_op = gpu_subgraph->operations[0]; auto& conv_op = gpu_subgraph->operations[1]; conv_op.input_ids = {static_cast<int>(inputs[0]->id), -1}; conv_op.output_ids = {static_cast<int>(outputs[0]->id)}; OperationDef conv_def = op_def; conv_def.src_tensors[1] = weights_desc; WeightsDescription conv_weights_desc; conv_op.operation = SelectConvolutionWithDynamicWeights( attr, weights_shape, output_shape, gpu_info, conv_def, hints, &conv_weights_desc); int aligned_output = AlignByN( weights_shape.b, conv_weights_desc.GetOutputGroupSize() * 4); int aligned_input = AlignByN(weights_shape.c, 4); gpu_subgraph->new_tensors = { {BHWC(1, 1, 1, aligned_output * aligned_input * weights_shape.h * weights_shape.w), weights_desc}}; OperationDef converter_def; converter_def.precision = op_def.precision; converter_def.src_tensors.push_back(op_def.src_tensors[1]); converter_def.dst_tensors.push_back(weights_desc); converter_op.input_ids = {static_cast<int>(inputs[1]->id)}; converter_op.output_ids = {-1}; converter_op.operation = SelectConverterToConvWeights( conv_weights_desc, converter_def, hints); return absl::OkStatus(); } } case OperationType::CONVOLUTION_TRANSPOSED: { auto attr = absl::any_cast<ConvolutionTransposedAttributes>( node.operation.attributes); if (inputs.size() == 1) { *gpu_op = SelectConvolutionTransposed(attr, gpu_info, op_def); return absl::OkStatus(); } else { // CONVOLUTION_TRANSPOSED with runtime weights OHWI weights_shape = OHWI(inputs[1]->tensor.shape.b, inputs[1]->tensor.shape.h, inputs[1]->tensor.shape.w, inputs[1]->tensor.shape.c); if (attr.bias.data.empty()) { attr.bias.shape = Linear(weights_shape.o); attr.bias.data.resize(weights_shape.o, 0.0f); } gpu_subgraph->operations.clear(); gpu_subgraph->operations.resize(2); auto& converter_op = gpu_subgraph->operations[0]; auto& conv_op = gpu_subgraph->operations[1]; WeightsDescription weights_desc; conv_op.operation = SelectConvolutionTransposedWithDynamicWeights( attr, gpu_info, op_def, &weights_desc); conv_op.output_ids = {static_cast<int>(outputs[0]->id)}; const int dst_depth = AlignByN(DivideRoundUp(weights_shape.o, 4), weights_desc.GetOutputGroupSize()); const int src_depth = DivideRoundUp(weights_shape.i, 4); const int kernel_x = weights_shape.w; const int kernel_y = weights_shape.h; if (weights_desc.layout == WeightsLayout::k2DX4I4YIsSpatialIAndXIsOOGroupO4 || weights_desc.layout == WeightsLayout::k2DX4O4YIsSpatialIAndXIsOOGroupI4) { // weights are 4x textures 2d conv_op.input_ids = {static_cast<int>(inputs[0]->id), -1, -2, -3, -4}; int texture_width = dst_depth; int texture_height = src_depth * kernel_x * kernel_y; for (int i = 0; i < 4; ++i) { gpu_subgraph->new_tensors.push_back( {BHWC(1, texture_height, texture_width, 4), TensorDescriptor(op_def.GetDataType(), TensorStorageType::TEXTURE_2D, Layout::HWC)}); } } else { // weights is single buffer conv_op.input_ids = {static_cast<int>(inputs[0]->id), -1}; gpu_subgraph->new_tensors = { {BHWC( 1, 1, 1, GetTotalElementsCountForLayout(weights_desc, weights_shape)), TensorDescriptor(op_def.GetDataType(), TensorStorageType::BUFFER, Layout::HWC)}}; } OperationDef conv_def = conv_op.operation->GetDefinition(); OperationDef converter_def; converter_def.precision = op_def.precision; converter_def.src_tensors.push_back(op_def.src_tensors[1]); for (int i = 1; i < conv_def.src_tensors.size(); ++i) { converter_def.dst_tensors.push_back(conv_def.src_tensors[i]); converter_op.output_ids.push_back(-i); } converter_op.input_ids = {static_cast<int>(inputs[1]->id)}; converter_op.operation = SelectConverterToConvWeights(weights_desc, converter_def, hints); return absl::OkStatus(); } } case OperationType::DEPTHWISE_CONVOLUTION: { auto attr = absl::any_cast<DepthwiseConvolution2DAttributes>( node.operation.attributes); if (inputs.size() == 1) { *gpu_op = SelectDWConvolution(attr, gpu_info, op_def); } else { if (inputs[1]->tensor.shape.b != 1) { return absl::UnimplementedError( "No support of depthwise runtime weights with channel multiplier " "!= 1"); } *gpu_op = SelectDWConvolutionDynamicWeights(attr, gpu_info, op_def); } return absl::OkStatus(); } case OperationType::DEPTH_TO_SPACE: { auto attr = absl::any_cast<SpaceToDepthAttributes>(node.operation.attributes); SelectDepthToSpace(attr, op_def, gpu_op); return absl::OkStatus(); } case OperationType::FULLY_CONNECTED: { auto attr = absl::any_cast<FullyConnectedAttributes>(node.operation.attributes); *gpu_op = SelectFullyConnected(attr, gpu_info, op_def, inputs[0]->tensor.shape.b); return absl::OkStatus(); } case OperationType::FULLY_CONNECTED_INT8: { auto attr = absl::any_cast<FullyConnectedInt8Attributes>( node.operation.attributes); *gpu_op = SelectFullyConnected(attr, gpu_info, op_def); return absl::OkStatus(); } case OperationType::GATHER: { auto attr = absl::any_cast<GatherAttributes>(node.operation.attributes); RETURN_IF_ERROR(SelectGather(attr, op_def, gpu_op)); return absl::OkStatus(); } case OperationType::LSTM: { *gpu_op = SelectLSTM(op_def, gpu_info); return absl::OkStatus(); } case OperationType::MAX_UNPOOLING_2D: { auto attr = absl::any_cast<MaxUnpooling2DAttributes>(node.operation.attributes); *gpu_op = SelectMaxUnpooling(attr, op_def); return absl::OkStatus(); } case OperationType::MEAN: { auto attr = absl::any_cast<MeanAttributes>(node.operation.attributes); *gpu_op = SelectReduce(attr.dims, inputs[0]->tensor.shape, op_type, op_def, gpu_info); return absl::OkStatus(); } case OperationType::MEAN_STDDEV_NORMALIZATION: { MeanStdDevNormalization operation = CreateMeanStdDevNormalization( op_def, gpu_info, (inputs[0]->tensor.shape.c + 3) / 4); *gpu_op = absl::make_unique<MeanStdDevNormalization>(std::move(operation)); return absl::OkStatus(); } case OperationType::PAD: { auto attr = absl::any_cast<PadAttributes>(node.operation.attributes); SelectPadding(attr, op_def, gpu_op); return absl::OkStatus(); } case OperationType::POOLING_2D: { auto attr = absl::any_cast<Pooling2DAttributes>(node.operation.attributes); *gpu_op = SelectPooling(attr, op_def); return absl::OkStatus(); } case OperationType::PRELU: { auto attr = absl::any_cast<PReLUAttributes>(node.operation.attributes); *gpu_op = SelectPReLU(attr, gpu_info, op_def); return absl::OkStatus(); } case OperationType::QUANTIZE_AND_DEQUANTIZE: { auto attr = absl::any_cast<QuantizeAndDequantizeAttributes>( node.operation.attributes); *gpu_op = SelectQuantizeAndDequantize(attr, op_def); return absl::OkStatus(); } case OperationType::RELU: { auto attr = absl::any_cast<ReLUAttributes>(node.operation.attributes); *gpu_op = SelectReLU(attr, op_def); return absl::OkStatus(); } case OperationType::RESAMPLER: { *gpu_op = SelectResampler(op_def); return absl::OkStatus(); } case OperationType::RESHAPE: { const int src_channels = inputs[0]->tensor.shape.c; auto attr = absl::any_cast<ReshapeAttributes>(node.operation.attributes); SelectReshape(src_channels, attr.new_shape.c, op_def, gpu_op); return absl::OkStatus(); } case OperationType::RESIZE: { auto attr = absl::any_cast<Resize2DAttributes>(node.operation.attributes); return SelectResize(attr, op_def, gpu_op); } case OperationType::SLICE: { auto attr = absl::any_cast<SliceAttributes>(node.operation.attributes); SelectStridedSlice(attr, op_def, gpu_op); return absl::OkStatus(); } case OperationType::SOFTMAX: { SelectSoftmax(inputs[0]->tensor.shape, op_def, gpu_op); return absl::OkStatus(); } case OperationType::SPACE_TO_DEPTH: { auto attr = absl::any_cast<SpaceToDepthAttributes>(node.operation.attributes); SelectSpaceToDepth(attr, op_def, gpu_op); return absl::OkStatus(); } case OperationType::SPLIT: { auto attr = absl::any_cast<SplitAttributes>(node.operation.attributes); SelectSplit(attr, op_def, gpu_op); return absl::OkStatus(); } case OperationType::TILE: { *gpu_op = SelectTile(op_def, inputs[0]->tensor.shape); return absl::OkStatus(); } case OperationType::TRANSPOSE: { auto attr = absl::any_cast<TransposeAttributes>(node.operation.attributes); SelectTranspose(attr, op_def, gpu_op); return absl::OkStatus(); } case OperationType::ABS: case OperationType::COPY: case OperationType::COS: case OperationType::ELU: case OperationType::EXP: case OperationType::HARD_SWISH: case OperationType::LOG: case OperationType::NEG: case OperationType::RSQRT: case OperationType::SIGMOID: case OperationType::SIN: case OperationType::SQRT: case OperationType::SQUARE: case OperationType::TANH: { GPUOperation operation = CreateElementwiseOneInput(gpu_info, op_def, op_type); *gpu_op = absl::make_unique<GPUOperation>(std::move(operation)); return absl::OkStatus(); } case OperationType::DIV: case OperationType::EQUAL: case OperationType::GREATER: case OperationType::GREATER_EQUAL: case OperationType::LESS: case OperationType::LESS_EQUAL: case OperationType::MAXIMUM: case OperationType::MINIMUM: case OperationType::MUL: case OperationType::NOT_EQUAL: case OperationType::POW: case OperationType::SQUARED_DIFF: case OperationType::SUB: { if (inputs.size() == 2) { GPUOperation operation = CreateElementwiseTwoInput(op_def, op_type, inputs[1]->tensor.shape); *gpu_op = absl::make_unique<GPUOperation>(std::move(operation)); return absl::OkStatus(); } else if (inputs.size() == 1 && node.operation.attributes.has_value()) { auto attr = absl::any_cast<ElementwiseAttributes>(node.operation.attributes); GPUOperation operation = CreateElementwise(gpu_info, op_def, op_type, attr); *gpu_op = absl::make_unique<GPUOperation>(std::move(operation)); return absl::OkStatus(); } return absl::UnimplementedError(absl::StrCat( "No support of ", node.operation.type, " with this parameters")); } case OperationType::REDUCE_MAXIMUM: case OperationType::REDUCE_MINIMUM: case OperationType::REDUCE_PRODUCT: case OperationType::REDUCE_SUM: { auto attr = absl::any_cast<ReduceAttributes>(node.operation.attributes); *gpu_op = SelectReduce(attr.dims, inputs[0]->tensor.shape, op_type, op_def, gpu_info); return absl::OkStatus(); } default: return SelectDefault(gpu_info, op_def, hints, inputs, outputs, node, gpu_subgraph); } } } // namespace gpu } // namespace tflite
43.532508
91
0.643446
[ "shape", "vector" ]
33fdf5eb5efdb4472d2c0fc1d54bebe6d7a3d028
14,582
cpp
C++
lib/Module/KModule.cpp
sysrel/SIFT
32a952c9b5bcf576bbd91c6a7510182b6cb94748
[ "Apache-2.0" ]
null
null
null
lib/Module/KModule.cpp
sysrel/SIFT
32a952c9b5bcf576bbd91c6a7510182b6cb94748
[ "Apache-2.0" ]
null
null
null
lib/Module/KModule.cpp
sysrel/SIFT
32a952c9b5bcf576bbd91c6a7510182b6cb94748
[ "Apache-2.0" ]
null
null
null
//===-- KModule.cpp -------------------------------------------------------===// // // The KLEE Symbolic Virtual Machine // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "KModule" #include "klee/Internal/Module/KModule.h" #include "klee/Internal/Support/ErrorHandling.h" #include "Passes.h" #include "klee/Config/Version.h" #include "klee/Interpreter.h" #include "klee/Internal/Module/Cell.h" #include "klee/Internal/Module/KInstruction.h" #include "klee/Internal/Module/InstructionInfoTable.h" #include "klee/Internal/Support/Debug.h" #include "klee/Internal/Support/ModuleUtil.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/ValueSymbolTable.h" #include "llvm/IR/DataLayout.h" #if LLVM_VERSION_CODE < LLVM_VERSION(3, 5) #include "llvm/Support/CallSite.h" #else #include "llvm/IR/CallSite.h" #endif #include "klee/Internal/Module/LLVMPassManager.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_os_ostream.h" #include "llvm/Support/Path.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/Cloning.h" #include <sstream> using namespace llvm; using namespace klee; namespace { enum SwitchImplType { eSwitchTypeSimple, eSwitchTypeLLVM, eSwitchTypeInternal }; cl::opt<bool> OutputSource("output-source", cl::desc("Write the assembly for the final transformed source"), cl::init(true)); cl::opt<bool> OutputModule("output-module", cl::desc("Write the bitcode for the final transformed module"), cl::init(false)); cl::opt<SwitchImplType> SwitchType("switch-type", cl::desc("Select the implementation of switch"), cl::values(clEnumValN(eSwitchTypeSimple, "simple", "lower to ordered branches"), clEnumValN(eSwitchTypeLLVM, "llvm", "lower using LLVM"), clEnumValN(eSwitchTypeInternal, "internal", "execute switch internally") KLEE_LLVM_CL_VAL_END), cl::init(eSwitchTypeInternal)); cl::opt<bool> DebugPrintEscapingFunctions("debug-print-escaping-functions", cl::desc("Print functions whose address is taken.")); } KModule::KModule(Module *_module) : module(_module), targetData(new DataLayout(module)), infos(0), constantTable(0) { } KModule::~KModule() { delete[] constantTable; delete infos; for (std::vector<KFunction*>::iterator it = functions.begin(), ie = functions.end(); it != ie; ++it) delete *it; for (std::map<const llvm::Constant*, KConstant*>::iterator it=constantMap.begin(), itE=constantMap.end(); it!=itE;++it) delete it->second; delete targetData; delete module; } /***/ namespace llvm { extern void Optimize(Module *, const std::string &EntryPoint); } // what a hack static Function *getStubFunctionForCtorList(Module *m, GlobalVariable *gv, std::string name) { assert(!gv->isDeclaration() && !gv->hasInternalLinkage() && "do not support old LLVM style constructor/destructor lists"); std::vector<Type *> nullary; Function *fn = Function::Create(FunctionType::get(Type::getVoidTy(m->getContext()), nullary, false), GlobalVariable::InternalLinkage, name, m); BasicBlock *bb = BasicBlock::Create(m->getContext(), "entry", fn); // From lli: // Should be an array of '{ int, void ()* }' structs. The first value is // the init priority, which we ignore. ConstantArray *arr = dyn_cast<ConstantArray>(gv->getInitializer()); if (arr) { for (unsigned i=0; i<arr->getNumOperands(); i++) { ConstantStruct *cs = cast<ConstantStruct>(arr->getOperand(i)); #if LLVM_VERSION_CODE >= LLVM_VERSION(3, 5) // There is a third *optional* element in global_ctor elements (``i8 // @data``). assert((cs->getNumOperands() == 2 || cs->getNumOperands() == 3) && "unexpected element in ctor initializer list"); #else assert(cs->getNumOperands()==2 && "unexpected element in ctor initializer list"); #endif Constant *fp = cs->getOperand(1); if (!fp->isNullValue()) { if (llvm::ConstantExpr *ce = dyn_cast<llvm::ConstantExpr>(fp)) fp = ce->getOperand(0); if (Function *f = dyn_cast<Function>(fp)) { CallInst::Create(f, "", bb); } else { assert(0 && "unable to get function pointer from ctor initializer list"); } } } } ReturnInst::Create(m->getContext(), bb); return fn; } static void injectStaticConstructorsAndDestructors(Module *m) { GlobalVariable *ctors = m->getNamedGlobal("llvm.global_ctors"); GlobalVariable *dtors = m->getNamedGlobal("llvm.global_dtors"); if (ctors || dtors) { Function *mainFn = m->getFunction("main"); if (!mainFn) klee_error("Could not find main() function."); if (ctors) CallInst::Create(getStubFunctionForCtorList(m, ctors, "klee.ctor_stub"), "", &*(mainFn->begin()->begin())); if (dtors) { Function *dtorStub = getStubFunctionForCtorList(m, dtors, "klee.dtor_stub"); for (Function::iterator it = mainFn->begin(), ie = mainFn->end(); it != ie; ++it) { if (isa<ReturnInst>(it->getTerminator())) CallInst::Create(dtorStub, "", it->getTerminator()); } } } } void KModule::addInternalFunction(const char* functionName){ Function* internalFunction = module->getFunction(functionName); if (!internalFunction) { KLEE_DEBUG(klee_warning( "Failed to add internal function %s. Not found.", functionName)); return ; } KLEE_DEBUG(klee_message("Added function %s.",functionName)); internalFunctions.insert(internalFunction); } void KModule::prepare(const Interpreter::ModuleOptions &opts, InterpreterHandler *ih) { // Inject checks prior to optimization... we also perform the // invariant transformations that we will end up doing later so that // optimize is seeing what is as close as possible to the final // module. LegacyLLVMPassManagerTy pm; pm.add(new RaiseAsmPass()); // This pass will scalarize as much code as possible so that the Executor // does not need to handle operands of vector type for most instructions // other than InsertElementInst and ExtractElementInst. // // NOTE: Must come before division/overshift checks because those passes // don't know how to handle vector instructions. pm.add(createScalarizerPass()); if (opts.CheckDivZero) pm.add(new DivCheckPass()); if (opts.CheckOvershift) pm.add(new OvershiftCheckPass()); pm.add(new IntrinsicCleanerPass(*targetData)); pm.run(*module); if (opts.Optimize) Optimize(module, opts.EntryPoint); // FIXME: Missing force import for various math functions. // FIXME: Find a way that we can test programs without requiring // this to be linked in, it makes low level debugging much more // annoying. SmallString<128> LibPath(opts.LibraryDir); llvm::sys::path::append(LibPath, "kleeRuntimeIntrinsic.bc" ); module = linkWithLibrary(module, LibPath.str()); // Add internal functions which are not used to check if instructions // have been already visited if (opts.CheckDivZero) addInternalFunction("klee_div_zero_check"); if (opts.CheckOvershift) addInternalFunction("klee_overshift_check"); // Needs to happen after linking (since ctors/dtors can be modified) // and optimization (since global optimization can rewrite lists). injectStaticConstructorsAndDestructors(module); // Finally, run the passes that maintain invariants we expect during // interpretation. We run the intrinsic cleaner just in case we // linked in something with intrinsics but any external calls are // going to be unresolved. We really need to handle the intrinsics // directly I think? LegacyLLVMPassManagerTy pm3; pm3.add(createCFGSimplificationPass()); switch(SwitchType) { case eSwitchTypeInternal: break; case eSwitchTypeSimple: pm3.add(new LowerSwitchPass()); break; case eSwitchTypeLLVM: pm3.add(createLowerSwitchPass()); break; default: klee_error("invalid --switch-type"); } InstructionOperandTypeCheckPass *operandTypeCheckPass = new InstructionOperandTypeCheckPass(); pm3.add(new IntrinsicCleanerPass(*targetData)); pm3.add(new PhiCleanerPass()); pm3.add(operandTypeCheckPass); pm3.run(*module); // Enforce the operand type invariants that the Executor expects. This // implicitly depends on the "Scalarizer" pass to be run in order to succeed // in the presence of vector instructions. if (!operandTypeCheckPass->checkPassed()) { klee_error("Unexpected instruction operand types detected"); } if (OutputSource) { std::unique_ptr<llvm::raw_fd_ostream> os(ih->openOutputFile("assembly.ll")); assert(os && !os->has_error() && "unable to open source output"); *os << *module; } if (OutputModule) { llvm::raw_fd_ostream *f = ih->openOutputFile("final.bc"); WriteBitcodeToFile(module, *f); delete f; } /* Build shadow structures */ infos = new InstructionInfoTable(module); for (Module::iterator it = module->begin(), ie = module->end(); it != ie; ++it) { if (it->isDeclaration()) continue; Function *fn = &*it; KFunction *kf = new KFunction(fn, this); for (unsigned i=0; i<kf->numInstructions; ++i) { KInstruction *ki = kf->instructions[i]; ki->info = &infos->getInfo(ki->inst); } functions.push_back(kf); functionMap.insert(std::make_pair(fn, kf)); } /* Compute various interesting properties */ for (std::vector<KFunction*>::iterator it = functions.begin(), ie = functions.end(); it != ie; ++it) { KFunction *kf = *it; if (functionEscapes(kf->function)) escapingFunctions.insert(kf->function); } if (DebugPrintEscapingFunctions && !escapingFunctions.empty()) { llvm::errs() << "KLEE: escaping functions: ["; for (std::set<Function*>::iterator it = escapingFunctions.begin(), ie = escapingFunctions.end(); it != ie; ++it) { llvm::errs() << (*it)->getName() << ", "; } llvm::errs() << "]\n"; } } KConstant* KModule::getKConstant(const Constant *c) { std::map<const llvm::Constant*, KConstant*>::iterator it = constantMap.find(c); if (it != constantMap.end()) return it->second; return NULL; } unsigned KModule::getConstantID(Constant *c, KInstruction* ki) { KConstant *kc = getKConstant(c); if (kc) return kc->id; unsigned id = constants.size(); kc = new KConstant(c, id, ki); constantMap.insert(std::make_pair(c, kc)); constants.push_back(c); return id; } /***/ KConstant::KConstant(llvm::Constant* _ct, unsigned _id, KInstruction* _ki) { ct = _ct; id = _id; ki = _ki; } /***/ static int getOperandNum(Value *v, std::map<Instruction*, unsigned> &registerMap, KModule *km, KInstruction *ki) { if (Instruction *inst = dyn_cast<Instruction>(v)) { return registerMap[inst]; } else if (Argument *a = dyn_cast<Argument>(v)) { return a->getArgNo(); #if LLVM_VERSION_CODE >= LLVM_VERSION(3, 6) // Metadata is no longer a Value } else if (isa<BasicBlock>(v) || isa<InlineAsm>(v)) { #else } else if (isa<BasicBlock>(v) || isa<InlineAsm>(v) || isa<MDNode>(v)) { #endif return -1; } else { assert(isa<Constant>(v)); Constant *c = cast<Constant>(v); return -(km->getConstantID(c, ki) + 2); } } KFunction::KFunction(llvm::Function *_function, KModule *km) : function(_function), numArgs(function->arg_size()), numInstructions(0), trackCoverage(true) { for (llvm::Function::iterator bbit = function->begin(), bbie = function->end(); bbit != bbie; ++bbit) { BasicBlock *bb = &*bbit; basicBlockEntry[bb] = numInstructions; numInstructions += bb->size(); } instructions = new KInstruction*[numInstructions]; std::map<Instruction*, unsigned> registerMap; // The first arg_size() registers are reserved for formals. unsigned rnum = numArgs; for (llvm::Function::iterator bbit = function->begin(), bbie = function->end(); bbit != bbie; ++bbit) { for (llvm::BasicBlock::iterator it = bbit->begin(), ie = bbit->end(); it != ie; ++it) registerMap[&*it] = rnum++; } numRegisters = rnum; //llvm::errs() << "numRegisters=" << numRegisters << " for function " << _function->getName() << "\n"; unsigned i = 0; for (llvm::Function::iterator bbit = function->begin(), bbie = function->end(); bbit != bbie; ++bbit) { for (llvm::BasicBlock::iterator it = bbit->begin(), ie = bbit->end(); it != ie; ++it) { KInstruction *ki; switch(it->getOpcode()) { case Instruction::GetElementPtr: case Instruction::InsertValue: case Instruction::ExtractValue: ki = new KGEPInstruction(); break; default: ki = new KInstruction(); break; } Instruction *inst = &*it; ki->inst = inst; ki->dest = registerMap[inst]; if (isa<CallInst>(it) || isa<InvokeInst>(it)) { CallSite cs(inst); unsigned numArgs = cs.arg_size(); ki->operands = new int[numArgs+1]; ki->operands[0] = getOperandNum(cs.getCalledValue(), registerMap, km, ki); for (unsigned j=0; j<numArgs; j++) { Value *v = cs.getArgument(j); ki->operands[j+1] = getOperandNum(v, registerMap, km, ki); } } else { unsigned numOperands = it->getNumOperands(); ki->operands = new int[numOperands]; for (unsigned j=0; j<numOperands; j++) { Value *v = it->getOperand(j); ki->operands[j] = getOperandNum(v, registerMap, km, ki); } } instructions[i++] = ki; } } } KFunction::~KFunction() { for (unsigned i=0; i<numInstructions; ++i) delete instructions[i]; delete[] instructions; }
32.189845
104
0.632286
[ "vector" ]
d50034c21a0f1d173e610fb42c12fcbc41e299c1
1,948
cpp
C++
4. Алгоритмы на графах/6. Открытки и конверты #753/[OK]230761.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
19
2018-05-19T16:37:14.000Z
2022-03-23T20:13:43.000Z
4. Алгоритмы на графах/6. Открытки и конверты #753/[OK]230761.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
6
2020-05-07T21:06:48.000Z
2020-06-05T17:52:57.000Z
4. Алгоритмы на графах/6. Открытки и конверты #753/[OK]230761.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
31
2019-03-01T21:41:38.000Z
2022-03-27T17:56:39.000Z
#include <iostream> #include <fstream> #include <cmath> #include <vector> using namespace std; struct card { long double a; long double b; }; struct cover { long double a; long double b; }; int max; int n; card *aCard; cover *aCover; vector<vector<int>> cac; vector<int> met; vector<char> visit; bool kun(int v) { if (visit[v]) return false; visit[v] = true; for (int i = 0; i < cac[v].size(); ++i) { int to = cac[v][i]; if (met[to] == -1 || kun(met[to])) { met[to] = v; return true; } } return false; } bool cardInCover(int iCover, int iCard) { long double a, b, A, B; if (aCover[iCover].a >= aCover[iCover].b) { B = aCover[iCover].a; A = aCover[iCover].b; } else { B = aCover[iCover].b; A = aCover[iCover].a; } if (aCard[iCard].a >= aCard[iCard].b) { b = aCard[iCard].a; a = aCard[iCard].b; } else { b = aCard[iCard].b; a = aCard[iCard].a; } if (a <= A && b <= B) return true; if (sqrt(a*a + b*b) > sqrt(A*A + B*B)) return false; if (A*B < a*b) return false; long double ss, p, q; ss = a*a+b*b; p = sqrt(ss - B*B); q = sqrt(ss - A*A); return A*B - p * q >= a*b * 2; } int main() { fstream f("input.in"); f >> n; aCard = new card[n]; aCover = new cover[n]; for (int i = 0;i < n;i++) { f >> aCard[i].a >> aCard[i].b; } for (int i = 0;i < n;i++) f >> aCover[i].a >> aCover[i].b; f.close(); vector<int> temp; cac.assign(n, temp); for (int iCard = 0; iCard < n; iCard++) { for (int iCover = 0; iCover < n; iCover++) { if (cardInCover(iCover, iCard)) { cac[iCover].push_back(iCard); } } } max = 0; met.assign(n, -1); for (int v = 0; v<n; ++v) { visit.assign(n, false); if (kun(v)) max++; } ofstream of("output.out"); if (max == n) of << "YES"; else of << "NO" << endl << max; of.close(); return 0; }
16.508475
47
0.508727
[ "vector" ]
d50907f971ebc96082414f48803d4bede3b34988
5,459
cpp
C++
Game/graphics/skeletalstorage.cpp
okkindel/OpenGothic
0055d51d4c96ff56fd330378b1c1a90c365d1316
[ "MIT" ]
null
null
null
Game/graphics/skeletalstorage.cpp
okkindel/OpenGothic
0055d51d4c96ff56fd330378b1c1a90c365d1316
[ "MIT" ]
null
null
null
Game/graphics/skeletalstorage.cpp
okkindel/OpenGothic
0055d51d4c96ff56fd330378b1c1a90c365d1316
[ "MIT" ]
null
null
null
#include "skeletalstorage.h" using namespace Tempest; struct SkeletalStorage::Impl { virtual ~Impl() = default; virtual size_t alloc(size_t bonesCount) = 0; virtual void free (const size_t objId, const size_t bonesCount) = 0; virtual void bind(Uniforms& ubo, uint8_t bind, uint8_t fId, size_t id) = 0; virtual bool commitUbo(Tempest::Device &device, uint8_t fId) = 0; virtual Matrix4x4* get(size_t id) = 0; virtual void reserve(size_t n) = 0; void markAsChanged(size_t/*elt*/) { for(auto& i:pf) i.uboChanged=true; } struct PerFrame final { std::atomic_bool uboChanged{false}; // invalidate ubo array }; PerFrame pf[Resources::MaxFramesInFlight]; }; template<size_t BlkSz> struct SkeletalStorage::FreeList<Resources::MAX_NUM_SKELETAL_NODES,BlkSz> { FreeList(){ freeList.reserve(2); } size_t alloc(size_t /*bonesCount*/) { if(freeList.size()>0){ size_t id=freeList.back(); freeList.pop_back(); return id; } return size_t(-1); } void free(const size_t objId, const size_t /*bonesCount*/) { freeList.push_back(objId); } size_t blockCount(const size_t /*bonesCount*/) const { return Resources::MAX_NUM_SKELETAL_NODES/BlkSz; } std::vector<size_t> freeList; }; template<size_t sz, size_t BlkSz> struct SkeletalStorage::FreeList : FreeList<sz*2,BlkSz> { FreeList(){ freeList.reserve(2); } size_t alloc(size_t bonesCount) { if(bonesCount>sz) return FreeList<sz*2,BlkSz>::alloc(bonesCount); if(freeList.size()>0){ size_t id=freeList.back(); freeList.pop_back(); return id; } // size_t ret = FreeList<sz*2,BlkSz>::alloc(bonesCount); // if(ret!=size_t(-1)) // freeList.push_back(ret+sz/BlkSz); return size_t(-1); } void free(const size_t objId, const size_t bonesCount) { if(bonesCount>sz) return FreeList<sz*2,BlkSz>::free(objId,bonesCount); freeList.push_back(objId); } size_t blockCount(const size_t bonesCount) const { if(bonesCount>sz) return FreeList<sz*2,BlkSz>::blockCount(bonesCount); return sz/BlkSz; } std::vector<size_t> freeList; }; template<size_t BlkSz> struct SkeletalStorage::TImpl : Impl { struct Block { Tempest::Matrix4x4 mat[BlkSz]; }; enum { // do padding in the end, to make shader access to a valid mat4[MAX_NUM_SKELETAL_NODES] array Padding = Resources::MAX_NUM_SKELETAL_NODES-BlkSz }; TImpl() { obj.resize(Padding); } size_t alloc(size_t bonesCount) override { size_t ret = freeList.alloc(bonesCount); if(ret!=size_t(-1)) return ret; markAsChanged(ret); ret = obj.size()-Padding; const size_t increment = freeList.blockCount(bonesCount); obj.resize(obj.size()+increment); return ret; } void free(const size_t objId, const size_t bonesCount) override { freeList.free(objId, bonesCount); auto m = &obj[objId]; std::memset(m,0,sizeof(Matrix4x4)*bonesCount); } void bind(Uniforms& ubo, uint8_t bind, uint8_t fId, size_t id) override { auto& v = uboData[fId]; ubo.set(bind,v,id); } bool commitUbo(Tempest::Device &device, uint8_t fId) override { auto& frame = pf[fId]; if(!frame.uboChanged) return false; const bool realloc = uboData[fId].size()!=obj.size(); if(realloc) uboData[fId] = device.ubo<Block>(obj.data(),obj.size()); else uboData[fId].update(obj.data(),0,obj.size()); frame.uboChanged = false; return realloc; } Matrix4x4* get(size_t id) override { return obj[id].mat; } void reserve(size_t n) override { obj.reserve(n); } FreeList<BlkSz,BlkSz> freeList; std::vector<Block> obj; Tempest::UniformBuffer<Block> uboData[Resources::MaxFramesInFlight]; }; SkeletalStorage::SkeletalStorage(Tempest::Device& device) { if(tryInit<Resources::MAX_NUM_SKELETAL_NODES/16>(device)) return; if(tryInit<Resources::MAX_NUM_SKELETAL_NODES/8>(device)) return; if(tryInit<Resources::MAX_NUM_SKELETAL_NODES/4>(device)) return; if(tryInit<Resources::MAX_NUM_SKELETAL_NODES/2>(device)) return; blockSize = Resources::MAX_NUM_SKELETAL_NODES; impl.reset(new TImpl<Resources::MAX_NUM_SKELETAL_NODES>()); } SkeletalStorage::~SkeletalStorage() { } template<size_t sz> bool SkeletalStorage::tryInit(Tempest::Device& device) { const auto align = device.properties().ubo.offsetAlign; if(Resources::MAX_NUM_SKELETAL_NODES%sz==0 && (sizeof(Matrix4x4)*sz)%align==0) { blockSize = sz; impl.reset(new TImpl<sz>()); return true; } return false; } size_t SkeletalStorage::alloc(size_t bonesCount) { return impl->alloc(bonesCount); } void SkeletalStorage::free(const size_t objId, size_t bonesCount) { impl->free(objId,bonesCount); } void SkeletalStorage::bind(Uniforms& ubo, uint8_t bind, uint8_t fId, size_t id, size_t /*boneCnt*/) { impl->bind(ubo,bind,fId,id); } bool SkeletalStorage::commitUbo(Tempest::Device& device, uint8_t fId) { if(!impl->commitUbo(device,fId)) return false; updatesTotal++; return true; } void SkeletalStorage::markAsChanged(size_t elt) { impl->markAsChanged(elt); } Matrix4x4& SkeletalStorage::element(size_t i) { return *impl->get(i); } void SkeletalStorage::reserve(size_t sz) { impl->reserve(sz*Resources::MAX_NUM_SKELETAL_NODES/blockSize); }
26.629268
101
0.671552
[ "vector" ]
d5094e5a4c38c321d6724652530a9b6861b32506
8,088
cpp
C++
thirdparty/GeometricTools/WildMagic5/SampleGraphics/RenderToTexture/RenderToTexture.cpp
SoMa-Project/vision
ea8199d98edc363b2be79baa7c691da3a5a6cc86
[ "BSD-2-Clause-FreeBSD" ]
1
2020-07-24T23:40:01.000Z
2020-07-24T23:40:01.000Z
thirdparty/GeometricTools/WildMagic5/SampleGraphics/RenderToTexture/RenderToTexture.cpp
SoMa-Project/vision
ea8199d98edc363b2be79baa7c691da3a5a6cc86
[ "BSD-2-Clause-FreeBSD" ]
4
2020-05-19T18:14:33.000Z
2021-03-19T15:53:43.000Z
thirdparty/GeometricTools/WildMagic5/SampleGraphics/RenderToTexture/RenderToTexture.cpp
SoMa-Project/vision
ea8199d98edc363b2be79baa7c691da3a5a6cc86
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
// Geometric Tools, LLC // Copyright (c) 1998-2014 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.0 (2010/01/01) #include "RenderToTexture.h" WM5_WINDOW_APPLICATION(RenderToTexture); //---------------------------------------------------------------------------- RenderToTexture::RenderToTexture () : WindowApplication3("SampleGraphics/RenderToTexture", 0, 0, 640, 480, Float4(0.5f, 0.5f, 0.5f, 1.0f)), mClearWhite(1.0f, 1.0f, 1.0f, 1.0f), mClearGray(0.5f, 0.5f, 0.5f, 1.0f), mTextColor(0.0f, 0.0f, 0.0f, 1.0f) { } //---------------------------------------------------------------------------- bool RenderToTexture::OnInitialize () { if (!WindowApplication3::OnInitialize()) { return false; } CreateScene(); // Center-and-fit for camera viewing. mScene->Update(); mTrnNode->LocalTransform.SetTranslate(-mScene->WorldBound.GetCenter()); mCamera->SetFrustum(60.0f, GetAspectRatio(), 1.0f, 1000.0f); AVector camDVector(0.0f, 1.0f, 0.0f); AVector camUVector(0.0f, 0.0f, 1.0f); AVector camRVector = camDVector.Cross(camUVector); APoint camPosition = APoint::ORIGIN - 300.0f*camDVector; mCamera->SetFrame(camPosition, camDVector, camUVector, camRVector); // Initial update of objects. mScene->Update(); // Initial culling of scene. mCuller.SetCamera(mCamera); mCuller.ComputeVisibleSet(mScene); InitializeCameraMotion(0.1f, 0.001f); InitializeObjectMotion(mScene); return true; } //---------------------------------------------------------------------------- void RenderToTexture::OnTerminate () { mScene = 0; mTrnNode = 0; mWireState = 0; mScreenCamera = 0; mRenderTarget = 0; mScreenPolygon = 0; WindowApplication3::OnTerminate(); } //---------------------------------------------------------------------------- void RenderToTexture::OnIdle () { MeasureTime(); if (MoveCamera()) { mCuller.ComputeVisibleSet(mScene); } if (MoveObject()) { mScene->Update(); mCuller.ComputeVisibleSet(mScene); } if (mRenderer->PreDraw()) { // Draw the scene to a render target. mRenderer->Enable(mRenderTarget); mRenderer->SetClearColor(mClearWhite); mRenderer->ClearBuffers(); mRenderer->Draw(mCuller.GetVisibleSet()); mRenderer->Disable(mRenderTarget); // Draw the scene to the main window and also to a regular screen // polygon, placed in the lower-left corner of the main window. mRenderer->SetClearColor(mClearGray); mRenderer->ClearBuffers(); mRenderer->Draw(mCuller.GetVisibleSet()); mRenderer->SetCamera(mScreenCamera); mRenderer->Draw(mScreenPolygon); mRenderer->SetCamera(mCamera); DrawFrameRate(8, 16, mTextColor); mRenderer->PostDraw(); mRenderer->DisplayColorBuffer(); } UpdateFrameCount(); } //---------------------------------------------------------------------------- bool RenderToTexture::OnKeyDown (unsigned char key, int x, int y) { if (WindowApplication3::OnKeyDown(key, x, y)) { return true; } switch (key) { case 'w': case 'W': mWireState->Enabled = !mWireState->Enabled; return true; } return false; } //---------------------------------------------------------------------------- void RenderToTexture::CreateScene () { // Create the root of the scene. mScene = new0 Node(); mTrnNode = new0 Node(); mScene->AttachChild(mTrnNode); mWireState = new0 WireState(); mRenderer->SetOverrideWireState(mWireState); // Create a screen-space camera to use with the render target. mScreenCamera = ScreenTarget::CreateCamera(); // Create a screen polygon to use with the render target. VertexFormat* vformat = VertexFormat::Create(2, VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0, VertexFormat::AU_TEXCOORD, VertexFormat::AT_FLOAT2, 0); const int rtWidth = 256, rtHeight = 256; mScreenPolygon = ScreenTarget::CreateRectangle(vformat, rtWidth, rtHeight, 0.0f, 0.2f, 0.0f, 0.2f, 0.0f); // Create the render target. //Texture::Format tformat = Texture::TF_A8B8G8R8; // DX9 fails Texture::Format tformat = Texture::TF_A8R8G8B8; //Texture::Format tformat = Texture::TF_A16B16G16R16; //Texture::Format tformat = Texture::TF_A16B16G16R16F; //Texture::Format tformat = Texture::TF_A32B32G32R32F; mRenderTarget = new0 RenderTarget(1, tformat, rtWidth, rtHeight, false, false); // Attach the render target texture to the screen polygon mesh. mScreenPolygon->SetEffectInstance(Texture2DEffect::CreateUniqueInstance( mRenderTarget->GetColorTexture(0), Shader::SF_LINEAR, Shader::SC_CLAMP_EDGE, Shader::SC_CLAMP_EDGE)); // Load the face model and use multitexturing. #ifdef WM5_LITTLE_ENDIAN std::string path = Environment::GetPathR("FacePN.wmof"); #else std::string path = Environment::GetPathR("FacePN.be.wmof"); #endif InStream inStream; inStream.Load(path); TriMeshPtr mesh = DynamicCast<TriMesh>(inStream.GetObjectAt(0)); // Create texture coordinates for the face. Based on knowledge of the // mesh, the (x,z) values of the model-space vertices may be mapped to // (s,t) in [0,1]^2. VertexBufferAccessor vba0(mesh); const int numVertices = vba0.GetNumVertices(); float xmin = Mathf::MAX_REAL, xmax = -Mathf::MAX_REAL; float zmin = Mathf::MAX_REAL, zmax = -Mathf::MAX_REAL; int i; for (i = 1; i < numVertices; ++i) { Float3 position = vba0.Position<Float3>(i); float x = position[0]; if (x < xmin) { xmin = x; } if (x > xmax) { xmax = x; } float z = position[2]; if (z < zmin) { zmin = z; } if (z > zmax) { zmax = z; } } float invXRange = 1.0f/(xmax - xmin); float invZRange = 1.0f/(zmax - zmin); // Strip out the normal vectors, because there is no lighting in this // sample. Add in two texture coordinate channels for a multiplicative // texture effect. vformat = VertexFormat::Create(3, VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0, VertexFormat::AU_TEXCOORD, VertexFormat::AT_FLOAT2, 0, VertexFormat::AU_TEXCOORD, VertexFormat::AT_FLOAT2, 1); int vstride = vformat->GetStride(); VertexBuffer* vbuffer = new0 VertexBuffer(numVertices, vstride); VertexBufferAccessor vba1(vformat, vbuffer); for (i = 0; i < numVertices; ++i) { Float3 position = vba0.Position<Float3>(i); Float2 tcoord( (position[0] - xmin)*invXRange, (position[2] - zmin)*invZRange); vba1.Position<Float3>(i) = position; vba1.TCoord<Float2>(0, i) = tcoord; vba1.TCoord<Float2>(1, i) = tcoord; } mesh->SetVertexFormat(vformat); mesh->SetVertexBuffer(vbuffer); path = Environment::GetPathR("Leaf.wmtf"); Texture2D* texture0 = Texture2D::LoadWMTF(path); path = Environment::GetPathR("Water.wmtf"); Texture2D* texture1 = Texture2D::LoadWMTF(path); VisualEffectInstance* instance = Texture2AddEffect::CreateUniqueInstance( texture0, Shader::SF_LINEAR, Shader::SC_CLAMP_EDGE, Shader::SC_CLAMP_EDGE, texture1, Shader::SF_LINEAR, Shader::SC_CLAMP_EDGE, Shader::SC_CLAMP_EDGE); mesh->SetEffectInstance(instance); mTrnNode->AttachChild(mesh); } //----------------------------------------------------------------------------
33.147541
79
0.581231
[ "mesh", "render", "model" ]
d5096d7a0b57d3e1b4accb4086de46ada6560825
8,938
cpp
C++
Gems/Atom/Feature/Common/Code/Source/Material/MaterialConverterSystemComponent.cpp
whywhywhyw/o3de
8e09f66799d4c8f188d45861d821e8656a554cb1
[ "Apache-2.0", "MIT" ]
1
2022-01-21T03:51:42.000Z
2022-01-21T03:51:42.000Z
Gems/Atom/Feature/Common/Code/Source/Material/MaterialConverterSystemComponent.cpp
whywhywhyw/o3de
8e09f66799d4c8f188d45861d821e8656a554cb1
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/Atom/Feature/Common/Code/Source/Material/MaterialConverterSystemComponent.cpp
whywhywhyw/o3de
8e09f66799d4c8f188d45861d821e8656a554cb1
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "MaterialConverterSystemComponent.h" #include <AssetBuilderSDK/AssetBuilderSDK.h> #include <AzCore/Math/Color.h> #include <AzCore/Serialization/EditContext.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Settings/SettingsRegistry.h> #include <AzToolsFramework/API/EditorAssetSystemAPI.h> #include <Atom/RPI.Reflect/Material/MaterialAsset.h> namespace AZ { namespace Render { void MaterialConverterSettings::Reflect(AZ::ReflectContext* context) { if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) { serializeContext->Class<MaterialConverterSettings>() ->Version(2) ->Field("Enable", &MaterialConverterSettings::m_enable) ->Field("DefaultMaterial", &MaterialConverterSettings::m_defaultMaterial); } } void MaterialConverterSystemComponent::Reflect(AZ::ReflectContext* context) { if (auto* serialize = azrtti_cast<SerializeContext*>(context)) { serialize->Class<MaterialConverterSystemComponent, Component>() ->Version(3) ->Attribute(Edit::Attributes::SystemComponentTags, AZStd::vector<Crc32>({ AssetBuilderSDK::ComponentTags::AssetBuilder })); } MaterialConverterSettings::Reflect(context); } void MaterialConverterSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services) { services.emplace_back(AZ_CRC_CE("FingerprintModification")); } void MaterialConverterSystemComponent::Activate() { if (auto* settingsRegistry = AZ::SettingsRegistry::Get()) { settingsRegistry->GetObject(m_settings, "/O3DE/SceneAPI/MaterialConverter"); } RPI::MaterialConverterBus::Handler::BusConnect(); } void MaterialConverterSystemComponent::Deactivate() { RPI::MaterialConverterBus::Handler::BusDisconnect(); } bool MaterialConverterSystemComponent::IsEnabled() const { return m_settings.m_enable; } bool MaterialConverterSystemComponent::ConvertMaterial( const AZ::SceneAPI::DataTypes::IMaterialData& materialData, RPI::MaterialSourceData& sourceData) { using namespace AZ::RPI; if (!m_settings.m_enable) { return false; } // The source data for generating material asset sourceData.m_materialType = GetMaterialTypePath(); auto handleTexture = [&materialData, &sourceData]( const char* propertyTextureGroup, SceneAPI::DataTypes::IMaterialData::TextureMapType textureType) { MaterialSourceData::PropertyMap& properties = sourceData.m_properties[propertyTextureGroup]; const AZStd::string& texturePath = materialData.GetTexture(textureType); // Check to see if the image asset exists. If not, skip this texture map and just disable it. bool assetFound = false; if (!texturePath.empty()) { using namespace AzToolsFramework; AZ::Data::AssetInfo sourceInfo; AZStd::string watchFolder; AssetSystemRequestBus::BroadcastResult( assetFound, &AssetSystem::AssetSystemRequest::GetSourceInfoBySourcePath, texturePath.c_str(), sourceInfo, watchFolder); } if (assetFound) { properties["textureMap"].m_value = texturePath; } else if (!texturePath.empty()) { AZ_Warning("AtomFeatureCommon", false, "Could not find asset '%s' for '%s'", texturePath.c_str(), propertyTextureGroup); } }; // If PBR material properties aren't in use, fall back to legacy properties. Don't do that if some PBR material properties are set, though. bool anyPBRInUse = false; handleTexture("specularF0", SceneAPI::DataTypes::IMaterialData::TextureMapType::Specular); handleTexture("normal", SceneAPI::DataTypes::IMaterialData::TextureMapType::Normal); AZStd::optional<bool> useColorMap = materialData.GetUseColorMap(); // If the useColorMap property exists, this is a PBR material and the color should be set to baseColor. if (useColorMap.has_value()) { anyPBRInUse = true; handleTexture("baseColor", SceneAPI::DataTypes::IMaterialData::TextureMapType::BaseColor); sourceData.m_properties["baseColor"]["textureBlendMode"].m_value = AZStd::string("Lerp"); } else { // If it doesn't have the useColorMap property, then it's a non-PBR material and the baseColor // texture needs to be set to the diffuse texture. handleTexture("baseColor", SceneAPI::DataTypes::IMaterialData::TextureMapType::Diffuse); } auto toColor = [](const AZ::Vector3& v) { return AZ::Color::CreateFromVector3AndFloat(v, 1.0f); }; AZStd::optional<AZ::Vector3> baseColor = materialData.GetBaseColor(); if (baseColor.has_value()) { anyPBRInUse = true; sourceData.m_properties["baseColor"]["color"].m_value = toColor(baseColor.value()); } sourceData.m_properties["opacity"]["factor"].m_value = materialData.GetOpacity(); auto applyOptionalPropertiesFunc = [&sourceData, &anyPBRInUse](const auto& propertyGroup, const auto& propertyName, const auto& propertyOptional) { // Only set PBR settings if they were specifically set in the scene's data. // Otherwise, leave them unset so the data driven default properties are used. if (propertyOptional.has_value()) { anyPBRInUse = true; sourceData.m_properties[propertyGroup][propertyName].m_value = propertyOptional.value(); } }; handleTexture("metallic", SceneAPI::DataTypes::IMaterialData::TextureMapType::Metallic); applyOptionalPropertiesFunc("metallic", "factor", materialData.GetMetallicFactor()); applyOptionalPropertiesFunc("metallic", "useTexture", materialData.GetUseMetallicMap()); handleTexture("roughness", SceneAPI::DataTypes::IMaterialData::TextureMapType::Roughness); applyOptionalPropertiesFunc("roughness", "factor", materialData.GetRoughnessFactor()); applyOptionalPropertiesFunc("roughness", "useTexture", materialData.GetUseRoughnessMap()); handleTexture("emissive", SceneAPI::DataTypes::IMaterialData::TextureMapType::Emissive); sourceData.m_properties["emissive"]["color"].m_value = toColor(materialData.GetEmissiveColor()); applyOptionalPropertiesFunc("emissive", "intensity", materialData.GetEmissiveIntensity()); applyOptionalPropertiesFunc("emissive", "useTexture", materialData.GetUseEmissiveMap()); handleTexture("ambientOcclusion", SceneAPI::DataTypes::IMaterialData::TextureMapType::AmbientOcclusion); applyOptionalPropertiesFunc("ambientOcclusion", "useTexture", materialData.GetUseAOMap()); if (!anyPBRInUse) { // If it doesn't have the useColorMap property, then it's a non-PBR material and the baseColor // texture needs to be set to the diffuse color. sourceData.m_properties["baseColor"]["color"].m_value = toColor(materialData.GetDiffuseColor()); } return true; } AZStd::string MaterialConverterSystemComponent::GetMaterialTypePath() const { return "Materials/Types/StandardPBR.materialtype"; } AZStd::string MaterialConverterSystemComponent::GetDefaultMaterialPath() const { if (m_settings.m_defaultMaterial.empty()) { AZ_Error("MaterialConverterSystemComponent", m_settings.m_enable, "Material conversion is disabled but a default material not specified in registry /O3DE/SceneAPI/MaterialConverter/DefaultMaterial"); } return m_settings.m_defaultMaterial; } } }
45.602041
157
0.621951
[ "render", "vector", "3d" ]
d50d1720048e7fef1d1a051e7070fbf3cb12dde1
531
cpp
C++
test/aoj/GRL_3_B.test.cpp
atree-GitHub/competitive-library
606b444036530b698a6363b1a41cdaa90a7f9578
[ "CC0-1.0" ]
1
2022-01-25T23:03:10.000Z
2022-01-25T23:03:10.000Z
test/aoj/GRL_3_B.test.cpp
atree4728/competitive-library
1aaa4d2cf9283b9a1a3d4c7f114ff7b867ca2f8b
[ "CC0-1.0" ]
6
2021-10-06T01:17:04.000Z
2022-01-16T14:45:47.000Z
test/aoj/GRL_3_B.test.cpp
atree-GitHub/competitive-library
606b444036530b698a6363b1a41cdaa90a7f9578
[ "CC0-1.0" ]
null
null
null
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/problems/GRL_3_B" #include <iostream> #include "lib/graph/lowlink.hpp" int main() { using namespace std; size_t v, e; cin >> v >> e; vector graph(v, vector<size_t>{}); while (e--) { size_t s, t; cin >> s >> t; graph[s].push_back(t); graph[t].push_back(s); } auto bridge = Lowlink(graph).bridge; sort(begin(bridge), end(bridge)); for (const auto &[u, v]: bridge) { cout << u << " " << v << "\n"; } }
23.086957
67
0.53484
[ "vector" ]
d50f71bbe2969bf53cbc5786a8ec5edbaa7b1c07
1,437
cpp
C++
tools/pnnx/src/pass_level0.cpp
jasonZhang892/ncnn
c2fb93b6ff99045dd76aae2d41218a15df189247
[ "BSD-3-Clause" ]
2
2022-02-28T14:59:08.000Z
2022-03-13T23:55:21.000Z
tools/pnnx/src/pass_level0.cpp
jasonZhang892/ncnn
c2fb93b6ff99045dd76aae2d41218a15df189247
[ "BSD-3-Clause" ]
9
2020-03-17T13:15:18.000Z
2020-08-20T09:17:48.000Z
tools/pnnx/src/pass_level0.cpp
jasonZhang892/ncnn
c2fb93b6ff99045dd76aae2d41218a15df189247
[ "BSD-3-Clause" ]
3
2022-02-28T07:38:32.000Z
2022-03-17T18:49:28.000Z
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "pass_level0.h" #include "pass_level0/constant_unpooling.h" #include "pass_level0/inline_block.h" #include "pass_level0/shape_inference.h" namespace pnnx { void pass_level0(const torch::jit::Module& mod, std::shared_ptr<torch::jit::Graph>& g, const std::vector<at::Tensor>& input_tensors, const std::vector<at::Tensor>& input_tensors2, const std::vector<std::string>& module_operators, const std::string& ptpath, std::map<std::string, Attribute>& foldable_constants) { inline_block(g, module_operators); constant_unpooling(g); if (!input_tensors.empty()) { shape_inference(mod, g, input_tensors, input_tensors2, module_operators, ptpath, foldable_constants); } } } // namespace pnnx
39.916667
310
0.750174
[ "vector" ]
d513c83b3c846d675437f20f237ff41f2ba2ad16
3,766
hpp
C++
include/openpose/filestream/wPeopleJsonSaver.hpp
meiwanlanjun/openpose
71078eb1b7571789c7589cf6c8de1786c3227a90
[ "DOC", "MIT-CMU" ]
717
2018-10-31T16:52:42.000Z
2022-03-31T16:13:47.000Z
include/openpose/filestream/wPeopleJsonSaver.hpp
meiwanlanjun/openpose
71078eb1b7571789c7589cf6c8de1786c3227a90
[ "DOC", "MIT-CMU" ]
48
2018-11-08T12:16:43.000Z
2020-08-10T00:24:50.000Z
include/openpose/filestream/wPeopleJsonSaver.hpp
meiwanlanjun/openpose
71078eb1b7571789c7589cf6c8de1786c3227a90
[ "DOC", "MIT-CMU" ]
180
2018-10-31T18:41:33.000Z
2022-03-27T23:49:06.000Z
#ifndef OPENPOSE_FILESTREAM_W_PEOPLE_JSON_SAVER_HPP #define OPENPOSE_FILESTREAM_W_PEOPLE_JSON_SAVER_HPP #include <openpose/core/common.hpp> #include <openpose/filestream/peopleJsonSaver.hpp> #include <openpose/thread/workerConsumer.hpp> namespace op { template<typename TDatums> class WPeopleJsonSaver : public WorkerConsumer<TDatums> { public: explicit WPeopleJsonSaver(const std::shared_ptr<PeopleJsonSaver>& peopleJsonSaver); void initializationOnThread(); void workConsumer(const TDatums& tDatums); private: const std::shared_ptr<PeopleJsonSaver> spPeopleJsonSaver; DELETE_COPY(WPeopleJsonSaver); }; } // Implementation #include <openpose/utilities/pointerContainer.hpp> namespace op { template<typename TDatums> WPeopleJsonSaver<TDatums>::WPeopleJsonSaver(const std::shared_ptr<PeopleJsonSaver>& peopleJsonSaver) : spPeopleJsonSaver{peopleJsonSaver} { } template<typename TDatums> void WPeopleJsonSaver<TDatums>::initializationOnThread() { } template<typename TDatums> void WPeopleJsonSaver<TDatums>::workConsumer(const TDatums& tDatums) { try { if (checkNoNullNorEmpty(tDatums)) { // Debugging log dLog("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); // Profiling speed const auto profilerKey = Profiler::timerInit(__LINE__, __FUNCTION__, __FILE__); // Save body/face/hand keypoints to JSON file const auto& tDatumFirst = (*tDatums)[0]; const auto baseFileName = (!tDatumFirst.name.empty() ? tDatumFirst.name : std::to_string(tDatumFirst.id)) + "_keypoints"; const bool humanReadable = false; for (auto i = 0u ; i < tDatums->size() ; i++) { const auto& tDatum = (*tDatums)[i]; // const auto fileName = baseFileName; const auto fileName = baseFileName + (i != 0 ? "_" + std::to_string(i) : ""); const std::vector<std::pair<Array<float>, std::string>> keypointVector{ // 2D std::make_pair(tDatum.poseKeypoints, "pose_keypoints_2d"), std::make_pair(tDatum.faceKeypoints, "face_keypoints_2d"), std::make_pair(tDatum.handKeypoints[0], "hand_left_keypoints_2d"), std::make_pair(tDatum.handKeypoints[1], "hand_right_keypoints_2d"), // 3D std::make_pair(tDatum.poseKeypoints3D, "pose_keypoints_3d"), std::make_pair(tDatum.faceKeypoints3D, "face_keypoints_3d"), std::make_pair(tDatum.handKeypoints3D[0], "hand_left_keypoints_3d"), std::make_pair(tDatum.handKeypoints3D[1], "hand_right_keypoints_3d") }; // Save keypoints spPeopleJsonSaver->save(keypointVector, tDatum.poseCandidates, fileName, humanReadable); } // Profiling speed Profiler::timerEnd(profilerKey); Profiler::printAveragedTimeMsOnIterationX(profilerKey, __LINE__, __FUNCTION__, __FILE__); // Debugging log dLog("", Priority::Low, __LINE__, __FUNCTION__, __FILE__); } } catch (const std::exception& e) { this->stop(); error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } COMPILE_TEMPLATE_DATUM(WPeopleJsonSaver); } #endif // OPENPOSE_FILESTREAM_W_PEOPLE_JSON_SAVER_HPP
37.287129
108
0.593468
[ "vector", "3d" ]
d516e90af00cfae2423aa40d6f2d3f999e0ad637
43,313
cxx
C++
thirdparty/moab/tools/qvdual/vtkMOABUtils.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
thirdparty/moab/tools/qvdual/vtkMOABUtils.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
4
2016-11-10T15:49:51.000Z
2017-02-06T23:24:16.000Z
thirdparty/moab/tools/qvdual/vtkMOABUtils.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
#include "vtkMOABUtils.h" #include "vtkPoints.h" #include "vtkUnstructuredGrid.h" #include "vtkPropAssembly.h" #include "vtkProperty.h" #include "vtkProperty2D.h" #include "vtkActor.h" #include "vtkActor2D.h" #include "vtkActorCollection.h" #include "vtkIdList.h" #include "vtkPropCollection.h" #include "vtkObjectFactory.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkDataSetMapper.h" #include "vtkPolyDataMapper.h" #include "vtkPolyData.h" #include "vtkExtractCells.h" #include "vtkExtractGeometry.h" #include "vtkExtractPolyDataGeometry.h" #include "vtkImplicitFunction.h" #include "vtkExtractEdges.h" #include "vtkTubeFilter.h" #include "vtkGeometryFilter.h" #include "vtkLookupTable.h" #include "vtkSource.h" #include <assert.h> #include "DrawDual.hpp" #include "DualTool.hpp" #include "MBTagConventions.hpp" #define IS_BUILDING_MB #include "MBCore.hpp" // need internals to create whole-mesh handle #include "MBInternals.hpp" #undef IS_BUILDING_MB //#define RED(x) ((x > 0.5) ? 0.0 : 1.0 - 2*x) //#define BLUE(x) ((x < 0.5) ? 0.0 : 2*(x-0.5)) //#define GREEN(x) (x <= 0.5 ? 1.0 - RED(x) : 1.0 - BLUE(x)) #define RED(x) (1.0-x) #define BLUE(x) (x) #define GREEN(x) (x <= 0.5 ? 2.0*x : 2.0*(x-0.5)) int vtkMOABUtils::totalColors = 10; vtkLookupTable *vtkMOABUtils::lookupTable = NULL; const int vtkMOABUtils::vtk_cell_types[] = { 1, 3, 5, 9, 7, 10, 14, 13, 0, 12, 0, 0, 0}; //! static interface pointer, use this when accessing MOAB within vtk MBInterface *vtkMOABUtils::mbImpl = NULL; //! static interface pointer, use this when accessing MOAB within vtk DualTool *vtkMOABUtils::dualTool = NULL; //! static pointer to the renderer vtkRenderer *vtkMOABUtils::myRen = NULL; //! static pointer to the renderer vtkUnstructuredGrid *vtkMOABUtils::myUG = NULL; //! the default property vtkProperty *vtkMOABUtils::topProperty = NULL; //! the highlight property vtkProperty *vtkMOABUtils::highlightProperty = NULL; //! map between actors in the display and properties; if null, an actor //! inherits from topProperty std::map<vtkActor*, vtkProperty*> vtkMOABUtils::actorProperties; //! map between props (actor2d's and actors) and sets they represent (0 if no set, //! e.g. an extracted set) std::map<vtkProp*, MBEntityHandle> vtkMOABUtils::propSetMap; //! topmost assembly for displaying contains relationships vtkPropAssembly *vtkMOABUtils::topContainsAssy = NULL; //! topmost assembly for displaying parent/child relationships vtkPropAssembly *vtkMOABUtils::topParentAssy = NULL; //! tag indicating whether a given set is in top contains assy MBTag vtkMOABUtils::vtkTopContainsTag = 0; //! name for vtkTopContainsTag; const char *vtkMOABUtils::vtkTopContainsTagName = "__vtkTopContainsTag"; //! tag indicating whether a given set is in top parent assy MBTag vtkMOABUtils::vtkTopParentTag = 0; //! name for vtkTopParentTag; const char *vtkMOABUtils::vtkTopParentTagName = "__vtkTopParentTag"; //! tag for pointing to vtk cell representing an entity MBTag vtkMOABUtils::vtkCellTag = 0; //! name for vtkCellTag const char *vtkMOABUtils::vtkCellTagName = "__vtkCellTag"; //! tag for pointing to vtk actor for a set MBTag vtkMOABUtils::vtkSetActorTag = 0; //! name for vtkSetActorTag const char *vtkMOABUtils::vtkSetActorTagName = "__vtkSetActorTag"; //! tag for pointing to vtk prop assembly for a set MBTag vtkMOABUtils::vtkSetPropAssemblyTag = 0; //! name for vtkSetPropAssemblyTag const char *vtkMOABUtils::vtkSetPropAssemblyTagName = "__vtkSetPropAssemblyTag"; //! tag for determining whether a point has been allocated for a vertex MBTag vtkMOABUtils::vtkPointAllocatedTag = 0; //! name for vtkPointAllocatedTag const char *vtkMOABUtils::vtkPointAllocatedTagName = "__vtkPointAllocatedTag"; DrawDual *vtkMOABUtils::drawDual = NULL; vtkCallbackCommand *vtkMOABUtils::eventCallbackCommand = NULL; MBTag vtkMOABUtils::globalIdTag = 0; MBTag vtkMOABUtils::categoryTag = 0; bool vtkMOABUtils::debug = false; //vtkStandardNewMacro(vtkMOABUtils); MBErrorCode vtkMOABUtils::init(MBInterface *impl, vtkRenderer *this_ren) { if (NULL == this_ren) return MB_FAILURE; myRen = this_ren; if (NULL == impl && NULL == mbImpl) { impl = new MBCore(); vtkMOABUtils::mbImpl = impl; } if (NULL == dualTool) dualTool = new DualTool(mbImpl); MBErrorCode result = create_tags(); make_properties(); return result; } MBErrorCode vtkMOABUtils::create_tags() { MBErrorCode result; { vtkIdType def_val = -1; result = vtkMOABUtils::mbImpl->tag_get_handle(vtkCellTagName, sizeof(vtkIdType), MB_TYPE_OPAQUE, vtkCellTag, MB_TAG_DENSE|MB_TAG_CREAT, &def_val); if (MB_SUCCESS != result) return result; } { unsigned char def_val = 0x0; result = vtkMOABUtils::mbImpl->tag_get_handle(vtkTopContainsTagName, 1, MB_TYPE_BIT, vtkTopContainsTag, MB_TAG_CREAT, &def_val); if (MB_SUCCESS != result) return result; } { unsigned char def_val = 0x0; result = vtkMOABUtils::mbImpl->tag_get_handle(vtkTopParentTagName, 1, MB_TAG_BIT, vtkTopParentTag, MB_TAG_CREAT, &def_val); if (MB_SUCCESS != result) return result; } { vtkActor *def_val = NULL; result = vtkMOABUtils::mbImpl->tag_get_handle(vtkSetActorTagName, sizeof(vtkActor*), MB_TYPE_OPAQUE, vtkSetActorTag, MB_TAG_SPASRE|MB_TAG_CREAT, &def_val); if (MB_SUCCESS != result) return result; } { vtkPropAssembly *def_val = NULL; result = vtkMOABUtils::mbImpl->tag_get_handle(vtkSetPropAssemblyTagName, sizeof(vtkPropAssembly*), MB_TYPE_OPAQUE, vtkSetPropAssemblyTag, MB_TAG_SPARSE|MB_TAG_CREAT, &def_val); if (MB_SUCCESS != result) return result; } { bool def_val = false; result = vtkMOABUtils::mbImpl->tag_get_handle(vtkPointAllocatedTagName, sizeof(bool), MB_TYPE_OPAQUE, vtkPointAllocatedTag, MB_TAG_DENSE|MB_TAG_CREAT, &def_val); if (MB_SUCCESS != result) return result; } return MB_SUCCESS; } void vtkMOABUtils::make_properties() { // make top property if (NULL == topProperty) { vtkMOABUtils::topProperty = vtkProperty::New(); // need to increase use count of top property vtkMOABUtils::topProperty->Register(NULL); // want the top property to be wire frame to start with vtkMOABUtils::topProperty->SetRepresentationToWireframe(); //vtkMOABUtils::topProperty->SetColor(0.0, 1.0, 0.0); vtkMOABUtils::topProperty->SetDiffuse(1.0); vtkMOABUtils::topProperty->SetAmbient(1.0); vtkMOABUtils::topProperty->SetSpecular(1.0); //vtkMOABUtils::topProperty->SetLineWidth(2.0); //vtkMOABUtils::topProperty->SetEdgeColor(0.0, 0.0, 0.0); //vtkMOABUtils::topProperty->EdgeVisibilityOn(); } if (NULL == highlightProperty) { // make highlight property vtkMOABUtils::highlightProperty = vtkProperty::New(); // need to increase use count of highlight property vtkMOABUtils::highlightProperty->Register(NULL); // want the highlight property to be shaded and highlight color vtkMOABUtils::highlightProperty->SetRepresentationToSurface(); vtkMOABUtils::highlightProperty->SetColor(1.0, 0.67, 0.0); vtkMOABUtils::highlightProperty->SetEdgeColor(1.0, 0.67, 0.0); vtkMOABUtils::highlightProperty->SetDiffuse(1.0); vtkMOABUtils::highlightProperty->SetAmbient(1.0); vtkMOABUtils::highlightProperty->SetSpecular(1.0); //vtkMOABUtils::highlightProperty->SetLineWidth(2.0); //vtkMOABUtils::highlightProperty->SetEdgeColor(0.0, 0.0, 0.0); //vtkMOABUtils::highlightProperty->EdgeVisibilityOn(); } } void vtkMOABUtils::destroy() { if (NULL != vtkMOABUtils::mbImpl) { delete vtkMOABUtils::mbImpl; vtkMOABUtils::mbImpl = NULL; } } MBErrorCode vtkMOABUtils::make_vertex_points(vtkUnstructuredGrid *&ug) { MBRange verts; bool allocated; MBErrorCode result = vtkMOABUtils::mbImpl->get_entities_by_type(0, MBVERTEX, verts); if (MB_SUCCESS != result || verts.empty()) return result; // get the point array vtkPoints *points = ug->GetPoints(); if (NULL == points) { points = vtkPoints::New(); ug->SetPoints(points); points->Delete(); } // iterate from reverse so we only re-allocate once MBRange::reverse_iterator rit = verts.rbegin(); double coords[3]; MBErrorCode tmp_result; for (rit = verts.rbegin(); rit != verts.rend(); rit++) { // need to check for allocation tmp_result = vtkMOABUtils::mbImpl->tag_get_data(vtkPointAllocatedTag, &(*rit), 1, &allocated); if (MB_SUCCESS != tmp_result) result = tmp_result; if (allocated) continue; tmp_result = vtkMOABUtils::mbImpl->get_coords(&(*rit), 1, coords); if (MB_SUCCESS != tmp_result) result = tmp_result; else { points->InsertPoint(vtkMOABUtils::mbImpl->id_from_handle(*rit), coords); allocated = true; tmp_result = vtkMOABUtils::mbImpl->tag_set_data(vtkPointAllocatedTag, &(*rit), 1, &allocated); if (MB_SUCCESS != tmp_result) result = tmp_result; } } return result; } MBErrorCode vtkMOABUtils::make_cells(MBRange &ents, vtkUnstructuredGrid *&ug) { // add a cell for each entity, setting its global id to the cell id std::vector<vtkIdType> pt_ids; const MBEntityHandle *connect; int num_connect; MBErrorCode tmp_result, result = MB_SUCCESS; // check for unallocated ug (shouldn't have to do this, really...) if (NULL == ug->GetCells()) ug->Allocate(); vtkIdType cell_id; for (MBRange::iterator rit = ents.begin(); rit != ents.end(); rit++) { // check to see if it's been allocated already tmp_result = vtkMOABUtils::mbImpl->tag_get_data(vtkCellTag, &(*rit), 1, &cell_id); if (MB_SUCCESS != tmp_result) result = tmp_result; if (cell_id != -1) continue; // get a list of point ids if (vtkMOABUtils::mbImpl->type_from_handle(*rit) == MBVERTEX) { connect = &(*rit); num_connect = 1; } else { tmp_result = vtkMOABUtils::mbImpl->get_connectivity(*rit, connect, num_connect); if (MB_SUCCESS != tmp_result) result = tmp_result; } pt_ids.reserve(num_connect); for (int i = 0; i < num_connect; i++) pt_ids[i] = vtkMOABUtils::mbImpl->id_from_handle(connect[i]); // make the actual polygon cell_id = ug->InsertNextCell(vtk_cell_types[vtkMOABUtils::mbImpl->type_from_handle(*rit)], num_connect, &pt_ids[0]); // assign the resulting cell id to the global id tmp_result = vtkMOABUtils::mbImpl->tag_set_data(vtkCellTag, &(*rit), 1, &cell_id); if (MB_SUCCESS != tmp_result) result = tmp_result; } return MB_SUCCESS; } MBErrorCode vtkMOABUtils::make_cells(vtkUnstructuredGrid *&ug) { // add a cell for all entities MBRange ents; MBErrorCode result = MB_SUCCESS; for (MBEntityType in_type = MBVERTEX; in_type < MBENTITYSET; in_type++) { // skip cell types vtk doesn't understand if (vtk_cell_types[in_type] == 0) continue; ents.clear(); MBErrorCode tmp_result = mbImpl->get_entities_by_type(0, in_type, ents); if (MB_SUCCESS != tmp_result || ents.empty()) { result = tmp_result; continue; } tmp_result = make_cells(ents, ug); if (MB_SUCCESS != tmp_result) result = tmp_result; } return result; } MBErrorCode vtkMOABUtils::make_cells(MBEntityType in_type, vtkUnstructuredGrid *&ug) { // skip cell types vtk doesn't understand if (vtk_cell_types[in_type] == 0) return MB_FAILURE; // add a cell for entities of types passed in MBRange ents; MBErrorCode result = mbImpl->get_entities_by_type(0, in_type, ents); if (MB_SUCCESS != result || ents.empty()) return result; return make_cells(ents, ug); } MBErrorCode vtkMOABUtils::update_all_actors(MBEntityHandle this_set, vtkUnstructuredGrid *ug, const bool shaded, const bool tubed, const bool colored) { assert(NULL != ug); MBRange update_sets; MBErrorCode result = vtkMOABUtils::mbImpl->get_entities_by_type(this_set, MBENTITYSET, update_sets); if (MB_SUCCESS != result) return result; // finally, the sets MBRange chord_sets, sheet_sets; result = dualTool->get_dual_hyperplanes(vtkMOABUtils::mbImpl, 1, chord_sets); if (MB_SUCCESS != result) return result; result = dualTool->get_dual_hyperplanes(vtkMOABUtils::mbImpl, 2, sheet_sets); if (MB_SUCCESS != result) return result; result = vtkMOABUtils::update_set_actors(chord_sets, vtkMOABUtils::myUG, true, false, true); if (MB_SUCCESS != result) return result; result = vtkMOABUtils::update_set_actors(sheet_sets, vtkMOABUtils::myUG, true, false, true); if (MB_SUCCESS != result) return result; int table_size = ((int) (chord_sets.size()+sheet_sets.size()) > vtkMOABUtils::totalColors ? chord_sets.size()+sheet_sets.size() : vtkMOABUtils::totalColors); vtkMOABUtils::construct_lookup_table(table_size); update_sets = update_sets.subtract(chord_sets); update_sets = update_sets.subtract(sheet_sets); return vtkMOABUtils::update_set_actors(update_sets, ug, shaded, tubed, colored); } MBErrorCode vtkMOABUtils::update_set_actors(const MBRange &update_sets, vtkUnstructuredGrid *ug, const bool shaded, const bool tubed, const bool colored) { assert(NULL != ug); // update (empty & re-populate) actors corresponding to these sets MBErrorCode tmp_result; vtkActor *this_actor; MBRange ents; MBErrorCode result = MB_SUCCESS; for (MBRange::const_iterator rit = update_sets.begin(); rit != update_sets.end(); rit++) { ents.clear(); // get a list of vtk cell ids for this set vtkIdList *ids; tmp_result = vtkMOABUtils::get_id_list(*rit, ids); if (MB_SUCCESS != tmp_result || NULL == ids) { result = tmp_result; continue; } if (ids->GetNumberOfIds() == 0) { ids->Delete(); continue; } // non-zero list of ids; get an actor to put them in vtkExtractCells *ec; vtkMapper *this_mapper; this_actor = vtkMOABUtils::get_actor(*rit); // if the actor already exists, replace its id list with this one and go on // to next set if (NULL != this_actor) { // get ec from this actor vtkSource *this_source = this_actor->GetMapper()->GetInput()->GetSource(); ec = vtkExtractCells::SafeDownCast(this_source); if (debug) { std::cout << "Set " << mbImpl->id_from_handle(*rit) << ", actor " << this_actor << ", extractcells = "; if (NULL == ec) std::cout << "(null)"; else std::cout << ec; std::cout << std::endl; } // don't act on root entity set (that'll be the only one not connected // to an extract cells filter) // empty out the extract cells filter if (NULL != ec) ec->SetCellList(ids); ids->Delete(); continue; } // otherwise, we need to make a new one; also make an extractor to extract // the right ids this_actor = vtkMOABUtils::get_actor(*rit, true); ec = vtkExtractCells::New(); ec->SetInput(ug); ec->AddCellList(ids); if (debug) { std::cout << "Set " << mbImpl->id_from_handle(*rit) << ", actor " << this_actor << ", extractcells = "; if (NULL == ec) std::cout << "(null)"; else std::cout << ec; std::cout << std::endl; std::cout << "Number of ids is " << ids->GetNumberOfIds() << std::endl; } // if tube filter is requested, do special stuff to extract edges and // wrap them in tubes, returning a mapper if (tubed) vtkMOABUtils::setup_tube_filter(*rit, ec, this_mapper); // otherwise just put a mapper around the ec else { vtkDataSetMapper *ds_mapper = vtkDataSetMapper::New(); ds_mapper->SetInput(ec->GetOutput()); this_mapper = ds_mapper; } this_actor->SetMapper(this_mapper); vtkMOABUtils::myRen->AddActor(this_actor); vtkProperty *this_prop; // only if we're shaded or colored do we get our own property, otherwise // we inherit from the top-level property if (shaded || colored) this_prop = vtkMOABUtils::get_property(this_actor, true); else this_actor->SetProperty(topProperty); // now set the actual properties if (shaded) this_prop->SetRepresentationToSurface(); // if we're drawing shaded and not tubed, it's probably a dual surface, so // turn off backface culling so we can see both sides if (shaded && !tubed) this_prop->BackfaceCullingOff(); // only set color on the property if it's tubed if (colored) vtkMOABUtils::set_color(*rit, this_prop); // otherwise, use scalars to set the color // else if (colored) { // this_mapper->SetLookupTable(lookupTable); // this_mapper->UseLookupTableScalarRangeOn(); // } ids->Delete(); this_mapper->Delete(); ec->Delete(); } return result; } MBErrorCode vtkMOABUtils::setup_tube_filter(MBEntityHandle this_set, vtkExtractCells *ec, vtkMapper *&this_mapper) { // decide whether an edge extractor is needed (if > 1d entities exist, it is) int hd_ents, dum; MBErrorCode result = vtkMOABUtils::mbImpl->get_number_entities_by_dimension(this_set, 2, hd_ents, true), tmp_result = vtkMOABUtils::mbImpl->get_number_entities_by_dimension(this_set, 3, dum, true); hd_ents += dum; if (MB_SUCCESS != result) return result; if (MB_SUCCESS != tmp_result) return tmp_result; // put an edge extractor and tube filter around these vtkTubeFilter *tf = vtkTubeFilter::New(); if (hd_ents > 0) { vtkExtractEdges *ee = vtkExtractEdges::New(); ee->SetInput(ec->GetOutput()); tf->SetInput(ee->GetOutput()); // ee->Delete(); } else { // need a geometry filter to change unstructuredgrid to polydata vtkGeometryFilter *gf = vtkGeometryFilter::New(); gf->SetInput(ec->GetOutput()); tf->SetInput(gf->GetOutput()); // gf->Delete(); } tf->SetNumberOfSides(6); tf->SetRadius(0.005); vtkPolyDataMapper *pd_mapper = vtkPolyDataMapper::New(); pd_mapper->SetInput(tf->GetOutput()); this_mapper = pd_mapper; return MB_SUCCESS; } MBErrorCode vtkMOABUtils::get_id_list(MBEntityHandle this_set, vtkIdList *&ids) { MBRange ents; MBErrorCode result = vtkMOABUtils::mbImpl->get_entities_by_handle(this_set, ents); if (MB_SUCCESS != result || ents.empty()) { ids = NULL; return result; } return get_id_list(ents, ids); } MBErrorCode vtkMOABUtils::get_id_list(MBRange &ents, vtkIdList *&ids) { MBErrorCode tmp_result, result = MB_SUCCESS; ids = vtkIdList::New(); vtkIdType this_id; for (MBRange::iterator rit = ents.begin(); rit != ents.end(); rit++) { if (vtkMOABUtils::mbImpl->type_from_handle(*rit) == MBENTITYSET) continue; tmp_result = vtkMOABUtils::mbImpl->tag_get_data(vtkCellTag, &(*rit), 1, &this_id); if (MB_SUCCESS != tmp_result) result = tmp_result; else if (this_id != -1) { ids->InsertNextId(this_id); } } return result; } MBErrorCode vtkMOABUtils::empty_assy(vtkPropAssembly *this_assy) { // remove all the parts from this assy vtkPropCollection *parts = this_assy->GetParts(); vtkProp *this_part = NULL, *next_part = parts->GetNextProp(); while (NULL != next_part) { this_part = next_part; next_part = parts->GetNextProp(); this_assy->RemovePart(this_part); } return MB_SUCCESS; } MBErrorCode vtkMOABUtils::get_top_contains_sets(MBRange &top_sets) { // get top contains sets, which are those containing sets and not contained in any other sets top_sets.clear(); MBErrorCode result = vtkMOABUtils::mbImpl->get_entities_by_type(0, MBENTITYSET, top_sets); if (MB_SUCCESS != result || top_sets.empty()) return result; MBRange dum_sets = top_sets, tmp_set; // now go through all children, removing them from top sets MBErrorCode tmp_result; for (MBRange::iterator rit = dum_sets.begin(); rit != dum_sets.end(); rit++) { tmp_set.clear(); tmp_result = vtkMOABUtils::mbImpl->get_entities_by_type(*rit, MBENTITYSET, tmp_set); if (MB_SUCCESS != tmp_result) result = tmp_result; else if (!tmp_set.empty()) // remove all the children from the top sets top_sets = top_sets.subtract(tmp_set); else // else no children - shouldn't be a top set top_sets.erase(*rit); if (top_sets.empty()) break; } return result; } MBErrorCode vtkMOABUtils::get_top_parent_sets(MBRange &top_sets) { // get top parent sets, which are those who aren't children of others but have // some children top_sets.clear(); MBRange dum_sets; MBErrorCode result = vtkMOABUtils::mbImpl->get_entities_by_type(0, MBENTITYSET, dum_sets); if (MB_SUCCESS != result || dum_sets.empty()) return result; MBErrorCode tmp_result; int num_children, num_parents; for (MBRange::iterator rit = dum_sets.begin(); rit != dum_sets.end(); rit++) { tmp_result = vtkMOABUtils::mbImpl->num_child_meshsets(*rit, &num_children); if (MB_SUCCESS != tmp_result) result = tmp_result; tmp_result = vtkMOABUtils::mbImpl->num_parent_meshsets(*rit, &num_parents); if (MB_SUCCESS != tmp_result) result = tmp_result; if (num_parents == 0 && num_children > 0) top_sets.insert(*rit); } return result; } MBErrorCode vtkMOABUtils::set_color(MBEntityHandle this_set, vtkProperty *this_property, const int total_colors) { double red, green, blue; int dum; MBErrorCode result = vtkMOABUtils::get_colors(this_set, total_colors, dum, red, green, blue); this_property->SetColor(red, green, blue); return result; } vtkProperty *vtkMOABUtils::get_property(vtkActor *this_actor, const bool make_if_missing) { vtkProperty *this_prop = vtkMOABUtils::actorProperties[this_actor]; if (NULL == this_prop && make_if_missing) { this_prop = this_actor->MakeProperty(); actorProperties[this_actor] = this_prop; this_actor->SetProperty(this_prop); } return this_prop; } vtkProperty *vtkMOABUtils::get_property(MBEntityHandle this_set, const bool make_if_missing) { vtkActor *this_actor; MBErrorCode result = vtkMOABUtils::mbImpl->tag_get_data(vtkSetActorTag, &this_set, 1, &this_actor); if (MB_SUCCESS != result || NULL == this_actor) return NULL; return get_property(this_actor, make_if_missing); } vtkActor *vtkMOABUtils::get_actor(MBEntityHandle this_set, const bool make_if_missing) { vtkActor *this_actor = NULL; assert(0 != vtkSetActorTag); if (0 == this_set) vtkMOABUtils::mbImpl->tag_get_data(vtkSetActorTag, NULL, 0, &this_actor); else vtkMOABUtils::mbImpl->tag_get_data(vtkSetActorTag, &this_set, 1, &this_actor); if (make_if_missing && NULL == this_actor) { this_actor = vtkActor::New(); propSetMap[this_actor] = this_set; if (0 == this_set) vtkMOABUtils::mbImpl->tag_set_data(vtkSetActorTag, NULL, 0, &this_actor); else vtkMOABUtils::mbImpl->tag_set_data(vtkSetActorTag, &this_set, 1, &this_actor); } return this_actor; } //! given a prop, get the corresponding set MBEntityHandle vtkMOABUtils::get_set(vtkProp *this_prop) { return propSetMap[this_prop]; } MBTag vtkMOABUtils::globalId_tag() { if (0 == globalIdTag) vtkMOABUtils::mbImpl->tag_get_handle(GLOBAL_ID_TAG_NAME, 1, MB_TYPE_INTEGER, globalIdTag); return globalIdTag; } MBTag vtkMOABUtils::category_tag() { if (0 == categoryTag) vtkMOABUtils::mbImpl->tag_get_handle(CATEGORY_TAG_NAME, NAME_TAG_SIZE, MB_TYPE_OPAQUE, categoryTag); return categoryTag; } MBErrorCode vtkMOABUtils::get_set_category_name( MBEntityHandle this_set, char *this_name ) { if (0 == vtkMOABUtils::globalId_tag()) return MB_SUCCESS; int this_id; MBErrorCode result = vtkMOABUtils::mbImpl->tag_get_data(vtkMOABUtils::globalId_tag(), &this_set, 1, &this_id); if (MB_SUCCESS != result) return result; // get the id of the set char cat_name[CATEGORY_TAG_SIZE]; sprintf(cat_name, "\0"); if (0 != vtkMOABUtils::category_tag()) result = vtkMOABUtils::mbImpl->tag_get_data(vtkMOABUtils::category_tag(), &this_set, 1, &cat_name); if (MB_SUCCESS != result || !strcmp(cat_name, "\0")) { if (0 == this_id) { this_id = vtkMOABUtils::mbImpl->id_from_handle(this_set); sprintf(cat_name, "Set handle"); } else { sprintf(cat_name, "Set id"); } } sprintf(this_name, "%s %d", cat_name, this_id); return MB_SUCCESS; } void vtkMOABUtils::print_debug() { for (std::map<vtkActor*,vtkProperty*>::const_iterator mit = actorProperties.begin(); mit != actorProperties.end(); mit++) mit->first->GetMapper()->GetInput()->PrintSelf(std::cout, vtkIndent(0)); } void vtkMOABUtils::change_set_visibility( MBRange &visible_sets, MBRange &invisible_sets ) { static std::vector<vtkActor*> tmp_actors; // always do invisible first tmp_actors.reserve(invisible_sets.size()); MBErrorCode result = mbImpl->tag_get_data(vtkSetActorTag, invisible_sets, &tmp_actors[0]); if (MB_SUCCESS != result) { ; // do nothing, just place to stop the debugger } for (unsigned int i = 0; i < invisible_sets.size(); i++) if (NULL != tmp_actors[i]) tmp_actors[i]->VisibilityOff(); tmp_actors.reserve(visible_sets.size()); result = mbImpl->tag_get_data(vtkSetActorTag, visible_sets, &tmp_actors[0]); if (MB_SUCCESS != result) { ; // do nothing, just place to stop the debugger } for (unsigned int i = 0; i < visible_sets.size(); i++) if (NULL != tmp_actors[i]) tmp_actors[i]->VisibilityOn(); } void vtkMOABUtils::change_set_properties(MBRange &high_mbsets, MBRange &unhigh_mbsets) { vtkProperty *curr_prop; MBRange::iterator rit; for (rit = high_mbsets.begin(); rit != high_mbsets.end(); rit++) { vtkActor *this_actor = get_actor(*rit); if (NULL == this_actor) continue; curr_prop = this_actor->GetProperty(); if (curr_prop != highlightProperty) this_actor->SetProperty(highlightProperty); } for (rit = unhigh_mbsets.begin(); rit != unhigh_mbsets.end(); rit++) { vtkActor *this_actor = get_actor(*rit); if (NULL == this_actor) continue; curr_prop = this_actor->GetProperty(); if (curr_prop == highlightProperty) { if ((curr_prop = actorProperties[this_actor])) this_actor->SetProperty(curr_prop); else this_actor->SetProperty(topProperty); } } } //! toggle the wireframe/shaded property void vtkMOABUtils::toggle_wireframe_shaded(MBRange &high_mbsets) { for (MBRange::iterator rit = high_mbsets.begin(); rit != high_mbsets.end(); rit++) { vtkProperty *this_prop = get_property(*rit, true); if (this_prop->GetRepresentation() == VTK_WIREFRAME) this_prop->SetRepresentation(VTK_SURFACE); else if (this_prop->GetRepresentation() == VTK_SURFACE) this_prop->SetRepresentation(VTK_WIREFRAME); } } //! put the specified extractor at the head of the pipeline, just after myUG void vtkMOABUtils::add_geom_extractors(vtkImplicitFunction *this_func) { assert(NULL != myRen); vtkActorCollection *my_actors = myRen->GetActors(); my_actors->InitTraversal(); vtkActor *this_actor = my_actors->GetNextActor(); while (NULL != this_actor) { // trace back to mapper input vtkDataSetMapper *this_dsmapper = vtkDataSetMapper::SafeDownCast(this_actor->GetMapper()); vtkPolyDataMapper *this_pdmapper = vtkPolyDataMapper::SafeDownCast(this_actor->GetMapper()); if (NULL != this_dsmapper) { vtkDataSet *this_ds = this_dsmapper->GetInput(); // re-route this data set through a new vtkExtractGeometry and that to the mapper vtkExtractGeometry *eg = vtkExtractGeometry::New(); eg->SetImplicitFunction(this_func); eg->SetInput(this_ds); this_dsmapper->SetInput(eg->GetOutput()); } else if (NULL != this_pdmapper) { vtkPolyData *this_pd = this_pdmapper->GetInput(); // re-route this data set through a new vtkExtractGeometry and that to the mapper vtkExtractPolyDataGeometry *epg = vtkExtractPolyDataGeometry::New(); epg->SetImplicitFunction(this_func); epg->SetInput(this_pd); this_pdmapper->SetInput(epg->GetOutput()); } else { assert(false); } this_actor = my_actors->GetNextActor(); } /* this_extr->SetInput(myUG); // put this extractor between myUG and all its consumers int num_cons = myUG->GetNumberOfConsumers(); // build a list of consumers std::vector<vtkObject*> consumers; for (int i = 0; i < num_cons; i++) consumers.push_back(myUG->GetConsumer(i)); // now reset the inputs of these consumers to be this_extr; should remove the consumers // from ug also, I'd think for (int i = 0; i < num_cons; i++) { vtkObject *this_obj = consumers[i]; // try the various types they can be vtkDataSetToPolyDataFilter *ds = vtkDataSetToPolyDataFilter::SafeDownCast(this_obj); if (NULL != ds) { ds->SetInput(this_extr->GetOutput()); ds->Update(); continue; } vtkDataSetToUnstructuredGridFilter *dsu = vtkDataSetToUnstructuredGridFilter::SafeDownCast(this_obj); if (NULL != dsu) { dsu->SetInput(this_extr->GetOutput()); dsu->Update(); continue; } vtkDataSetMapper *dsm = vtkDataSetMapper::SafeDownCast(this_obj); if (NULL != dsm) { dsm->SetInput(this_extr->GetOutput()); dsm->Update(); continue; } } */ } //! remove the specified extractor from the head of the pipeline, just after myUG void vtkMOABUtils::remove_geom_extractors() { assert(NULL != myRen); vtkActorCollection *my_actors = myRen->GetActors(); my_actors->InitTraversal(); vtkActor *this_actor = my_actors->GetNextActor(); while (NULL != this_actor) { // trace back to mapper input vtkDataSetMapper *this_dsmapper = vtkDataSetMapper::SafeDownCast(this_actor->GetMapper()); vtkPolyDataMapper *this_pdmapper = vtkPolyDataMapper::SafeDownCast(this_actor->GetMapper()); if (NULL != this_dsmapper) { vtkExtractGeometry *eg = vtkExtractGeometry::SafeDownCast(this_dsmapper->GetInput()->GetSource()); if (NULL != eg) { vtkDataSet* set = vtkDataSet::SafeDownCast(eg->GetInput()); this_dsmapper->SetInput(set); eg->Delete(); } else std::cerr << "Didn't find vtkExtractGeometry!" << std::endl; } else if (NULL != this_pdmapper) { vtkExtractPolyDataGeometry *epg = vtkExtractPolyDataGeometry::SafeDownCast(this_pdmapper->GetInput()->GetSource()); if (NULL != epg) { vtkPolyData* pd = vtkPolyData::SafeDownCast(epg->GetInput()); this_pdmapper->SetInput(pd); epg->Delete(); } else std::cerr << "Didn't find vtkExtractPolyDataGeometry!" << std::endl; } else { assert(false); } this_actor = my_actors->GetNextActor(); } /* assert(NULL != myUG); // remove this extractor from the pipeline int num_cons = this_extr->GetOutput()->GetNumberOfConsumers(); // build a list of consumers std::vector<vtkObject*> consumers; for (int i = 0; i < num_cons; i++) consumers.push_back(this_extr->GetOutput()->GetConsumer(i)); // now reset the inputs of these consumers to be this_extr; should remove the consumers // from ug also, I'd think for (int i = 0; i < num_cons; i++) { vtkObject *this_obj = consumers[i]; // try the various types they can be vtkDataSetToUnstructuredGridFilter *dsu = vtkDataSetToUnstructuredGridFilter::SafeDownCast(this_obj); if (NULL != dsu) { dsu->SetInput(myUG); continue; } vtkDataSetToPolyDataFilter *ds = vtkDataSetToPolyDataFilter::SafeDownCast(this_obj); if (NULL != ds) { ds->SetInput(myUG); continue; } vtkDataSetMapper *dsm = vtkDataSetMapper::SafeDownCast(this_obj); if (NULL != dsm) { dsm->SetInput(myUG); continue; } } this_extr->SetInput(NULL); */ } void vtkMOABUtils::construct_lookup_table(const int max_scalars) { // constructs color lookup table and populates if (NULL != lookupTable) lookupTable->Delete(); lookupTable = vtkLookupTable::New(); // set the range to 0..max_scalars lookupTable->SetTableRange(0.0, (double) max_scalars); lookupTable->Build(); lookupTable->SetRampToLinear(); } MBErrorCode vtkMOABUtils::get_colors(MBEntityHandle dual_set, const int total_colors, int &global_id, double &red, double &green, double &blue) { #define MIN(a,b) (a > b ? b : a) #define MAX(a,b) (a < b ? b : a) if (NULL == lookupTable) construct_lookup_table(total_colors); MBErrorCode result = vtkMOABUtils::mbImpl->tag_get_data(vtkMOABUtils::globalId_tag(), &dual_set, 1, &global_id); if (MB_SUCCESS != result) return result; int max_val = (int) lookupTable->GetTableRange()[1]; int color_id = (global_id > max_val ? global_id % max_val : global_id); double colors[3]; lookupTable->GetColor((double)color_id, colors); red = colors[0]; green = colors[1]; blue = colors[2]; /* if (global_id >= 0) { // set the color by this id double factor = ((double)(global_id%total_colors)) / ((double)total_colors); red = RED(factor); green = GREEN(factor); blue = BLUE(factor); } */ return MB_SUCCESS; } void vtkMOABUtils::update_display(vtkUnstructuredGrid *ug) { if (NULL == myUG) { if (NULL == ug) ug = vtkUnstructuredGrid::New(); myUG = ug; // make sure there's a mapper, actor for the whole mesh in ug, put in renderer vtkPolyDataMapper *poly_mapper; vtkDataSetMapper *set_mapper; vtkTubeFilter *tube_filter; vtkExtractEdges *edge_filter; vtkActor *mesh_actor = vtkActor::New(); bool tubes = true; if (tubes) { // extract edges and build a tube filter for them poly_mapper = vtkPolyDataMapper::New(); mesh_actor->SetMapper(poly_mapper); tube_filter = vtkTubeFilter::New(); poly_mapper->SetInput(tube_filter->GetOutput()); edge_filter = vtkExtractEdges::New(); tube_filter->SetInput(edge_filter->GetOutput()); /* cell_filter = vtkExtractCells::New(); vtkIdList *ids; MBRange ents, dum_ents; MBErrorCode result = mbImpl->get_entities_by_dimension(0, 3, dum_ents); if (MB_SUCCESS != result) return; for (MBRange::iterator rit = dum_ents.begin(); rit != dum_ents.end(); rit++) if (mbImpl->type_from_handle(*rit) != MBPOLYHEDRON) ents.insert(*rit); result = vtkMOABUtils::get_id_list(ents, ids); cell_filter->SetInput(myUG); cell_filter->AddCellList(ids); ids->Delete(); edge_filter->SetInput(cell_filter->GetOutput()); */ edge_filter->SetInput(myUG); tube_filter->SetNumberOfSides(6); tube_filter->SetRadius(0.005); poly_mapper->ImmediateModeRenderingOn(); } else { set_mapper = vtkDataSetMapper::New(); set_mapper->SetInput(vtkMOABUtils::myUG); mesh_actor->SetMapper(set_mapper); set_mapper->ImmediateModeRenderingOn(); } vtkMOABUtils::myRen->AddActor(mesh_actor); MBErrorCode result = vtkMOABUtils::mbImpl->tag_set_data(vtkMOABUtils::vtkSetActorTag, NULL, 0, &mesh_actor); if (MB_SUCCESS != result) { std::cerr << "Failed to set actor for mesh in vtkMOABUtils::update_display()." << std::endl; return; } // now turn around and set a different property for the mesh, because we want the tubes // to be shaded in red vtkMOABUtils::actorProperties[mesh_actor] = NULL; vtkProperty *this_prop = vtkMOABUtils::get_property(mesh_actor, true); vtkMOABUtils::actorProperties[mesh_actor] = this_prop; this_prop->SetRepresentationToSurface(); this_prop->SetColor(0.0, 1.0, 0.0); this_prop->SetEdgeColor(0.0, 1.0, 0.0); // mesh_actor->VisibilityOff(); /* // center the camera on the center of the ug vtkMOABUtils::myRen->GetActiveCamera()->SetFocalPoint(ug->GetPoint(1)); vtkMOABUtils::myRen->GetActiveCamera()->SetPosition(0, 0, 50.0); vtkMOABUtils::myRen->GetActiveCamera()->SetViewUp(0, 1.0, 0.0); std::cout << "Set focal point to " << ug->GetPoint(1)[0] << ", " << ug->GetPoint(1)[1] << ", " << ug->GetPoint(1)[2] << std::endl; */ mesh_actor->Delete(); if (tubes) { // tube_filter->Delete(); // edge_filter->Delete(); // poly_mapper->Delete(); } else { set_mapper->Delete(); } } MBErrorCode result = vtkMOABUtils::make_vertex_points(myUG); if (MB_SUCCESS != result) { std::cerr << "Failed to make vertex points." << std::endl; return; } // now make the cells result = vtkMOABUtils::make_cells(myUG); if (MB_SUCCESS != result) { std::cerr << "Failed to make cells." << std::endl; return; } result = update_all_actors(0, myUG, false); if (MB_SUCCESS != result) { std::cerr << "Failed to update. " << std::endl; } // Render myRen->GetRenderWindow()->Render(); // Reset camera vtkMOABUtils::myRen->ResetCamera(); } //! get rid of all the vtk drawing stuff void vtkMOABUtils::reset_drawing_data() { MBRange these_sets; MBErrorCode result; dualTool->get_dual_hyperplanes(vtkMOABUtils::mbImpl, 1, these_sets); dualTool->get_dual_hyperplanes(vtkMOABUtils::mbImpl, 2, these_sets); for (MBRange::iterator rit = these_sets.begin(); rit != these_sets.end(); rit++) vtkMOABUtils::get_actor(*rit)->Delete(); actorProperties.clear(); //! map between props (actor2d's and actors) and sets they represent (0 if no set, //! e.g. an extracted set) propSetMap.clear(); if (NULL != topContainsAssy) { topContainsAssy->Delete(); topContainsAssy = NULL; } //! topmost assembly for displaying parent/child relationships if (NULL != topParentAssy) { topParentAssy->Delete(); topParentAssy = NULL; } if (NULL != drawDual) { delete drawDual; drawDual = NULL; } if (NULL != myUG) { myUG->Delete(); myUG = NULL; } if (NULL == mbImpl) return; //! tag indicating whether a given set is in top contains assy result = mbImpl->tag_delete(vtkTopContainsTag); if (MB_SUCCESS != result && MB_TAG_NOT_FOUND != result) std::cout << "Trouble deleting tag." << std::endl; vtkTopContainsTag = NULL; //! tag indicating whether a given set is in top parent assy result = mbImpl->tag_delete(vtkTopParentTag); if (MB_SUCCESS != result && MB_TAG_NOT_FOUND != result) std::cout << "Trouble deleting tag." << std::endl; vtkTopParentTag = NULL; result = mbImpl->tag_delete(vtkCellTag); if (MB_SUCCESS != result && MB_TAG_NOT_FOUND != result) std::cout << "Trouble deleting tag." << std::endl; vtkCellTag = NULL; result = mbImpl->tag_delete(vtkSetActorTag); if (MB_SUCCESS != result && MB_TAG_NOT_FOUND != result) std::cout << "Trouble deleting tag." << std::endl; vtkSetActorTag = NULL; result = mbImpl->tag_delete(vtkSetPropAssemblyTag); if (MB_SUCCESS != result && MB_TAG_NOT_FOUND != result) std::cout << "Trouble deleting tag." << std::endl; vtkSetPropAssemblyTag = NULL; result = mbImpl->tag_delete(vtkPointAllocatedTag); if (MB_SUCCESS != result && MB_TAG_NOT_FOUND != result) std::cout << "Trouble deleting tag." << std::endl; vtkPointAllocatedTag = NULL; create_tags(); } void vtkMOABUtils::assign_global_ids() { std::vector<int> ids; MBTag gid = globalId_tag(); MBErrorCode result; MBEntityType types[] = {MBVERTEX, MBEDGE, MBQUAD, MBHEX}; for (unsigned int j = 0; j <= 3; j++) { MBRange ents; result = mbImpl->get_entities_by_type(0, types[j], ents); if (MB_SUCCESS != result) return; ids.resize(ents.size()); std::fill(ids.begin(), ids.end(), -1); mbImpl->tag_get_data(gid, ents, &ids[0]); bool need_set = false; // get max id int max_id = -1; for (unsigned int i = 0; i < ids.size(); i++) if (ids[i] > max_id) max_id = ids[i]; for (unsigned int i = 0; i < ids.size(); i++) { if (ids[i] == 0) { ids[i] = ++max_id; need_set = true; } } if (need_set) mbImpl->tag_set_data(gid, ents, &ids[0]); } }
32.689057
105
0.632535
[ "mesh", "geometry", "render", "vector" ]
d51951cc331250dbeceb73af8d889991dd07140e
53,407
cpp
C++
toonz/sources/tnztools/toolutils.cpp
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/tnztools/toolutils.cpp
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/tnztools/toolutils.cpp
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
1
2019-10-07T17:12:30.000Z
2019-10-07T17:12:30.000Z
#include "tools/toolutils.h" #include "tools/toolhandle.h" #include "toonzqt/imageutils.h" #include "trop.h" #include "tools/tool.h" #include "tstroke.h" #include "timageinfo.h" #include "timagecache.h" #include "tgl.h" #include "toonz/txsheethandle.h" #include "toonz/tframehandle.h" #include "toonz/txshlevelhandle.h" #include "toonz/tscenehandle.h" #include "toonz/txshleveltypes.h" #include "toonz/tcolumnhandle.h" #include "toonz/tpalettehandle.h" #include "toonz/txshlevel.h" #include "toonz/txshcell.h" #include "toonz/txshsimplelevel.h" #include "toonz/imagemanager.h" #include "toonz/ttileset.h" #include "toonz/toonzimageutils.h" #include "toonz/levelproperties.h" #include "toonz/tstageobjectspline.h" #include "toonz/tobjecthandle.h" #include "toonz/tstageobject.h" #include "toonz/trasterimageutils.h" #include "toonz/levelset.h" #include "toonz/toonzscene.h" #include "toonz/preferences.h" #include "toonz/palettecontroller.h" #include "toonzqt/tselectionhandle.h" #include "toonzqt/icongenerator.h" #include "toonzqt/selection.h" #include "toonzqt/gutil.h" #include "tools/strokeselection.h" #include <QPainter> #include <QGLWidget> #include <QFont> #include <QFontMetrics> //**************************************************************************************** // Local namespace //**************************************************************************************** namespace { //!Riempie il vettore \b theVect con gli indici degli stroke contenuti nel mapping \b theMap. void mapToVector(const std::map<int, VIStroke *> &theMap, std::vector<int> &theVect) { assert(theMap.size() == theVect.size()); std::map<int, VIStroke *>::const_iterator it = theMap.begin(); UINT i = 0; for (; it != theMap.end(); ++it) { theVect[i++] = it->first; } } //------------------------------------------------------------ void updateSaveBox(const TToonzImageP &ti) { if (ti) { assert(ti->getRaster()); // Image should have a raster assert(ti->getSubsampling() == 1); // Image should not be subsampled - modified images must be the ORIGINAL ones const TRect &savebox = ti->getSavebox(); { TRect newSaveBox; TRop::computeBBox(ti->getRaster(), newSaveBox); // This iterates the WHOLE raster to find its new savebox! if (!Preferences::instance()->isMinimizeSaveboxAfterEditing()) newSaveBox += savebox; // If not minimizing the savebox, it cannot be shrunk. ti->setSavebox(newSaveBox); } } } } //namespace //**************************************************************************************** // ToolUtils namespace //**************************************************************************************** void ToolUtils::updateSaveBox(const TXshSimpleLevelP &sl, const TFrameId &fid) { // TODO: Savebox updates should not happen on mouse updates. This is, unfortunately, what currently happens. sl->setDirtyFlag(true); TImageP img = sl->getFrame(fid, true); // The image will be modified (it should already have been, though) // Observe that the returned image will forcedly have subsampling 1 ::updateSaveBox(img); TImageInfo *info = sl->getFrameInfo(fid, true); ImageBuilder::setImageInfo(*info, img.getPointer()); } //------------------------------------------------------------ void ToolUtils::updateSaveBox(const TXshSimpleLevelP &sl, const TFrameId &fid, TImageP img) { sl->setFrame(fid, img); ToolUtils::updateSaveBox(sl, fid); } //------------------------------------------------------------ void ToolUtils::updateSaveBox() { TTool::Application *application = TTool::getApplication(); if (!application) return; TXshLevel *xl = application->getCurrentLevel()->getLevel(); if (!xl) return; TXshSimpleLevel *sl = xl->getSimpleLevel(); if (!sl || sl->getType() != TZP_XSHLEVEL) return; TFrameId fid = getFrameId(); ToolUtils::updateSaveBox(sl, fid); } //----------------------------------------------------------------------------- //! Return the right value in both case: LevelFrame and SceneFrame. TFrameId ToolUtils::getFrameId() { TTool::Application *app = TTool::getApplication(); if (!app) return TFrameId(); TFrameHandle *frameHandle = app->getCurrentFrame(); if (frameHandle->isEditingScene()) { TXsheet *xsh = app->getCurrentXsheet()->getXsheet(); if (!xsh) return 0; int row = frameHandle->getFrame(); int col = app->getCurrentColumn()->getColumnIndex(); if (col < 0) return 0; TXshCell cell = xsh->getCell(row, col); return cell.getFrameId(); } else return frameHandle->getFid(); } //------------------------------------------------------------ void ToolUtils::drawRect(const TRectD &rect, const TPixel32 &color, unsigned short stipple, bool doContrast) { GLint src, dst; bool isEnabled; tglColor(color); if (doContrast) { if (color == TPixel32::Black) tglColor(TPixel32(90, 90, 90)); isEnabled = glIsEnabled(GL_BLEND); glGetIntegerv(GL_BLEND_SRC, &src); glGetIntegerv(GL_BLEND_DST, &dst); glEnable(GL_BLEND); glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA); } if (stipple != 0xffff) { glLineStipple(1, stipple); glEnable(GL_LINE_STIPPLE); } glBegin(GL_LINE_STRIP); tglVertex(rect.getP00()); tglVertex(rect.getP01()); tglVertex(rect.getP11()); tglVertex(rect.getP10()); tglVertex(rect.getP00()); glEnd(); glDisable(GL_LINE_STIPPLE); if (doContrast) { if (!isEnabled) glDisable(GL_BLEND); glBlendFunc(src, dst); } } //----------------------------------------------------------------------------- void ToolUtils::fillRect(const TRectD &rect, const TPixel32 &color) { tglColor(color); glBegin(GL_QUADS); tglVertex(rect.getP00()); tglVertex(rect.getP01()); tglVertex(rect.getP11()); tglVertex(rect.getP10()); tglVertex(rect.getP00()); glEnd(); } //----------------------------------------------------------------------------- void ToolUtils::drawPoint(const TPointD &q, double pixelSize) { double size = pixelSize * 2.0; glBegin(GL_QUADS); glVertex2d(q.x - size, q.y - size); glVertex2d(q.x - size, q.y + size); glVertex2d(q.x + size, q.y + size); glVertex2d(q.x + size, q.y - size); glEnd(); } //----------------------------------------------------------------------------- void ToolUtils::drawCross(const TPointD &q, double pixelSize) { double size = pixelSize; glBegin(GL_LINES); glVertex2d(q.x - size, q.y); glVertex2d(q.x + size, q.y); glEnd(); glBegin(GL_LINES); glVertex2d(q.x, q.y - size); glVertex2d(q.x, q.y + size); glEnd(); } //----------------------------------------------------------------------------- void ToolUtils::drawArrow(const TSegment &s, double pixelSize) { TPointD v, vn; double length = s.getLength() * pixelSize; if (length == 0) return; v = normalize(s.getSpeed()); vn = v; TPointD p1 = s.getP0() + v * length; glBegin(GL_LINES); tglVertex(s.getP0()); tglVertex(p1); glEnd(); v = v * length * 0.7; vn = vn * length * 0.2; TPointD p; glBegin(GL_TRIANGLES); p = s.getP0() + v + rotate90(vn); tglVertex(p); tglVertex(p1); p = s.getP0() + v + rotate270(vn); tglVertex(p); glEnd(); } //----------------------------------------------------------------------------- void ToolUtils::drawSquare(const TPointD &pos, double r, const TPixel32 &color) { TRectD rect(pos - TPointD(r, r), pos + TPointD(r, r)); tglColor(color); glBegin(GL_LINE_STRIP); tglVertex(rect.getP00()); tglVertex(rect.getP01()); tglVertex(rect.getP11()); tglVertex(rect.getP10()); tglVertex(rect.getP00()); glEnd(); } //----------------------------------------------------------------------------- void ToolUtils::drawRectWhitArrow(const TPointD &pos, double r) { if (TTool::getApplication()->getCurrentObject()->isSpline()) return; TRectD rect(pos - TPointD(14 * r, 2 * r), pos + TPointD(14 * r, 2 * r)); tglColor(TPixel32::Black); glBegin(GL_POLYGON); tglVertex(rect.getP00()); tglVertex(rect.getP10()); tglVertex(rect.getP11()); tglVertex(rect.getP01()); glEnd(); double par = 5 * r; TPointD p01 = 0.5 * (rect.getP00() + rect.getP10()); TPointD p02 = 0.5 * (rect.getP01() + rect.getP11()); TPointD p11 = TPointD(p01.x, p01.y - par); TPointD p12 = TPointD(p02.x, p02.y + par); TPointD p; tglColor(TPixel32(130, 130, 130)); glBegin(GL_TRIANGLES); p = p11 + rotate90(TPointD(0, par)); tglVertex(p); tglVertex(p01); p = p11 + rotate270(TPointD(0, par)); tglVertex(p); glEnd(); glBegin(GL_TRIANGLES); p = p12 + rotate90(TPointD(0, -par)); tglVertex(p); tglVertex(p02); p = p12 + rotate270(TPointD(0, -par)); tglVertex(p); glEnd(); } //----------------------------------------------------------------------------- QRadialGradient ToolUtils::getBrushPad(int size, double hardness) { hardness = tcrop(hardness, 0.0, 0.97); double halfSize = size * 0.5; double x = halfSize * hardness; TQuadratic q(TPointD(x, 1.0), TPointD((halfSize + x) * 0.5, 0.0), TPointD(halfSize, 0.0)); QRadialGradient rd(QPointF(halfSize, halfSize), halfSize, QPointF(halfSize, halfSize)); rd.setColorAt(0, QColor(0, 0, 0)); double t; double offset = halfSize - x; assert(offset > 0); for (t = 0; t <= 1; t += 1.0 / offset) { TPointD p = q.getPoint(t); int value = 255 * p.y; rd.setColorAt(p.x / halfSize, QColor(0, 0, 0, value)); } return rd; } //----------------------------------------------------------------------------- QList<TRect> ToolUtils::splitRect(const TRect &first, const TRect &second) { TRect intersection = first * second; QList<TRect> rects; if (intersection.isEmpty()) { rects.append(first); return rects; } TRect rect; if (first.x0 < intersection.x0) { rect = TRect(first.getP00(), TPoint(intersection.x0 - 1, first.y1)); rects.append(rect); } if (intersection.x1 < first.x1) { rect = TRect(TPoint(intersection.x1 + 1, first.y0), first.getP11()); rects.append(rect); } if (intersection.y1 < first.y1) { rect = TRect(intersection.x0, intersection.y1 + 1, intersection.x1, first.y1); rects.append(rect); } if (first.y0 < intersection.y0) { rect = TRect(intersection.x0, first.y0, intersection.x1, intersection.y0 - 1); rects.append(rect); } return rects; } //----------------------------------------------------------------------------- TRaster32P ToolUtils::convertStrokeToImage(TStroke *stroke, const TRect &imageBounds, TPoint &pos) { int count = stroke->getControlPointCount(); if (count == 0) return TRaster32P(); TPointD imgCenter = TPointD((imageBounds.x0 + imageBounds.x1) * 0.5, (imageBounds.y0 + imageBounds.y1) * 0.5); TStroke s(*stroke); //check self looped stroke TThickPoint first = s.getControlPoint(0); TThickPoint back = s.getControlPoint(count - 1); if (first != back) { TPointD mid = (first + back) * 0.5; s.setControlPoint(count, mid); s.setControlPoint(count + 1, first); } //check bounds intersection s.transform(TTranslation(imgCenter)); TRectD bbox = s.getBBox(); TRect rect(tfloor(bbox.x0), tfloor(bbox.y0), tfloor(bbox.x1), tfloor(bbox.y1)); pos = rect.getP00(); pos = TPoint(pos.x > 0 ? pos.x : 0, pos.y > 0 ? pos.y : 0); rect *= imageBounds; if (rect.isEmpty()) return TRaster32P(); //creates the image QImage img(rect.getLx(), rect.getLy(), QImage::Format_ARGB32); img.fill(Qt::transparent); QColor color = Qt::black; QPainter p(&img); p.setPen(QPen(color, 1, Qt::SolidLine)); p.setBrush(color); p.setRenderHint(QPainter::Antialiasing, true); QPainterPath path = strokeToPainterPath(&s); QRectF pathRect = path.boundingRect(); p.translate(-toQPoint(pos)); p.drawPath(path); return rasterFromQImage(img, true, false); } //----------------------------------------------------------------------------- TStroke *ToolUtils::merge(const ArrayOfStroke &a) { std::vector<TThickPoint> v; TStroke *ref = 0; int controlPoints = 0; for (UINT i = 0; i < a.size(); ++i) { ref = a[i]; assert(ref); if (!ref) continue; controlPoints = ref->getControlPointCount() - 1; for (int j = 0; j < controlPoints; ++j) v.push_back(ref->getControlPoint(j)); } if (controlPoints > 0) v.push_back(ref->getControlPoint(controlPoints)); TStroke *out = new TStroke(v); return out; } //================================================================================================ // //TToolUndo // //================================================================================================ ToolUtils::TToolUndo::TToolUndo(TXshSimpleLevel *level, const TFrameId &frameId, bool createdFrame, bool createdLevel, const TPaletteP &oldPalette) : TUndo(), m_level(level), m_frameId(frameId), m_oldPalette(oldPalette), m_col(-2), m_row(-1), m_isEditingLevel(false), m_createdFrame(createdFrame), m_createdLevel(createdLevel), m_imageId("") { m_animationSheetEnabled = Preferences::instance()->isAnimationSheetEnabled(); TTool::Application *app = TTool::getApplication(); m_isEditingLevel = app->getCurrentFrame()->isEditingLevel(); if (!m_isEditingLevel) { m_col = app->getCurrentColumn()->getColumnIndex(); m_row = app->getCurrentFrame()->getFrameIndex(); if (m_animationSheetEnabled) { m_cellsData = TTool::m_cellsData; } } if (createdFrame) { m_imageId = "TToolUndo" + toString(m_idCount++); TImageCache::instance()->add(m_imageId, level->getFrame(frameId, false), false); } } //------------------------------------------------------------------------------------------ ToolUtils::TToolUndo::~TToolUndo() { TImageCache::instance()->remove(m_imageId); } //----------------------------------------------------------------------------- void ToolUtils::TToolUndo::insertLevelAndFrameIfNeeded() const { TTool::Application *app = TTool::getApplication(); if (m_createdLevel) { TLevelSet *levelSet = app->getCurrentScene()->getScene()->getLevelSet(); if (levelSet) { levelSet->insertLevel(m_level.getPointer()); app->getCurrentScene()->notifyCastChange(); } } if (m_createdFrame) { TXsheet *xsh = app->getCurrentXsheet()->getXsheet(); TImageP img = TImageCache::instance()->get(m_imageId, false); m_level->setFrame(m_frameId, img); if (!m_isEditingLevel) { if (m_animationSheetEnabled) { int m = m_cellsData.size() / 3; for (int i = 0; i < m; i++) { int r0 = m_cellsData[i * 3]; int r1 = m_cellsData[i * 3 + 1]; int type = m_cellsData[i * 3 + 2]; TXshCell cell; if (type == 1) cell = xsh->getCell(r0 - 1, m_col); else cell = TXshCell(m_level.getPointer(), m_frameId); for (int r = r0; r <= r1; r++) xsh->setCell(r, m_col, cell); } } else { TXshCell cell(m_level.getPointer(), m_frameId); xsh->setCell(m_row, m_col, cell); } } app->getCurrentLevel()->notifyLevelChange(); } } //----------------------------------------------------------------------------- void ToolUtils::TToolUndo::removeLevelAndFrameIfNeeded() const { TTool::Application *app = TTool::getApplication(); if (m_createdFrame) { m_level->eraseFrame(m_frameId); if (!m_isEditingLevel) { TXsheet *xsh = app->getCurrentXsheet()->getXsheet(); if (m_animationSheetEnabled) { int m = m_cellsData.size() / 3; for (int i = 0; i < m; i++) { int r0 = m_cellsData[i * 3]; int r1 = m_cellsData[i * 3 + 1]; int type = m_cellsData[i * 3 + 2]; TXshCell cell; if (type == 0) cell = xsh->getCell(r0 - 1, m_col); for (int r = r0; r <= r1; r++) xsh->setCell(r, m_col, cell); } } else { xsh->clearCells(m_row, m_col); } } if (m_createdLevel) { // butta il livello TLevelSet *levelSet = app->getCurrentScene()->getScene()->getLevelSet(); if (levelSet) { levelSet->removeLevel(m_level.getPointer()); app->getCurrentScene()->notifyCastChange(); } } app->getCurrentLevel()->notifyLevelChange(); } if (m_oldPalette.getPointer()) { m_level->getPalette()->assign(m_oldPalette->clone()); app->getPaletteController()->getCurrentLevelPalette()->notifyPaletteChanged(); } } //------------------------------------------------------------------------------------------ void ToolUtils::TToolUndo::notifyImageChanged() const { TTool::Application *app = TTool::getApplication(); TXshSimpleLevel *currentSl = 0; TFrameId currentFrameId; if (app->getCurrentFrame()->isEditingLevel()) { TXshLevel *xl = app->getCurrentLevel()->getLevel(); if (!xl) return; currentSl = xl->getSimpleLevel(); currentFrameId = app->getCurrentFrame()->getFid(); } else { int row = app->getCurrentFrame()->getFrame(); int col = app->getCurrentColumn()->getColumnIndex(); if (col < 0) return; TXsheet *xsh = app->getCurrentXsheet()->getXsheet(); if (!xsh) return; TXshCell cell = xsh->getCell(row, col); currentSl = cell.getSimpleLevel(); currentFrameId = cell.getFrameId(); } if (currentSl == m_level.getPointer() && currentFrameId == m_frameId) { TTool *tool = app->getCurrentTool()->getTool(); if (tool) tool->onImageChanged(); } IconGenerator::instance()->invalidate(m_level.getPointer(), m_frameId); IconGenerator::instance()->invalidateSceneIcon(); if (m_level && m_level->getType() == PLI_XSHLEVEL) { std::string id = m_level->getImageId(m_frameId) + "_rasterized"; ImageManager::instance()->invalidate(id); } } int ToolUtils::TToolUndo::m_idCount = 0; //================================================================================================ //================================================================================================ ToolUtils::TRasterUndo::TRasterUndo(TTileSetCM32 *tiles, TXshSimpleLevel *level, const TFrameId &frameId, bool createdFrame, bool createdLevel, const TPaletteP &oldPalette) : TToolUndo(level, frameId, createdFrame, createdLevel, oldPalette), m_tiles(tiles) { } //------------------------------------------------------------------------------------------ ToolUtils::TRasterUndo::~TRasterUndo() { if (m_tiles) delete m_tiles; } //------------------------------------------------------------------------------------------ TToonzImageP ToolUtils::TRasterUndo::getImage() const { if (m_level->isFid(m_frameId)) return (TToonzImageP)m_level->getFrame(m_frameId, true); return 0; } //------------------------------------------------------------------------------------------ int ToolUtils::TRasterUndo::getSize() const { int size = sizeof(*this); size += sizeof(*(m_level.getPointer())); size += sizeof(*(m_oldPalette.getPointer())); return m_tiles ? m_tiles->getMemorySize() + size : size; } //------------------------------------------------------------------------------------------ void ToolUtils::TRasterUndo::undo() const { TTool::Application *app = TTool::getApplication(); if (!app) return; if (m_tiles && m_tiles->getTileCount() > 0) { TToonzImageP image = getImage(); if (!image) return; ToonzImageUtils::paste(image, m_tiles); ToolUtils::updateSaveBox(m_level, m_frameId); } removeLevelAndFrameIfNeeded(); app->getCurrentXsheet()->notifyXsheetChanged(); notifyImageChanged(); } //================================================================================================ //================================================================================================ ToolUtils::TFullColorRasterUndo::TFullColorRasterUndo(TTileSetFullColor *tiles, TXshSimpleLevel *level, const TFrameId &frameId, bool createdFrame, bool createdLevel, const TPaletteP &oldPalette) : TToolUndo(level, frameId, createdFrame, createdLevel, oldPalette), m_tiles(tiles) { } //----------------------------------------------------------------------------- ToolUtils::TFullColorRasterUndo::~TFullColorRasterUndo() { delete m_tiles; } //----------------------------------------------------------------------------- TRasterImageP ToolUtils::TFullColorRasterUndo::getImage() const { if (m_level->isFid(m_frameId)) return (TRasterImageP)m_level->getFrame(m_frameId, true); return 0; } //----------------------------------------------------------------------------- int ToolUtils::TFullColorRasterUndo::getSize() const { int size = sizeof(*this); size += sizeof(*(m_level.getPointer())); size += sizeof(*(m_oldPalette.getPointer())); return m_tiles ? m_tiles->getMemorySize() + size : size; } //----------------------------------------------------------------------------- void ToolUtils::TFullColorRasterUndo::undo() const { TTool::Application *app = TTool::getApplication(); if (!app) return; if (m_tiles && m_tiles->getTileCount() > 0) { TRasterImageP image = getImage(); if (!image) return; std::vector<TRect> rects = paste(image, m_tiles); int i; TRect resRect = rects[0]; for (i = 1; i < (int)rects.size(); i++) resRect += rects[i]; } removeLevelAndFrameIfNeeded(); app->getCurrentXsheet()->notifyXsheetChanged(); notifyImageChanged(); } //----------------------------------------------------------------------------- std::vector<TRect> ToolUtils::TFullColorRasterUndo::paste(const TRasterImageP &ti, const TTileSetFullColor *tileSet) const { std::vector<TRect> rects; TRasterP raster = ti->getRaster(); for (int i = 0; i < tileSet->getTileCount(); i++) { const TTileSetFullColor::Tile *tile = tileSet->getTile(i); TRasterP ras; tile->getRaster(ras); assert(!!ras); raster->copy(ras, tile->m_rasterBounds.getP00()); rects.push_back(tile->m_rasterBounds); } return rects; } //================================================================================================ //================================================================================================ ToolUtils::UndoModifyStroke::UndoModifyStroke(TXshSimpleLevel *level, const TFrameId &frameId, int strokeIndex) : TToolUndo(level, frameId), m_strokeIndex(strokeIndex) { TVectorImageP image = level->getFrame(frameId, true); assert(image); TStroke *stroke = image->getStroke(m_strokeIndex); int n = stroke->getControlPointCount(); for (int i = 0; i < n; i++) m_before.push_back(stroke->getControlPoint(i)); m_selfLoopBefore = stroke->isSelfLoop(); TTool::Application *app = TTool::getApplication(); m_row = app->getCurrentFrame()->getFrame(); m_column = app->getCurrentColumn()->getColumnIndex(); } //----------------------------------------------------------------------------- ToolUtils::UndoModifyStroke::~UndoModifyStroke() {} //----------------------------------------------------------------------------- void ToolUtils::UndoModifyStroke::onAdd() { TVectorImageP image = m_level->getFrame(m_frameId, true); assert(image); if (!image) return; TStroke *stroke = image->getStroke(m_strokeIndex); assert(stroke); int n = stroke->getControlPointCount(); for (int i = 0; i < n; i++) m_after.push_back(stroke->getControlPoint(i)); m_selfLoopAfter = stroke->isSelfLoop(); } //----------------------------------------------------------------------------- void ToolUtils::UndoModifyStroke::undo() const { TTool::Application *app = TTool::getApplication(); if (!app) return; if (app->getCurrentFrame()->isEditingScene()) { app->getCurrentColumn()->setColumnIndex(m_column); app->getCurrentFrame()->setFrame(m_row); } else app->getCurrentFrame()->setFid(m_frameId); TSelection *selection = app->getCurrentSelection()->getSelection(); if (selection) selection->selectNone(); TVectorImageP image = m_level->getFrame(m_frameId, true); assert(image); if (!image) return; QMutexLocker lock(image->getMutex()); TStroke *stroke = 0; if (image->getStrokeCount() == 1) // && image->getStroke(0)->getStyle()==SplineStyle) stroke = image->getStroke(0); else stroke = image->getStroke(m_strokeIndex); if (!stroke) return; TStroke *oldStroke = new TStroke(*stroke); stroke->reshape(&m_before[0], m_before.size()); stroke->setSelfLoop(m_selfLoopBefore); image->notifyChangedStrokes(m_strokeIndex, oldStroke); notifyImageChanged(); delete oldStroke; } //----------------------------------------------------------------------------- void ToolUtils::UndoModifyStroke::redo() const { TTool::Application *app = TTool::getApplication(); if (!app) return; if (app->getCurrentFrame()->isEditingScene()) { app->getCurrentColumn()->setColumnIndex(m_column); app->getCurrentFrame()->setFrame(m_row); } else app->getCurrentFrame()->setFid(m_frameId); TSelection *selection = app->getCurrentSelection()->getSelection(); if (selection) selection->selectNone(); TVectorImageP image = m_level->getFrame(m_frameId, true); assert(image); if (!image) return; QMutexLocker lock(image->getMutex()); TStroke *stroke = 0; if (image->getStrokeCount() == 1) //&& image->getStroke(0)->getStyle()==SplineStyle) stroke = image->getStroke(0); else stroke = image->getStroke(m_strokeIndex); if (!stroke) return; TStroke *oldStroke = new TStroke(*stroke); stroke->reshape(&m_after[0], m_after.size()); stroke->setSelfLoop(m_selfLoopAfter); image->notifyChangedStrokes(m_strokeIndex, oldStroke); delete oldStroke; app->getCurrentXsheet()->notifyXsheetChanged(); notifyImageChanged(); } //----------------------------------------------------------------------------- int ToolUtils::UndoModifyStroke::getSize() const { return (m_before.capacity() + m_after.capacity()) * sizeof(TThickPoint) + sizeof(*this) + 500; } //----------------------------------------------------------------------------- ToolUtils::UndoModifyStrokeAndPaint::UndoModifyStrokeAndPaint(TXshSimpleLevel *level, const TFrameId &frameId, int strokeIndex) : UndoModifyStroke(level, frameId, strokeIndex), m_fillInformation(0) { TVectorImageP image = level->getFrame(frameId, true); assert(image); TStroke *stroke = image->getStroke(strokeIndex); m_oldBBox = stroke->getBBox(); } //----------------------------------------------------------------------------- void ToolUtils::UndoModifyStrokeAndPaint::onAdd() { TVectorImageP image = m_level->getFrame(m_frameId, true); assert(!!image); if (!image) return; UndoModifyStroke::onAdd(); TStroke *stroke = image->getStroke(m_strokeIndex); m_fillInformation = new std::vector<TFilledRegionInf>; ImageUtils::getFillingInformationOverlappingArea(image, *m_fillInformation, m_oldBBox, stroke->getBBox()); } //----------------------------------------------------------------------------- void ToolUtils::UndoModifyStrokeAndPaint::undo() const { TTool::Application *application = TTool::getApplication(); if (!application) return; UndoModifyStroke::undo(); TRegion *reg; UINT size = m_fillInformation->size(); if (!size) { application->getCurrentXsheet()->notifyXsheetChanged(); notifyImageChanged(); return; } TVectorImageP image = m_level->getFrame(m_frameId, true); assert(!!image); if (!image) return; //image->validateRegions(); image->findRegions(); for (UINT i = 0; i < size; i++) { reg = image->getRegion((*m_fillInformation)[i].m_regionId); assert(reg); if (reg) reg->setStyle((*m_fillInformation)[i].m_styleId); } application->getCurrentXsheet()->notifyXsheetChanged(); notifyImageChanged(); } //----------------------------------------------------------------------------- ToolUtils::UndoModifyStrokeAndPaint::~UndoModifyStrokeAndPaint() { delete m_fillInformation; } //----------------------------------------------------------------------------- int ToolUtils::UndoModifyStrokeAndPaint::getSize() const { int size = m_fillInformation ? m_fillInformation->size() * sizeof(TFilledRegionInf) : 0; return UndoModifyStroke::getSize() + size; } //----------------------------------------------------------------------------- ToolUtils::UndoModifyListStroke::UndoModifyListStroke(TXshSimpleLevel *level, const TFrameId &frameId, const std::vector<TStroke *> &strokeVect) : TToolUndo(level, frameId), m_fillInformation(0) { UINT strokeNum = strokeVect.size(); TVectorImageP image = level->getFrame(frameId, true); assert(image); for (UINT i = 0; i < strokeNum; i++) { m_oldBBox += (strokeVect[i])->getBBox(); int strokeIndex = image->getStrokeIndex(strokeVect[i]); m_strokeList.push_back(new UndoModifyStroke(level, frameId, strokeIndex)); } m_beginIt = m_strokeList.begin(); m_endIt = m_strokeList.end(); } //----------------------------------------------------------------------------- ToolUtils::UndoModifyListStroke::~UndoModifyListStroke() { clearPointerContainer(m_strokeList); delete m_fillInformation; } //----------------------------------------------------------------------------- void ToolUtils::UndoModifyListStroke::onAdd() { std::list<UndoModifyStroke *>::iterator it = m_beginIt; TRectD newBBox; TVectorImageP image = m_level->getFrame(m_frameId, true); assert(!!image); if (!image) return; for (; it != m_endIt; ++it) { TStroke *s = image->getStroke((*it)->m_strokeIndex); (*it)->onAdd(); } m_fillInformation = new std::vector<TFilledRegionInf>; if (m_beginIt != m_endIt) ImageUtils::getFillingInformationOverlappingArea(image, *m_fillInformation, m_oldBBox, newBBox); } //----------------------------------------------------------------------------- void ToolUtils::UndoModifyListStroke::undo() const { TTool::Application *app = TTool::getApplication(); if (!app) return; std::list<UndoModifyStroke *>::iterator stroke_it = m_beginIt; if (m_beginIt == m_endIt) return; for (; stroke_it != m_endIt; ++stroke_it) { (*stroke_it)->undo(); } UINT size = m_fillInformation->size(); if (!size) { app->getCurrentXsheet()->notifyXsheetChanged(); app->getCurrentTool()->getTool()->notifyImageChanged(); return; } TVectorImageP image = m_level->getFrame(m_frameId, true); assert(!!image); if (!image) return; image->findRegions(); TRegion *reg; for (UINT i = 0; i < size; i++) { reg = image->getRegion((*m_fillInformation)[i].m_regionId); assert(reg); if (reg) reg->setStyle((*m_fillInformation)[i].m_styleId); } app->getCurrentXsheet()->notifyXsheetChanged(); notifyImageChanged(); } //----------------------------------------------------------------------------- void ToolUtils::UndoModifyListStroke::redo() const { TTool::Application *app = TTool::getApplication(); if (!app) return; std::list<UndoModifyStroke *>::iterator it = m_beginIt; for (; it != m_endIt; ++it) { (*it)->redo(); } app->getCurrentXsheet()->notifyXsheetChanged(); notifyImageChanged(); } //----------------------------------------------------------------------------- int ToolUtils::UndoModifyListStroke::getSize() const { int sum = 0; std::list<UndoModifyStroke *>::iterator it = m_beginIt; for (; it != m_endIt; ++it) { sum += (*it)->getSize(); } if (m_fillInformation) sum += m_fillInformation->capacity() * sizeof(TFilledRegionInf); return sum; } //============================================================================================= ToolUtils::UndoPencil::UndoPencil(TStroke *stroke, std::vector<TFilledRegionInf> *fillInformation, TXshSimpleLevel *level, const TFrameId &frameId, bool createdFrame, bool createdLevel, bool autogroup, bool autofill) : TToolUndo(level, frameId, createdFrame, createdLevel, 0), m_strokeId(stroke->getId()), m_fillInformation(fillInformation), m_autogroup(autogroup), m_autofill(autofill) { m_stroke = new TStroke(*stroke); } //----------------------------------------------------------------------------- ToolUtils::UndoPencil::~UndoPencil() { delete m_fillInformation; delete m_stroke; } //----------------------------------------------------------------------------- void ToolUtils::UndoPencil::undo() const { TTool::Application *app = TTool::getApplication(); if (!app) return; /*if(app->getCurrentFrame()->isEditingScene() && m_col!=-2 && m_row!=-1) { app->getCurrentColumn()->setColumnIndex(m_col); app->getCurrentFrame()->setFrame(m_row); } else app->getCurrentFrame()->setFid(m_frameId);*/ TVectorImageP image = m_level->getFrame(m_frameId, true); assert(image); if (!image) return; QMutexLocker sl(image->getMutex()); VIStroke *stroke = image->getStrokeById(m_strokeId); if (!stroke) return; image->deleteStroke(stroke); TSelection *selection = app->getCurrentSelection()->getSelection(); if (StrokeSelection *strokeSelection = (StrokeSelection *)selection) strokeSelection->selectNone(); UINT size = m_fillInformation->size(); TRegion *reg; for (UINT i = 0; i < size; i++) { reg = image->getRegion((*m_fillInformation)[i].m_regionId); assert(reg); if (reg) reg->setStyle((*m_fillInformation)[i].m_styleId); } removeLevelAndFrameIfNeeded(); app->getCurrentXsheet()->notifyXsheetChanged(); notifyImageChanged(); } //----------------------------------------------------------------------------- void ToolUtils::UndoPencil::redo() const { TTool::Application *app = TTool::getApplication(); if (!app) return; insertLevelAndFrameIfNeeded(); /*if(app->getCurrentFrame()->isEditingScene()) { app->getCurrentColumn()->setColumnIndex(m_col); app->getCurrentFrame()->setFrame(m_row); } else app->getCurrentFrame()->setFid(m_frameId);*/ TVectorImageP image = m_level->getFrame(m_frameId, true); if (!image) return; QMutexLocker sl(image->getMutex()); TStroke *stroke = new TStroke(*m_stroke); stroke->setId(m_strokeId); image->addStroke(stroke); if (image->isComputedRegionAlmostOnce()) image->findRegions(); if (m_autogroup && stroke->isSelfLoop()) { int index = image->getStrokeCount() - 1; image->group(index, 1); if (m_autofill) { //to avoid filling other strokes, I enter into the new stroke group int currentGroup = image->exitGroup(); image->enterGroup(index); image->selectFill(stroke->getBBox().enlarge(1, 1), 0, stroke->getStyle(), false, true, false); if (currentGroup != -1) image->enterGroup(currentGroup); else image->exitGroup(); } } app->getCurrentXsheet()->notifyXsheetChanged(); notifyImageChanged(); } //----------------------------------------------------------------------------- int ToolUtils::UndoPencil::getSize() const { return sizeof(*this) + m_fillInformation->capacity() * sizeof(TFilledRegionInf) + 500; } //============================================================================================= ToolUtils::UndoRasterPencil::UndoRasterPencil(TXshSimpleLevel *level, const TFrameId &frameId, TStroke *stroke, bool selective, bool filled, bool doAntialias, bool createdFrame, bool createdLevel, std::string primitiveName) : TRasterUndo(0, level, frameId, createdFrame, createdLevel, 0), m_selective(selective), m_filled(filled), m_doAntialias(doAntialias), m_primitiveName(primitiveName) { TRasterCM32P raster = getImage()->getRaster(); TDimension d = raster->getSize(); m_tiles = new TTileSetCM32(d); TRect rect = convert(stroke->getBBox()) + TPoint((int)(d.lx * 0.5), (int)(d.ly * 0.5)); m_tiles->add(raster, rect.enlarge(2)); m_stroke = new TStroke(*stroke); } //----------------------------------------------------------------------------- ToolUtils::UndoRasterPencil::~UndoRasterPencil() { delete m_stroke; } //----------------------------------------------------------------------------- void ToolUtils::UndoRasterPencil::redo() const { insertLevelAndFrameIfNeeded(); TToonzImageP image = getImage(); if (!image) return; ToonzImageUtils::addInkStroke(image, m_stroke, m_stroke->getStyle(), m_selective, m_filled, TConsts::infiniteRectD, m_doAntialias); ToolUtils::updateSaveBox(); TTool::getApplication()->getCurrentXsheet()->notifyXsheetChanged(); notifyImageChanged(); } //----------------------------------------------------------------------------- int ToolUtils::UndoRasterPencil::getSize() const { return TRasterUndo::getSize() + m_stroke->getControlPointCount() * sizeof(TThickPoint) + 100 + sizeof(this); } //============================================================================================= ToolUtils::UndoFullColorPencil::UndoFullColorPencil(TXshSimpleLevel *level, const TFrameId &frameId, TStroke *stroke, double opacity, bool doAntialias, bool createdFrame, bool createdLevel) : TFullColorRasterUndo(0, level, frameId, createdFrame, createdLevel, 0), m_opacity(opacity), m_doAntialias(doAntialias) { TRasterP raster = getImage()->getRaster(); TDimension d = raster->getSize(); m_tiles = new TTileSetFullColor(d); TRect rect = convert(stroke->getBBox()) + TPoint((int)(d.lx * 0.5), (int)(d.ly * 0.5)); m_tiles->add(raster, rect.enlarge(2)); m_stroke = new TStroke(*stroke); } //----------------------------------------------------------------------------- ToolUtils::UndoFullColorPencil::~UndoFullColorPencil() { delete m_stroke; } //----------------------------------------------------------------------------- void ToolUtils::UndoFullColorPencil::redo() const { insertLevelAndFrameIfNeeded(); TRasterImageP image = getImage(); if (!image) return; TRasterImageUtils::addStroke(image, m_stroke, TRectD(), m_opacity, m_doAntialias); TTool::getApplication()->getCurrentXsheet()->notifyXsheetChanged(); notifyImageChanged(); } //----------------------------------------------------------------------------- int ToolUtils::UndoFullColorPencil::getSize() const { return TFullColorRasterUndo::getSize() + m_stroke->getControlPointCount() * sizeof(TThickPoint) + 100 + sizeof(this); } //============================================================================================= // // undo class (path strokes). call it BEFORE and register it AFTER path change // ToolUtils::UndoPath::UndoPath(TStageObjectSpline *spline) : m_spline(spline) { assert(!!m_spline); const TStroke *stroke = m_spline->getStroke(); assert(stroke); int n = stroke->getControlPointCount(); for (int i = 0; i < n; i++) m_before.push_back(stroke->getControlPoint(i)); m_selfLoopBefore = stroke->isSelfLoop(); } ToolUtils::UndoPath::~UndoPath() { } void ToolUtils::UndoPath::onAdd() { assert(!!m_spline); const TStroke *stroke = m_spline->getStroke(); assert(stroke); int n = stroke->getControlPointCount(); for (int i = 0; i < n; i++) m_after.push_back(stroke->getControlPoint(i)); } void ToolUtils::UndoPath::undo() const { assert(!!m_spline); TTool::Application *app = TTool::getApplication(); TSelection *selection = app->getCurrentSelection()->getSelection(); if (selection) selection->selectNone(); TStroke *stroke = new TStroke(*m_spline->getStroke()); stroke->reshape(&m_before[0], m_before.size()); stroke->setSelfLoop(m_selfLoopBefore); m_spline->setStroke(stroke); if (!app->getCurrentObject()->isSpline()) return; TStageObjectId currentObjectId = app->getCurrentObject()->getObjectId(); TStageObject *stageObject = app->getCurrentXsheet()->getXsheet()->getStageObject(currentObjectId); if (stageObject->getSpline()->getId() == m_spline->getId()) app->getCurrentObject()->setSplineObject(m_spline); app->getCurrentTool()->getTool()->notifyImageChanged(); } void ToolUtils::UndoPath::redo() const { assert(!!m_spline); TTool::Application *app = TTool::getApplication(); TSelection *selection = app->getCurrentSelection()->getSelection(); if (selection) selection->selectNone(); TStroke *stroke = new TStroke(*m_spline->getStroke()); stroke->reshape(&m_after[0], m_after.size()); stroke->setSelfLoop(m_selfLoopBefore); m_spline->setStroke(stroke); if (!app->getCurrentObject()->isSpline()) return; TStageObjectId currentObjectId = app->getCurrentObject()->getObjectId(); TStageObject *stageObject = app->getCurrentXsheet()->getXsheet()->getStageObject(currentObjectId); if (stageObject->getSpline()->getId() == m_spline->getId()) app->getCurrentObject()->setSplineObject(m_spline); app->getCurrentTool()->getTool()->notifyImageChanged(); } int ToolUtils::UndoPath::getSize() const { return sizeof(*this) + 500; } //============================================================================================= // // UndoControlPointEditor // ToolUtils::UndoControlPointEditor::UndoControlPointEditor(TXshSimpleLevel *level, const TFrameId &frameId) : TToolUndo(level, frameId), m_isStrokeDelete(false) { TVectorImageP image = level->getFrame(frameId, true); assert(image); if (!image) return; TTool::Application *app = TTool::getApplication(); if (!app) return; m_row = app->getCurrentFrame()->getFrame(); m_column = app->getCurrentColumn()->getColumnIndex(); } ToolUtils::UndoControlPointEditor::~UndoControlPointEditor() { deleteVIStroke(m_oldStroke.second); if (!m_isStrokeDelete) deleteVIStroke(m_newStroke.second); } void ToolUtils::UndoControlPointEditor::onAdd() { TVectorImageP image = m_level->getFrame(m_frameId, true); assert(image); if (!image) return; QMutexLocker lock(image->getMutex()); if (m_isStrokeDelete) return; addNewStroke(m_oldStroke.first, image->getVIStroke(m_oldStroke.first)); } void ToolUtils::UndoControlPointEditor::addOldStroke(int index, VIStroke *vs) { VIStroke *s = cloneVIStroke(vs); m_oldStroke = std::make_pair(index, s); } void ToolUtils::UndoControlPointEditor::addNewStroke(int index, VIStroke *vs) { VIStroke *s = cloneVIStroke(vs); m_newStroke = std::make_pair(index, s); } void ToolUtils::UndoControlPointEditor::undo() const { TTool::Application *app = TTool::getApplication(); if (!app) return; if (app->getCurrentFrame()->isEditingScene()) { app->getCurrentColumn()->setColumnIndex(m_column); app->getCurrentFrame()->setFrame(m_row); } else app->getCurrentFrame()->setFid(m_frameId); TSelection *selection = app->getCurrentSelection()->getSelection(); if (selection) selection->selectNone(); TVectorImageP image = m_level->getFrame(m_frameId, true); assert(image); if (!image) return; QMutexLocker lock(image->getMutex()); if (!m_isStrokeDelete) image->removeStroke(m_newStroke.first, false); UINT i = 0; VIStroke *s = cloneVIStroke(m_oldStroke.second); image->insertStrokeAt(s, m_oldStroke.first); if (image->isComputedRegionAlmostOnce()) image->findRegions(); //in futuro togliere. Serve perche' la removeStrokes, se gli si dice //di non calcolare le regioni, e' piu' veloce ma poi chrash tutto app->getCurrentXsheet()->notifyXsheetChanged(); notifyImageChanged(); } void ToolUtils::UndoControlPointEditor::redo() const { TTool::Application *app = TTool::getApplication(); if (!app) return; if (app->getCurrentFrame()->isEditingScene()) { app->getCurrentColumn()->setColumnIndex(m_column); app->getCurrentFrame()->setFrame(m_row); } else app->getCurrentFrame()->setFid(m_frameId); TSelection *selection = app->getCurrentSelection()->getSelection(); if (selection) selection->selectNone(); TVectorImageP image = m_level->getFrame(m_frameId, true); assert(image); if (!image) return; QMutexLocker lock(image->getMutex()); image->removeStroke(m_oldStroke.first, false); if (!m_isStrokeDelete) { VIStroke *s = cloneVIStroke(m_newStroke.second); image->insertStrokeAt(s, m_newStroke.first); } if (image->isComputedRegionAlmostOnce()) image->findRegions(); //in futuro togliere. Serve perche' la removeStrokes, se gli si dice //di non calcolare le regioni, e' piu' veloce ma poi chrash tutto app->getCurrentXsheet()->notifyXsheetChanged(); notifyImageChanged(); } //============================================================================================= // // Menu // ToolUtils::DragMenu::DragMenu() : QMenu() { } //----------------------------------------------------------------------------- QAction *ToolUtils::DragMenu::exec(const QPoint &p, QAction *action) { QAction *execAct = QMenu::exec(p, action); if (execAct) return execAct; return defaultAction(); } //--------------------------------------------------------------------------------------------- void ToolUtils::DragMenu::mouseReleaseEvent(QMouseEvent *e) { QMenu::mouseReleaseEvent(e); hide(); } //============================================================================================= // // ColumChooserMenu // ToolUtils::ColumChooserMenu::ColumChooserMenu(TXsheet *xsh, const std::vector<int> &columnIndexes) : DragMenu() { int size = columnIndexes.size(); int i; for (i = size - 1; i >= 0; i--) { int index = columnIndexes[i]; TStageObjectId id = TStageObjectId::ColumnId(index); TStageObject *stageObject = xsh->getStageObject(id); QString cmdStr = "Column " + QString::fromStdString(stageObject->getName()); QAction *act = new QAction(cmdStr, this); act->setData(index); addAction(act); if (size - 1 == i) { setDefaultAction(act); setActiveAction(act); } } } //--------------------------------------------------------------------------------------------- int ToolUtils::ColumChooserMenu::execute() { QAction *executeAct = exec(QCursor::pos()); return (!executeAct) ? -1 : executeAct->data().toInt(); } //--------------------------------------------------------------------------------------------- double ToolUtils::ConeSubVolume::compute(double cover) { double x = (10 * tcrop(cover, -1.0, 1.0)) + 10; assert(0 <= x && x <= 20); int i = tfloor(x); if (i == 20) return m_values[i]; else //Interpolazione lineare. return (-(x - (i + 1)) * m_values[i]) - (-(x - i) * m_values[i + 1]); } const double ToolUtils::ConeSubVolume::m_values[] = { 1.0, 0.99778, 0.987779, 0.967282, 0.934874, 0.889929, 0.832457, 0.763067, 0.683002, 0.594266, 0.5, 0.405734, 0.316998, 0.236933, 0.167543, 0.110071, 0.0651259, 0.0327182, 0.0122208, 0.00221986, 0.0}; //--------------------------------------------------------------------------------------------- void ToolUtils::drawBalloon( const TPointD &pos, std::string text, const TPixel32 &color, TPoint delta, bool isPicking, std::vector<TRectD> *otherBalloons) { QString qText = QString::fromStdString(text); QFont font("Arial", 10); // ,QFont::Bold); QFontMetrics fm(font); QRect textRect = fm.boundingRect(qText); int baseLine = -textRect.top(); int mrg = 3; // avoid other balloons if (otherBalloons) { double pixelSize = sqrt(tglGetPixelSize2()); std::vector<TRectD> &balloons = *otherBalloons; int n = (int)balloons.size(); TDimensionD balloonSize(pixelSize * (textRect.width() + mrg * 2), pixelSize * (textRect.height() + mrg * 2)); TRectD balloonRect; for (;;) { balloonRect = TRectD(pos + TPointD(delta.x * pixelSize, delta.y * pixelSize), balloonSize); int i = 0; while (i < n && !balloons[i].overlaps(balloonRect)) i++; if (i == n) break; double y = balloons[i].y0 - balloonSize.ly - 2 * mrg * pixelSize; delta.y = (y - pos.y) / pixelSize; } balloons.push_back(balloonRect); } textRect.moveTo(qMax(delta.x, 10 + mrg), qMax(mrg + 2, -delta.y - baseLine)); int y = textRect.top() + baseLine; int x0 = textRect.left() - mrg; int x1 = textRect.right() + mrg; int y0 = textRect.top() - mrg; int y1 = textRect.bottom() + mrg; double pixelSize = sqrt(tglGetPixelSize2()); if (isPicking) { TTool::Viewer *viewer = TTool::getApplication()->getCurrentTool()->getTool()->getViewer(); if (viewer->is3DView()) { double x0 = pos.x + textRect.left() * pixelSize, y0 = pos.y + delta.y * pixelSize; double x1 = x0 + pixelSize * textRect.width(); double y1 = y0 + pixelSize * textRect.height(); double d = pixelSize * 5; glRectd(x0 - d, y0 - d, x1 + d, y1 + d); } else { TPoint posBalloon = viewer->worldToPos(pos); double d = 5; double x0 = posBalloon.x + textRect.left() - d; double y0 = posBalloon.y + delta.y - d; double x1 = x0 + textRect.width() + d; double y1 = y0 + textRect.height() + d; TPoint p1(x0, y0); TPoint p2(x1, y0); TPoint p3(x0, y1); TPoint p4(x1, y1); TPointD w1(viewer->winToWorld(p1)); TPointD w2(viewer->winToWorld(p2)); TPointD w3(viewer->winToWorld(p3)); TPointD w4(viewer->winToWorld(p4)); glBegin(GL_QUADS); glVertex2d(w1.x, w1.y); glVertex2d(w2.x, w2.y); glVertex2d(w4.x, w4.y); glVertex2d(w3.x, w3.y); glEnd(); } return; } QSize size( textRect.width() + textRect.left() + mrg, qMax(textRect.bottom() + mrg, y + delta.y) + 3); QImage label(size.width(), size.height(), QImage::Format_ARGB32); label.fill(Qt::transparent); // label.fill(qRgba(200,200,0,200)); QPainter p(&label); p.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); p.setBrush(QColor(color.r, color.g, color.b, color.m)); p.setPen(Qt::NoPen); QPainterPath pp; pp.moveTo(x0, y - 8); pp.lineTo(0, y + delta.y); pp.lineTo(x0, y); /* bordi arrotondati int arcSize = 10; pp.arcTo(x0,y1-arcSize,arcSize,arcSize,180,90); pp.arcTo(x1-arcSize,y1-arcSize,arcSize,arcSize,270,90); pp.arcTo(x1-arcSize,y0,arcSize,arcSize,0,90); pp.arcTo(x0,y0,arcSize,arcSize,90,90); */ // bordi acuti pp.lineTo(x0, y1); pp.lineTo(x1, y1); pp.lineTo(x1, y0); pp.lineTo(x0, y0); pp.closeSubpath(); p.drawPath(pp); p.setPen(Qt::black); p.setFont(font); p.drawText(textRect, Qt::AlignCenter | Qt::TextDontClip, qText); QImage texture = QGLWidget::convertToGLFormat(label); glRasterPos2f(pos.x, pos.y); glBitmap(0, 0, 0, 0, 0, -size.height() + (y + delta.y), NULL); // glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDrawPixels(texture.width(), texture.height(), GL_RGBA, GL_UNSIGNED_BYTE, texture.bits()); glDisable(GL_BLEND); glColor3d(0, 0, 0); } //--------------------------------------------------------------------------------------------- void ToolUtils::drawHook( const TPointD &pos, ToolUtils::HookType type, bool highlighted, bool onionSkin) { int r = 10, d = r + r; QImage image(d, d, QImage::Format_ARGB32); image.fill(Qt::transparent); // image.fill(qRgba(200,200,0,200)); QPainter painter(&image); // painter.setRenderHints(QPainter::Antialiasing|QPainter::TextAntialiasing); int matte = onionSkin ? 100 : 255; QColor color(0, 0, 0, matte); if (highlighted) color = QColor(0, 175, 175, matte); if (type == NormalHook || type == PassHookA) { painter.setPen(QPen(QColor(255, 255, 255, matte), 3)); painter.drawEllipse(5, 5, d - 10, d - 10); painter.setPen(color); painter.drawEllipse(5, 5, d - 10, d - 10); } else if (type == OtherLevelHook) { QColor color(0, 200, 200, 200); //painter.setPen(QPen(Qt::white,3)); //painter.drawEllipse(5,5,d-10,d-10); painter.setPen(Qt::white); painter.setBrush(color); painter.drawEllipse(6, 6, d - 12, d - 12); } if (type == NormalHook || type == PassHookB) { painter.setPen(QPen(QColor(255, 255, 255, matte), 3)); painter.drawLine(0, r, d, r); painter.drawLine(r, 0, r, d); painter.setPen(color); painter.drawLine(0, r, d, r); painter.drawLine(r, 0, r, d); } QImage texture = QGLWidget::convertToGLFormat(image); glRasterPos2f(pos.x, pos.y); glBitmap(0, 0, 0, 0, -r, -r, NULL); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDrawPixels(texture.width(), texture.height(), GL_RGBA, GL_UNSIGNED_BYTE, texture.bits()); glDisable(GL_BLEND); } //--------------------------------------------------------------------------------------------- bool ToolUtils::isJustCreatedSpline(TImage *image) { TVectorImageP vi = image; if (!vi) return false; if (vi->getStrokeCount() != 1) return false; TStroke *stroke = vi->getStroke(0); if (stroke->getControlPointCount() != 3) return false; TPointD p0 = stroke->getControlPoint(0); TPointD p1 = stroke->getControlPoint(1); TPointD p2 = stroke->getControlPoint(2); double d = 30.0; return p0 == TPointD(-d, 0) && p1 == TPointD(0, 0) && p2 == TPointD(d, 0); } //--------------------------------------------------------------------------------------------- TRectD ToolUtils::interpolateRect(const TRectD &rect1, const TRectD &rect2, double t) { assert(rect1.x0 <= rect1.x1); assert(rect1.y0 <= rect1.y1); assert(rect2.x0 <= rect2.x1); assert(rect2.y0 <= rect2.y1); return TRectD( rect1.x0 + (rect2.x0 - rect1.x0) * t, rect1.y0 + (rect2.y0 - rect1.y0) * t, rect1.x1 + (rect2.x1 - rect1.x1) * t, rect1.y1 + (rect2.y1 - rect1.y1) * t); } //----------------------------------------------------------------------------- /* bool ToolUtils::isASubRegion(int reg, const std::vector<TRegion*> &regions) { TRegion *region=regions[reg]; for (int i=0; i<(int)regions.size(); i++) { if(i!=reg) if(region->isSubRegionOf(*regions[i])) return true; } return false; } */ //----------------------------------------------------------------------------- TRectD ToolUtils::getBounds(const std::vector<TThickPoint> &points, double maxThickness) { TThickPoint p = points[0]; double radius = maxThickness == 0 ? p.thick * 0.5 : maxThickness * 0.5; TRectD rect(p - TPointD(radius, radius), p + TPointD(radius, radius)); int i; for (i = 1; i < (int)points.size(); i++) { p = points[i]; radius = maxThickness == 0 ? p.thick * 0.5 : maxThickness * 0.5; rect = rect + TRectD(p - TPointD(radius, radius), p + TPointD(radius, radius)); } return rect; } //----------------------------------------------------------------------------- /* template <typename PIXEL> TRasterPT<PIXEL> ToolUtils::rotate90(const TRasterPT<PIXEL> &ras, bool toRight) { if(!ras) return 0; int lx=ras->getLy(); int ly=ras->getLx(); TRasterPT<PIXEL> workRas(lx,ly); for (int i=0; i<ras->getLx(); i++) { for (int j=0; j<ras->getLy(); j++) { if(toRight) workRas->pixels(ly-1-i)[j]=ras->pixels(j)[i]; else workRas->pixels(i)[lx-1-j]=ras->pixels(j)[i]; } } return workRas; }*/
28.853052
194
0.601887
[ "vector", "transform" ]
d519c24f80d32a3aa2dc6d6234d95d539dfc2c81
3,658
cpp
C++
src/OpenLoco/Paint/PaintTree.cpp
GalBr/OpenLoco
0592f3c0da4a9c704a19fa2157df60b8294a8344
[ "MIT" ]
null
null
null
src/OpenLoco/Paint/PaintTree.cpp
GalBr/OpenLoco
0592f3c0da4a9c704a19fa2157df60b8294a8344
[ "MIT" ]
null
null
null
src/OpenLoco/Paint/PaintTree.cpp
GalBr/OpenLoco
0592f3c0da4a9c704a19fa2157df60b8294a8344
[ "MIT" ]
null
null
null
#include "PaintTree.h" #include "../Config.h" #include "../Graphics/Colour.h" #include "../Map/Tile.h" #include "../Objects/ObjectManager.h" #include "../Objects/TreeObject.h" #include "../Ui.h" #include "Paint.h" using namespace OpenLoco::Interop; using namespace OpenLoco::Ui::ViewportInteraction; namespace OpenLoco::Paint { constexpr std::array<uint8_t, 6> _50076A = { 3, 0, 1, 2, 1, 4 }; constexpr std::array<bool, 5> _500770 = { true, true, false, false, true }; constexpr std::array<Map::Pos2, 4> kTreeQuadrantOffset = { Map::Pos2{ 7, 7 }, Map::Pos2{ 7, 23 }, Map::Pos2{ 23, 23 }, Map::Pos2{ 23, 7 }, }; // 0x004BAEDA void paintTree(PaintSession& session, const Map::TreeElement& elTree) { session.setItemType(InteractionItem::tree); const auto* treeObj = ObjectManager::get<TreeObject>(elTree.treeObjectId()); const uint8_t viewableRotation = (session.getRotation() + elTree.rotation()) & 0x3; const uint32_t treeFrameNum = (viewableRotation % treeObj->num_rotations) + elTree.unk5l() * treeObj->num_rotations; uint8_t season = elTree.season(); const uint8_t altSeason = elTree.hasSnow() ? 1 : 0; bool hasImage2 = false; uint32_t imageId2 = 0; if (elTree.unk7l() != 7) { hasImage2 = true; uint32_t edx = (elTree.unk7l()) + 1; season = _50076A[season]; auto image2Season = elTree.season(); if (!_500770[season]) { image2Season = season; season = elTree.season(); edx = (~edx) & 0b111; } // Unlikely to do anything as no remap flag set edx = edx << 26; imageId2 = edx | (treeFrameNum + treeObj->sprites[altSeason][image2Season]); } const auto seasonBaseImageId = treeObj->sprites[altSeason][season]; std::optional<uint32_t> shadowImageId = std::nullopt; if (treeObj->flags & TreeObjectFlags::hasShadow) { shadowImageId = Gfx::recolourTranslucent(treeObj->shadowImageOffset + treeFrameNum + seasonBaseImageId, ExtColour::unk32); } const uint8_t quadrant = (elTree.quadrant() + session.getRotation()) % 4; const auto imageOffset = Map::Pos3(kTreeQuadrantOffset[quadrant].x, kTreeQuadrantOffset[quadrant].y, elTree.baseHeight()); const int16_t boundBoxSizeZ = std::min(elTree.clearZ() - elTree.baseZ(), 32) * Map::kSmallZStep - 3; uint32_t imageId1 = treeFrameNum + seasonBaseImageId; if (treeObj->colours != 0) { // No vanilla object has this property set const auto colour = static_cast<Colour>(elTree.colour()); imageId2 = Gfx::recolour(imageId2, colour); imageId1 = Gfx::recolour(imageId1, colour); } if (elTree.isGhost()) { session.setItemType(InteractionItem::noInteraction); imageId2 = Gfx::applyGhostToImage(imageId2); imageId1 = Gfx::applyGhostToImage(imageId1); } if (shadowImageId) { if (session.getContext()->zoom_level <= 1) { session.addToPlotListAsParent(*shadowImageId, imageOffset, imageOffset, { 18, 18, 1 }); } } session.addToPlotListAsParent(imageId1, imageOffset, imageOffset + Map::Pos3(0, 0, 2), { 2, 2, boundBoxSizeZ }); if (hasImage2) { session.addToPlotListAsChild(imageId2, imageOffset, imageOffset + Map::Pos3(0, 0, 2), { 2, 2, boundBoxSizeZ }); } } }
35.173077
134
0.594314
[ "object" ]
d51b18ae243d515f5c56270b703e0eb42035bbed
12,707
cpp
C++
Core/src/audio/RtAudioIO.cpp
delude88/ds-native-webclient
ae83e7897df2d10249219887bc0c3cfd50146808
[ "MIT" ]
null
null
null
Core/src/audio/RtAudioIO.cpp
delude88/ds-native-webclient
ae83e7897df2d10249219887bc0c3cfd50146808
[ "MIT" ]
null
null
null
Core/src/audio/RtAudioIO.cpp
delude88/ds-native-webclient
ae83e7897df2d10249219887bc0c3cfd50146808
[ "MIT" ]
null
null
null
// // Created by Tobias Hegemann on 06.11.21. // #include "RtAudioIO.h" #include "../utils/cp1252_to_utf8.h" #include <cstddef> #include <memory> #include <utility> #include <plog/Log.h> [[maybe_unused]] RtAudioIO::RtAudioIO(std::shared_ptr<DigitalStage::Api::Client> client) : AudioIO(std::move(client)), is_running_(true) { } RtAudioIO::~RtAudioIO() { PLOGD << "Stopping rt audio"; is_running_ = false; rt_audio_.reset(); } std::vector<nlohmann::json> RtAudioIO::enumerateRtDevices(RtAudio::Api rt_api, const std::shared_ptr<DigitalStage::Api::Store>& store) { PLOGD << "enumerateRtDevices"; auto sound_cards = std::vector<nlohmann::json>(); auto rt_audio = std::make_unique<RtAudio>(rt_api); const std::string driver = RtAudio::getApiName(rt_api); unsigned int devices = rt_audio->getDeviceCount(); RtAudio::DeviceInfo info; for (int i = 0; i < devices; i++) { info = rt_audio->getDeviceInfo(i); if (info.inputChannels > 0) { sound_cards.push_back(getDevice(std::to_string(i), driver, "input", info, store)); } if (info.outputChannels > 0) { sound_cards.push_back(getDevice(std::to_string(i), driver, "output", info, store)); } } return sound_cards; } nlohmann::json RtAudioIO::getDevice(const std::string &uuid, // NOLINT(bugprone-easily-swappable-parameters) const std::string &driver, const std::string &type, const RtAudio::DeviceInfo &info, const std::shared_ptr<DigitalStage::Api::Store>& store) { nlohmann::json sound_card; sound_card["audioDriver"] = driver; sound_card["audioEngine"] = "rtaudio"; sound_card["type"] = type; sound_card["uuid"] = uuid; sound_card["label"] = CP1252_to_UTF8(info.name); sound_card["isDefault"] = type == "input" ? info.isDefaultInput : info.isDefaultOutput; sound_card["sampleRates"] = info.sampleRates; sound_card["online"] = true; const auto local_device_id = store->getLocalDeviceId(); const auto existing = local_device_id ? store->getSoundCardByDeviceAndDriverAndTypeAndLabel( *store->getLocalDeviceId(), driver, type, info.name ) : std::nullopt; if (!existing) { sound_card["sampleRate"] = info.preferredSampleRate; sound_card["bufferSize"] = 512; } std::vector<DigitalStage::Types::Channel> channels; auto channel_count = type == "input" ? info.inputChannels : info.outputChannels; for (int i = 0; i < channel_count; ++i) { if (existing && existing->channels.size() >= i) { channels.push_back(existing->channels[i]); } else { DigitalStage::Types::Channel channel; channel.label = "Kanal " + std::to_string(i + 1); channel.active = false; channels.push_back(channel); } } sound_card["channels"] = channels; return sound_card; } std::vector<nlohmann::json> RtAudioIO::enumerateDevices(std::shared_ptr<DigitalStage::Api::Store> store) { PLOGD << "enumerateDevices"; auto sound_cards = std::vector<nlohmann::json>(); // Fetch existing std::vector<RtAudio::Api> compiled_apis; RtAudio::getCompiledApi(compiled_apis); for (const auto &item: compiled_apis) { auto found_sound_cards = enumerateRtDevices(item, store); sound_cards.insert(sound_cards.end(), found_sound_cards.begin(), found_sound_cards.end()); } return sound_cards; } void RtAudioIO::initAudio() { std::lock_guard<std::mutex> guard{mutex_}; if (!is_running_) { return; } // Capture all dependencies auto store_ptr = client_->getStore(); if(store_ptr.expired()) { return; } auto store = store_ptr.lock(); auto local_device = store->getLocalDevice(); if (local_device && local_device->audioDriver) { auto input_sound_card = store->getInputSoundCard(); auto output_sound_card = store->getOutputSoundCard(); unsigned int sample_rate = 48000; buffer_size_ = 512; /** * Input sound card handling */ bool has_input = false; if (input_sound_card && input_sound_card->audioEngine == "rtaudio" && input_sound_card->online && local_device->sendAudio) { has_input = true; PLOGD << "Got input sound card"; sample_rate = input_sound_card->sampleRate; buffer_size_ = input_sound_card->bufferSize; input_parameters_.deviceId = std::stoi(input_sound_card->uuid); input_parameters_.nChannels = input_sound_card->channels.size(); // Sync enabled channels for (int channel = 0; channel < input_sound_card->channels.size(); channel++) { if (input_sound_card->channels[channel].active) { publishChannel(channel); } else if (published_channels_[channel]) { unPublishChannel(channel); } } } else { unPublishAll(); } /** * Output sound card handling */ num_total_output_channels_ = 0; output_channels_.fill(false); bool has_output = false; if (output_sound_card && output_sound_card->audioEngine == "rtaudio" && output_sound_card->online && local_device->receiveAudio) { has_output = true; PLOGD << "Got output sound card"; sample_rate = output_sound_card->sampleRate; buffer_size_ = output_sound_card->bufferSize; output_parameters_.deviceId = std::stoi(output_sound_card->uuid); output_parameters_.nChannels = output_sound_card->channels.size(); num_total_output_channels_ = output_sound_card->channels.size(); num_output_channels_ = 0; for (auto i = 0; i < output_sound_card->channels.size(); i++) { if (output_sound_card->channels.at(i).active) { output_channels_[i] = true; num_output_channels_++; } } } if (has_input || has_output) { RtAudio::StreamOptions options; options.flags = RTAUDIO_NONINTERLEAVED | RTAUDIO_SCHEDULE_REALTIME; options.priority = 1; auto callback = [](void *output, // NOLINT(bugprone-easily-swappable-parameters) void *input, unsigned int bufferSize, double /*streamTime*/, RtAudioStreamStatus status, void *userData) { auto *context = static_cast<RtAudioIO *>(userData); if (context->mutex_.try_lock()) { auto *output_buffer = static_cast<float *>(output); auto *input_buffer = static_cast<float *>(input); if (status) { if (status & RTAUDIO_INPUT_OVERFLOW) { PLOGW << "Input data was discarded because of an overflow condition at the driver"; } if (status & RTAUDIO_OUTPUT_UNDERFLOW) { PLOGW << "The output buffer ran low, likely causing a gap in the output sound"; } } if (input_buffer && output_buffer) { // Duplex std::unordered_map<std::string, float *> input_channels; for (const auto &item: context->input_channel_mapping_) { input_channels[item.second] = &input_buffer[static_cast<size_t>(item.first) * bufferSize]; } auto **out = static_cast<float **>(malloc(bufferSize * context->num_output_channels_ * sizeof(float *))); for (int output_channel = 0; output_channel < context->num_output_channels_; output_channel++) { out[output_channel] = static_cast<float *>(malloc(bufferSize * sizeof(float))); } context->onDuplex(input_channels, out, context->num_output_channels_, bufferSize); unsigned int relative_channel = 0; for (std::size_t channel = 0; channel < context->num_total_output_channels_; channel++) { if (context->output_channels_[channel]) { memcpy(&output_buffer[channel * bufferSize], out[relative_channel], bufferSize * sizeof(float)); relative_channel++; } } free(out); } else if (input_buffer) { // Capture only for (const auto &item: context->input_channel_mapping_) { context->onCapture(item.second, &input_buffer[item.first * bufferSize], bufferSize); } } else if (output_buffer) { // Playback only auto **out = static_cast<float **>(malloc(bufferSize * context->num_output_channels_ * sizeof(float *))); for (int output_channel = 0; output_channel < context->num_output_channels_; output_channel++) { out[output_channel] = static_cast<float *>(malloc(bufferSize * sizeof(float))); } context->onPlayback(out, context->num_output_channels_, bufferSize); unsigned int relative_channel = 0; for (std::size_t channel = 0; channel < context->num_total_output_channels_; channel++) { if (context->output_channels_[channel]) { memcpy(&output_buffer[channel * bufferSize], out[relative_channel], bufferSize * sizeof(float)); relative_channel++; } } free(out); } context->mutex_.unlock(); } else { PLOGW << "Not owning lock"; } return 0; }; if (is_running_) { try { /** * Audio driver handling */ RtAudio::Api api = RtAudio::getCompiledApiByName(*local_device->audioDriver); PLOGD << "(Re)init with audio driver " << *local_device->audioDriver; rt_audio_ = std::make_unique<RtAudio>(std::move(api)); rt_audio_->openStream( has_output ? &output_parameters_ : nullptr, has_input ? &input_parameters_ : nullptr, RTAUDIO_FLOAT32, // Always prefer the output sound card settings sample_rate, &buffer_size_, callback, this, &options ); rt_audio_->startStream(); PLOGD << "Started Audio IO"; } catch (RtAudioError &e) { PLOGE << e.getMessage(); rt_audio_.reset(); } } } else { PLOGI << "Stopped Audio IO - no input or output sound card selected"; } } else { PLOGD << "Got invalid local_device or audio driver is missing"; } } void RtAudioIO::setAudioDriver(const std::string & /*audio_driver*/) { PLOGD << "setAudioDriver()"; initAudio(); } void RtAudioIO::setInputSoundCard(const DigitalStage::Types::SoundCard & /*sound_card*/, bool /*start*/) { PLOGD << "setInputSoundCard()"; initAudio(); } void RtAudioIO::setOutputSoundCard(const DigitalStage::Types::SoundCard & /*sound_card*/, bool /*start*/) { PLOGD << "setOutputSoundCard()"; initAudio(); } void RtAudioIO::startSending() { PLOGD << "startSending()"; initAudio(); } void RtAudioIO::stopSending() { PLOGD << "RtAudstopSending()"; initAudio(); } void RtAudioIO::startReceiving() { PLOGD << "startReceiving()"; initAudio(); } void RtAudioIO::stopReceiving() { PLOGD << "stopReceiving()"; initAudio(); } void RtAudioIO::restart() { PLOGD << "restart()"; initAudio(); } [[maybe_unused]] unsigned int RtAudioIO::getLowestBufferSize(std::optional<RtAudio::StreamParameters> inputParameters, std::optional<RtAudio::StreamParameters> outputParameters, unsigned int sample_rate) { PLOGD << "getLowestBufferSize"; unsigned int buffer_size = 256; // = default if (inputParameters || outputParameters) { RtAudio::StreamOptions options; options.flags = RTAUDIO_MINIMIZE_LATENCY | RTAUDIO_SCHEDULE_REALTIME; options.priority = 1; try { rt_audio_->openStream( outputParameters ? &(*outputParameters) : nullptr, inputParameters ? &(*inputParameters) : nullptr, RTAUDIO_FLOAT32, // Always prefer the output sound card settings sample_rate, &buffer_size, // Will be ignored, since RTAUDIO_SCHEDULE_REALTIME is set nullptr, nullptr, &options ); rt_audio_->closeStream(); } catch (RtAudioError &e) { PLOGE << "Error occurred while opening stream to determine lowest buffer size" << e.getMessage(); } buffer_size--; buffer_size |= buffer_size >> 1; buffer_size |= buffer_size >> 2; buffer_size |= buffer_size >> 4; buffer_size |= buffer_size >> 8; buffer_size |= buffer_size >> 16; buffer_size++; } return buffer_size; }
36.831884
138
0.616511
[ "vector" ]
d51fdff7094a1efbd41a83bbda6d349c9723c9fa
55,962
cpp
C++
source/octoon-hal/OpenGL 20/gl20_types.cpp
naeioi/octoon
e32152fe4730fa609def41114613dbe067d31276
[ "MIT" ]
null
null
null
source/octoon-hal/OpenGL 20/gl20_types.cpp
naeioi/octoon
e32152fe4730fa609def41114613dbe067d31276
[ "MIT" ]
null
null
null
source/octoon-hal/OpenGL 20/gl20_types.cpp
naeioi/octoon
e32152fe4730fa609def41114613dbe067d31276
[ "MIT" ]
null
null
null
#include "gl20_types.h" #include <cstring> #include <cstdarg> namespace octoon { namespace hal { GLboolean GL20Types::_gl20init = GL_FALSE; GLboolean GL20Types::_gl20Features[GL20_RangeSize]; bool GL20Types::setup() noexcept { if (_gl20init) return true; std::memset(_gl20Features, GL_FALSE, sizeof(_gl20Features)); const GLubyte* extension = glGetString(GL_EXTENSIONS); if (!extension) return false; std::size_t extensionLength = std::strlen((const char*)extension); if (extensionLength == 0) return false; const char* offset = (char*)extension; for (;;) { const char* pos = std::strstr(offset, " "); if (!pos) { std::size_t length = std::strlen(offset); if (length == 0) break; pos = offset + length; } std::intptr_t length = pos - offset; if (length < 0) return false; const char* src = pos - length; if (strncmp(src, "GL_OES_required_internalformat", length) == 0) _gl20Features[GL20Features::GL20_OES_required_internalformat] = GL_TRUE; else if (strncmp(src, "GL_EXT_read_format_bgra", length) == 0) _gl20Features[GL20Features::GL20_EXT_read_format_bgra] = GL_TRUE; else if (strncmp(src, "GL_ARM_rgba8", length) == 0) _gl20Features[GL20Features::GL20_ARM_rgba8] = GL_TRUE; else if (strncmp(src, "GL_OES_rgb8_rgba8", length) == 0) _gl20Features[GL20Features::GL20_OES_rgb8_rgba8] = GL_TRUE; else if (strncmp(src, "GL_EXT_texture_format_BGRA8888", length) == 0) _gl20Features[GL20Features::GL20_EXT_texture_format_BGRA8888] = GL_TRUE; else if (strncmp(src, "GL_APPLE_texture_format_BGRA8888", length) == 0) _gl20Features[GL20Features::GL20_APPLE_texture_format_BGRA8888] = GL_TRUE; else if (strncmp(src, "GL_EXT_sRGB", length) == 0) _gl20Features[GL20Features::GL20_EXT_sRGB] = GL_TRUE; else if (strncmp(src, "GL_NV_sRGB_formats", length) == 0) _gl20Features[GL20Features::GL20_NV_sRGB_formats] = GL_TRUE; else if (strncmp(src, "GL_EXT_texture_rg", length) == 0) _gl20Features[GL20Features::GL20_EXT_texture_rg] = GL_TRUE; else if (strncmp(src, "GL_EXT_texture_norm16", length) == 0) _gl20Features[GL20Features::GL20_EXT_texture_norm16] = GL_TRUE; else if (strncmp(src, "GL_OES_texture_half_float", length) == 0) _gl20Features[GL20Features::GL20_OES_texture_half_float] = GL_TRUE; else if (strncmp(src, "GL_EXT_color_buffer_half_float", length) == 0) _gl20Features[GL20Features::GL20_EXT_color_buffer_half_float] = GL_TRUE; else if (strncmp(src, "GL_OES_texture_float", length) == 0) _gl20Features[GL20Features::GL20_OES_texture_float] = GL_TRUE; else if (strncmp(src, "GL_EXT_color_buffer_float", length) == 0) _gl20Features[GL20Features::GL20_EXT_color_buffer_float] = GL_TRUE; else if (strncmp(src, "GL_EXT_texture_type_2_10_10_10_REV", length) == 0) _gl20Features[GL20Features::GL20_EXT_texture_type_2_10_10_10_REV] = GL_TRUE; else if (strncmp(src, "GL_APPLE_texture_packed_float", length) == 0) _gl20Features[GL20Features::GL20_APPLE_texture_packed_float] = GL_TRUE; else if (strncmp(src, "GL_OES_depth_texture", length) == 0) _gl20Features[GL20Features::GL20_OES_depth_texture] = GL_TRUE; else if (strncmp(src, "GL_OES_depth24", length) == 0) _gl20Features[GL20Features::GL20_OES_depth24] = GL_TRUE; else if (strncmp(src, "GL_OES_depth32", length) == 0) _gl20Features[GL20Features::GL20_OES_depth32] = GL_TRUE; else if (strncmp(src, "GL_OES_texture_stencil8", length) == 0) _gl20Features[GL20Features::GL20_OES_texture_stencil8] = GL_TRUE; else if (strncmp(src, "GL_OES_packed_depth_stencil", length) == 0) _gl20Features[GL20Features::GL20_OES_packed_depth_stencil] = GL_TRUE; else if (strncmp(src, "GL_EXT_texture_compression_dxt1", length) == 0) _gl20Features[GL20Features::GL20_EXT_texture_compression_dxt1] = GL_TRUE; else if (strncmp(src, "GL_EXT_texture_compression_s3tc", length) == 0) _gl20Features[GL20Features::GL20_EXT_texture_compression_s3tc] = GL_TRUE; else if (strncmp(src, "GL_KHR_texture_compression_astc_ldr", length) == 0) _gl20Features[GL20Features::GL20_KHR_texture_compression_astc_ldr] = GL_TRUE; else if (strncmp(src, "GL_OES_vertex_type_10_10_10_2", length) == 0) _gl20Features[GL20Features::GL20_OES_vertex_type_10_10_10_2] = GL_TRUE; else if (strncmp(src, "GL_OES_vertex_half_float", length) == 0) _gl20Features[GL20Features::GL20_OES_vertex_half_float] = GL_TRUE; else if (strncmp(src, "GL_EXT_texture_filter_anisotropic", length) == 0) _gl20Features[GL20Features::GL20_EXT_texture_filter_anisotropic] = GL_TRUE; else if (strncmp(src, "GL_KHR_debug", length) == 0) _gl20Features[GL20Features::GL20_KHR_debug] = GL_TRUE; offset = pos + 1; } _gl20init = true; return true; } GLenum GL20Types::asVertexType(GraphicsVertexType type) noexcept { switch (type) { case GraphicsVertexType::PointList: return GL_POINTS; case GraphicsVertexType::LineList: return GL_LINES; case GraphicsVertexType::LineStrip: return GL_LINE_STRIP; case GraphicsVertexType::TriangleList: return GL_TRIANGLES; case GraphicsVertexType::TriangleStrip: return GL_TRIANGLE_STRIP; case GraphicsVertexType::TriangleFan: return GL_TRIANGLE_FAN; default: GL_PLATFORM_LOG("Invalid vertex type"); return false; } } GLenum GL20Types::asVertexFormat(GraphicsFormat format) noexcept { switch (format) { case GraphicsFormat::R8SNorm: case GraphicsFormat::R8SScaled: case GraphicsFormat::R8SInt: case GraphicsFormat::R8SRGB: case GraphicsFormat::R8G8SNorm: case GraphicsFormat::R8G8SScaled: case GraphicsFormat::R8G8SInt: case GraphicsFormat::R8G8SRGB: case GraphicsFormat::R8G8B8SNorm: case GraphicsFormat::R8G8B8SScaled: case GraphicsFormat::R8G8B8SInt: case GraphicsFormat::R8G8B8SRGB: case GraphicsFormat::B8G8R8SNorm: case GraphicsFormat::B8G8R8SScaled: case GraphicsFormat::B8G8R8SInt: case GraphicsFormat::B8G8R8SRGB: case GraphicsFormat::R8G8B8A8SNorm: case GraphicsFormat::R8G8B8A8SScaled: case GraphicsFormat::R8G8B8A8SInt: case GraphicsFormat::R8G8B8A8SRGB: case GraphicsFormat::B8G8R8A8SNorm: case GraphicsFormat::B8G8R8A8SScaled: case GraphicsFormat::B8G8R8A8SInt: case GraphicsFormat::B8G8R8A8SRGB: case GraphicsFormat::A8B8G8R8SNormPack32: case GraphicsFormat::A8B8G8R8SScaledPack32: case GraphicsFormat::A8B8G8R8SIntPack32: case GraphicsFormat::A8B8G8R8SRGBPack32: return GL_BYTE; case GraphicsFormat::R8UNorm: case GraphicsFormat::R8UScaled: case GraphicsFormat::R8UInt: case GraphicsFormat::R8G8UNorm: case GraphicsFormat::R8G8UScaled: case GraphicsFormat::R8G8UInt: case GraphicsFormat::R8G8B8UNorm: case GraphicsFormat::R8G8B8UScaled: case GraphicsFormat::R8G8B8UInt: case GraphicsFormat::B8G8R8UNorm: case GraphicsFormat::B8G8R8UScaled: case GraphicsFormat::B8G8R8UInt: case GraphicsFormat::R8G8B8A8UNorm: case GraphicsFormat::R8G8B8A8UScaled: case GraphicsFormat::R8G8B8A8UInt: case GraphicsFormat::B8G8R8A8UNorm: case GraphicsFormat::B8G8R8A8UScaled: case GraphicsFormat::B8G8R8A8UInt: case GraphicsFormat::A8B8G8R8UNormPack32: case GraphicsFormat::A8B8G8R8UScaledPack32: case GraphicsFormat::A8B8G8R8UIntPack32: return GL_UNSIGNED_BYTE; case GraphicsFormat::R16SNorm: case GraphicsFormat::R16SScaled: case GraphicsFormat::R16SInt: case GraphicsFormat::R16SFloat: case GraphicsFormat::R16G16SNorm: case GraphicsFormat::R16G16SScaled: case GraphicsFormat::R16G16SInt: case GraphicsFormat::R16G16SFloat: case GraphicsFormat::R16G16B16SNorm: case GraphicsFormat::R16G16B16SScaled: case GraphicsFormat::R16G16B16SInt: case GraphicsFormat::R16G16B16SFloat: case GraphicsFormat::R16G16B16A16SNorm: case GraphicsFormat::R16G16B16A16SScaled: case GraphicsFormat::R16G16B16A16SInt: case GraphicsFormat::R16G16B16A16SFloat: return GL_SHORT; case GraphicsFormat::R16UNorm: case GraphicsFormat::R16UScaled: case GraphicsFormat::R16UInt: case GraphicsFormat::R16G16UNorm: case GraphicsFormat::R16G16UScaled: case GraphicsFormat::R16G16UInt: case GraphicsFormat::R16G16B16UNorm: case GraphicsFormat::R16G16B16UScaled: case GraphicsFormat::R16G16B16UInt: case GraphicsFormat::R16G16B16A16UNorm: case GraphicsFormat::R16G16B16A16UScaled: case GraphicsFormat::R16G16B16A16UInt: return GL_UNSIGNED_SHORT; case GraphicsFormat::R32SInt: case GraphicsFormat::R32G32SInt: case GraphicsFormat::R32G32B32SInt: case GraphicsFormat::R32G32B32A32SInt: return GL_INT; case GraphicsFormat::R32UInt: case GraphicsFormat::R32G32UInt: case GraphicsFormat::R32G32B32UInt: case GraphicsFormat::R32G32B32A32UInt: return GL_UNSIGNED_INT; case GraphicsFormat::R32SFloat: case GraphicsFormat::R32G32SFloat: case GraphicsFormat::R32G32B32SFloat: case GraphicsFormat::R32G32B32A32SFloat: return GL_FLOAT; case GraphicsFormat::R64SInt: case GraphicsFormat::R64G64SInt: case GraphicsFormat::R64G64B64SInt: case GraphicsFormat::R64G64B64A64SInt: case GraphicsFormat::R64UInt: case GraphicsFormat::R64G64UInt: case GraphicsFormat::R64G64B64UInt: case GraphicsFormat::R64G64B64A64UInt: case GraphicsFormat::R64SFloat: case GraphicsFormat::R64G64SFloat: case GraphicsFormat::R64G64B64SFloat: case GraphicsFormat::R64G64B64A64SFloat: GL_PLATFORM_LOG("Can't support format"); return GL_INVALID_ENUM; default: return GL_INVALID_ENUM; break; } } GLenum GL20Types::asIndexType(GraphicsIndexType type) noexcept { switch (type) { case GraphicsIndexType::UInt16: return GL_UNSIGNED_SHORT; case GraphicsIndexType::UInt32: return GL_UNSIGNED_INT; default: GL_PLATFORM_LOG("Invalid index type"); return GL_INVALID_ENUM; } } GLenum GL20Types::asShaderStage(GraphicsShaderStageFlags stage) noexcept { switch (stage) { case GraphicsShaderStageFlagBits::VertexBit: return GL_VERTEX_SHADER; case GraphicsShaderStageFlagBits::FragmentBit: return GL_FRAGMENT_SHADER; case GraphicsShaderStageFlagBits::ComputeBit: case GraphicsShaderStageFlagBits::GeometryBit: case GraphicsShaderStageFlagBits::TessControlBit: case GraphicsShaderStageFlagBits::TessEvaluationBit: GL_PLATFORM_LOG("Can't support shader stage"); default: GL_PLATFORM_LOG("Invalid shader type"); return GL_INVALID_ENUM; } } GLenum GL20Types::asTextureTarget(GraphicsTextureDim target) noexcept { switch (target) { case GraphicsTextureDim::Texture2D: return GL_TEXTURE_2D; case GraphicsTextureDim::Cube: return GL_TEXTURE_CUBE_MAP; case GraphicsTextureDim::Texture2DMultisample: case GraphicsTextureDim::Texture2DArrayMultisample: case GraphicsTextureDim::Texture2DArray: case GraphicsTextureDim::Texture3D: case GraphicsTextureDim::CubeArray: default: return GL_INVALID_ENUM; } } GLenum GL20Types::asTextureFormat(GraphicsFormat format) noexcept { switch (format) { case GraphicsFormat::R8UNorm: case GraphicsFormat::R8SNorm: case GraphicsFormat::R8UScaled: case GraphicsFormat::R8SScaled: case GraphicsFormat::R8UInt: case GraphicsFormat::R8SInt: case GraphicsFormat::R16UNorm: case GraphicsFormat::R16SNorm: case GraphicsFormat::R16UScaled: case GraphicsFormat::R16SScaled: case GraphicsFormat::R16UInt: case GraphicsFormat::R16SInt: case GraphicsFormat::R16SFloat: case GraphicsFormat::R32UInt: case GraphicsFormat::R32SInt: case GraphicsFormat::R32SFloat: case GraphicsFormat::R64UInt: case GraphicsFormat::R64SInt: case GraphicsFormat::R64SFloat: return GL_INVALID_ENUM; case GraphicsFormat::R4G4UNormPack8: case GraphicsFormat::R8G8UNorm: case GraphicsFormat::R8G8SNorm: case GraphicsFormat::R8G8UScaled: case GraphicsFormat::R8G8SScaled: case GraphicsFormat::R8G8UInt: case GraphicsFormat::R8G8SInt: case GraphicsFormat::R16G16UNorm: case GraphicsFormat::R16G16SNorm: case GraphicsFormat::R16G16UScaled: case GraphicsFormat::R16G16SScaled: case GraphicsFormat::R16G16UInt: case GraphicsFormat::R16G16SInt: case GraphicsFormat::R16G16SFloat: case GraphicsFormat::R32G32UInt: case GraphicsFormat::R32G32SInt: case GraphicsFormat::R32G32SFloat: case GraphicsFormat::R64G64UInt: case GraphicsFormat::R64G64SInt: case GraphicsFormat::R64G64SFloat: return GL_INVALID_ENUM; case GraphicsFormat::R5G6B5UNormPack16: case GraphicsFormat::R8G8B8UNorm: case GraphicsFormat::R8G8B8SNorm: case GraphicsFormat::R8G8B8UScaled: case GraphicsFormat::R8G8B8SScaled: case GraphicsFormat::R8G8B8UInt: case GraphicsFormat::R8G8B8SInt: case GraphicsFormat::R16G16B16UNorm: case GraphicsFormat::R16G16B16SNorm: case GraphicsFormat::R16G16B16UScaled: case GraphicsFormat::R16G16B16SScaled: case GraphicsFormat::R16G16B16UInt: case GraphicsFormat::R16G16B16SInt: case GraphicsFormat::R16G16B16SFloat: case GraphicsFormat::R32G32B32UInt: case GraphicsFormat::R32G32B32SInt: case GraphicsFormat::R32G32B32SFloat: case GraphicsFormat::R64G64B64UInt: case GraphicsFormat::R64G64B64SInt: case GraphicsFormat::R64G64B64SFloat: return GL_RGB; case GraphicsFormat::B5G6R5UNormPack16: case GraphicsFormat::B8G8R8UNorm: case GraphicsFormat::B8G8R8SNorm: case GraphicsFormat::B8G8R8UScaled: case GraphicsFormat::B8G8R8SScaled: case GraphicsFormat::B8G8R8UInt: case GraphicsFormat::B8G8R8SInt: case GraphicsFormat::B10G11R11UFloatPack32: return GL_INVALID_ENUM; case GraphicsFormat::R4G4B4A4UNormPack16: case GraphicsFormat::R5G5B5A1UNormPack16: case GraphicsFormat::A1R5G5B5UNormPack16: case GraphicsFormat::R8G8B8A8UNorm: case GraphicsFormat::R8G8B8A8SNorm: case GraphicsFormat::R8G8B8A8UScaled: case GraphicsFormat::R8G8B8A8SScaled: case GraphicsFormat::R8G8B8A8UInt: case GraphicsFormat::R8G8B8A8SInt: case GraphicsFormat::A2R10G10B10UNormPack32: case GraphicsFormat::A2R10G10B10SNormPack32: case GraphicsFormat::A2R10G10B10UScaledPack32: case GraphicsFormat::A2R10G10B10SScaledPack32: case GraphicsFormat::A2R10G10B10UIntPack32: case GraphicsFormat::A2R10G10B10SIntPack32: case GraphicsFormat::R16G16B16A16UNorm: case GraphicsFormat::R16G16B16A16SNorm: case GraphicsFormat::R16G16B16A16UScaled: case GraphicsFormat::R16G16B16A16SScaled: case GraphicsFormat::R16G16B16A16UInt: case GraphicsFormat::R16G16B16A16SInt: case GraphicsFormat::R16G16B16A16SFloat: case GraphicsFormat::R32G32B32A32UInt: case GraphicsFormat::R32G32B32A32SInt: case GraphicsFormat::R32G32B32A32SFloat: case GraphicsFormat::R64G64B64A64UInt: case GraphicsFormat::R64G64B64A64SInt: case GraphicsFormat::R64G64B64A64SFloat: return GL_RGBA; case GraphicsFormat::B4G4R4A4UNormPack16: case GraphicsFormat::B5G5R5A1UNormPack16: case GraphicsFormat::B8G8R8A8UNorm: case GraphicsFormat::B8G8R8A8SNorm: case GraphicsFormat::B8G8R8A8UScaled: case GraphicsFormat::B8G8R8A8SScaled: case GraphicsFormat::B8G8R8A8UInt: case GraphicsFormat::B8G8R8A8SInt: case GraphicsFormat::A2B10G10R10UNormPack32: case GraphicsFormat::A2B10G10R10SNormPack32: case GraphicsFormat::A2B10G10R10UScaledPack32: case GraphicsFormat::A2B10G10R10SScaledPack32: case GraphicsFormat::A2B10G10R10UIntPack32: case GraphicsFormat::A2B10G10R10SIntPack32: return GL_INVALID_ENUM; case GraphicsFormat::A8B8G8R8UNormPack32: case GraphicsFormat::A8B8G8R8SNormPack32: case GraphicsFormat::A8B8G8R8UScaledPack32: case GraphicsFormat::A8B8G8R8SScaledPack32: case GraphicsFormat::A8B8G8R8UIntPack32: case GraphicsFormat::A8B8G8R8SIntPack32: return GL_INVALID_ENUM; case GraphicsFormat::R8SRGB: case GraphicsFormat::R8G8SRGB: case GraphicsFormat::R8G8B8SRGB: case GraphicsFormat::B8G8R8SRGB: return GL_INVALID_ENUM; case GraphicsFormat::R8G8B8A8SRGB: case GraphicsFormat::B8G8R8A8SRGB: case GraphicsFormat::A8B8G8R8SRGBPack32: return GL_INVALID_ENUM; case GraphicsFormat::D16UNorm: case GraphicsFormat::X8_D24UNormPack32: case GraphicsFormat::D32_SFLOAT: return GL_DEPTH_COMPONENT; case GraphicsFormat::S8UInt: return GL_STENCIL_INDEX8; case GraphicsFormat::D24UNorm_S8UInt: case GraphicsFormat::D16UNorm_S8UInt: case GraphicsFormat::D32_SFLOAT_S8UInt: return GL_INVALID_ENUM; default: GL_PLATFORM_ASSERT(false, "Invalid texture format"); return GL_INVALID_ENUM; } } GLenum GL20Types::asTextureType(GraphicsFormat format) noexcept { switch (format) { case GraphicsFormat::R4G4UNormPack8: return GL_UNSIGNED_BYTE; case GraphicsFormat::R4G4B4A4UNormPack16: return GL_UNSIGNED_SHORT_4_4_4_4; case GraphicsFormat::B4G4R4A4UNormPack16: return GL_UNSIGNED_SHORT_4_4_4_4; case GraphicsFormat::R5G6B5UNormPack16: return GL_UNSIGNED_SHORT_5_6_5; case GraphicsFormat::B5G6R5UNormPack16: return GL_UNSIGNED_SHORT_5_6_5; case GraphicsFormat::R5G5B5A1UNormPack16: return GL_UNSIGNED_SHORT_5_5_5_1; case GraphicsFormat::B5G5R5A1UNormPack16: return GL_UNSIGNED_SHORT_5_5_5_1; case GraphicsFormat::A1R5G5B5UNormPack16: return GL_UNSIGNED_SHORT_5_5_5_1; case GraphicsFormat::R8UNorm: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8SNorm: return GL_BYTE; case GraphicsFormat::R8UScaled: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8SScaled: return GL_BYTE; case GraphicsFormat::R8UInt: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8SInt: return GL_BYTE; case GraphicsFormat::R8SRGB: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8G8UNorm: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8G8SNorm: return GL_BYTE; case GraphicsFormat::R8G8UScaled: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8G8SScaled: return GL_BYTE; case GraphicsFormat::R8G8UInt: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8G8SInt: return GL_BYTE; case GraphicsFormat::R8G8SRGB: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8G8B8UNorm: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8G8B8SNorm: return GL_BYTE; case GraphicsFormat::R8G8B8UScaled: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8G8B8SScaled: return GL_BYTE; case GraphicsFormat::R8G8B8UInt: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8G8B8SInt: return GL_BYTE; case GraphicsFormat::R8G8B8SRGB: return GL_UNSIGNED_BYTE; case GraphicsFormat::B8G8R8UNorm: return GL_UNSIGNED_BYTE; case GraphicsFormat::B8G8R8SNorm: return GL_BYTE; case GraphicsFormat::B8G8R8UScaled: return GL_UNSIGNED_BYTE; case GraphicsFormat::B8G8R8SScaled: return GL_BYTE; case GraphicsFormat::B8G8R8UInt: return GL_UNSIGNED_BYTE; case GraphicsFormat::B8G8R8SInt: return GL_BYTE; case GraphicsFormat::B8G8R8SRGB: return GL_BYTE; case GraphicsFormat::R8G8B8A8UNorm: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8G8B8A8SNorm: return GL_BYTE; case GraphicsFormat::R8G8B8A8UScaled: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8G8B8A8SScaled: return GL_BYTE; case GraphicsFormat::R8G8B8A8UInt: return GL_UNSIGNED_BYTE; case GraphicsFormat::R8G8B8A8SInt: return GL_BYTE; case GraphicsFormat::R8G8B8A8SRGB: return GL_BYTE; case GraphicsFormat::B8G8R8A8UNorm: return GL_UNSIGNED_BYTE; case GraphicsFormat::B8G8R8A8SNorm: return GL_BYTE; case GraphicsFormat::B8G8R8A8UScaled: return GL_UNSIGNED_BYTE; case GraphicsFormat::B8G8R8A8SScaled: return GL_BYTE; case GraphicsFormat::B8G8R8A8UInt: return GL_UNSIGNED_BYTE; case GraphicsFormat::B8G8R8A8SInt: return GL_BYTE; case GraphicsFormat::B8G8R8A8SRGB: return GL_BYTE; case GraphicsFormat::A8B8G8R8UNormPack32: return GL_UNSIGNED_BYTE; case GraphicsFormat::A8B8G8R8SNormPack32: return GL_BYTE; case GraphicsFormat::A8B8G8R8UScaledPack32: return GL_UNSIGNED_BYTE; case GraphicsFormat::A8B8G8R8SScaledPack32: return GL_BYTE; case GraphicsFormat::A8B8G8R8UIntPack32: return GL_UNSIGNED_BYTE; case GraphicsFormat::A8B8G8R8SIntPack32: return GL_BYTE; case GraphicsFormat::A8B8G8R8SRGBPack32: return GL_UNSIGNED_BYTE; case GraphicsFormat::A2R10G10B10UNormPack32: return GL_INVALID_ENUM; case GraphicsFormat::A2R10G10B10UScaledPack32: return GL_INVALID_ENUM; case GraphicsFormat::A2R10G10B10UIntPack32: return GL_INVALID_ENUM; case GraphicsFormat::A2B10G10R10UNormPack32: return GL_INVALID_ENUM; case GraphicsFormat::A2B10G10R10UScaledPack32: return GL_INVALID_ENUM; case GraphicsFormat::A2B10G10R10UIntPack32: return GL_INVALID_ENUM; case GraphicsFormat::R16UNorm: return GL_UNSIGNED_SHORT; case GraphicsFormat::R16SNorm: return GL_SHORT; case GraphicsFormat::R16UScaled: return GL_UNSIGNED_SHORT; case GraphicsFormat::R16SScaled: return GL_SHORT; case GraphicsFormat::R16UInt: return GL_UNSIGNED_SHORT; case GraphicsFormat::R16SInt: return GL_SHORT; case GraphicsFormat::R16SFloat: return GL_INVALID_ENUM; case GraphicsFormat::R16G16UNorm: return GL_UNSIGNED_SHORT; case GraphicsFormat::R16G16SNorm: return GL_SHORT; case GraphicsFormat::R16G16UScaled: return GL_UNSIGNED_SHORT; case GraphicsFormat::R16G16SScaled: return GL_SHORT; case GraphicsFormat::R16G16UInt: return GL_UNSIGNED_SHORT; case GraphicsFormat::R16G16SInt: return GL_SHORT; case GraphicsFormat::R16G16SFloat: return GL_INVALID_ENUM; case GraphicsFormat::R16G16B16UNorm: return GL_UNSIGNED_SHORT; case GraphicsFormat::R16G16B16SNorm: return GL_SHORT; case GraphicsFormat::R16G16B16UScaled: return GL_UNSIGNED_SHORT; case GraphicsFormat::R16G16B16SScaled: return GL_SHORT; case GraphicsFormat::R16G16B16UInt: return GL_UNSIGNED_SHORT; case GraphicsFormat::R16G16B16SInt: return GL_SHORT; case GraphicsFormat::R16G16B16SFloat: return GL_INVALID_ENUM; case GraphicsFormat::R16G16B16A16UNorm: return GL_UNSIGNED_SHORT; case GraphicsFormat::R16G16B16A16SNorm: return GL_SHORT; case GraphicsFormat::R16G16B16A16UScaled: return GL_UNSIGNED_SHORT; case GraphicsFormat::R16G16B16A16SScaled: return GL_SHORT; case GraphicsFormat::R16G16B16A16UInt: return GL_UNSIGNED_SHORT; case GraphicsFormat::R16G16B16A16SInt: return GL_SHORT; case GraphicsFormat::R16G16B16A16SFloat: return GL_INVALID_ENUM; case GraphicsFormat::R32UInt: return GL_UNSIGNED_INT; case GraphicsFormat::R32SInt: return GL_INT; case GraphicsFormat::R32SFloat: return GL_FLOAT; case GraphicsFormat::R32G32UInt: return GL_UNSIGNED_INT; case GraphicsFormat::R32G32SInt: return GL_INT; case GraphicsFormat::R32G32SFloat: return GL_FLOAT; case GraphicsFormat::R32G32B32UInt: return GL_UNSIGNED_INT; case GraphicsFormat::R32G32B32SInt: return GL_INT; case GraphicsFormat::R32G32B32SFloat: return GL_FLOAT; case GraphicsFormat::R32G32B32A32UInt: return GL_UNSIGNED_INT; case GraphicsFormat::R32G32B32A32SInt: return GL_INT; case GraphicsFormat::R32G32B32A32SFloat: return GL_FLOAT; case GraphicsFormat::D16UNorm: return GL_UNSIGNED_SHORT; case GraphicsFormat::D32_SFLOAT: return GL_FLOAT; case GraphicsFormat::S8UInt: return GL_UNSIGNED_BYTE; case GraphicsFormat::X8_D24UNormPack32: return GL_UNSIGNED_INT; case GraphicsFormat::D16UNorm_S8UInt: return GL_INVALID_ENUM; case GraphicsFormat::D24UNorm_S8UInt: return GL_INVALID_ENUM; case GraphicsFormat::D32_SFLOAT_S8UInt: return GL_INVALID_ENUM; case GraphicsFormat::A2R10G10B10SNormPack32: return GL_INVALID_ENUM; case GraphicsFormat::A2R10G10B10SScaledPack32: return GL_INVALID_ENUM; case GraphicsFormat::A2R10G10B10SIntPack32: return GL_INVALID_ENUM; case GraphicsFormat::A2B10G10R10SNormPack32: return GL_INVALID_ENUM; case GraphicsFormat::A2B10G10R10SScaledPack32: return GL_INVALID_ENUM; case GraphicsFormat::A2B10G10R10SIntPack32: return GL_INVALID_ENUM; case GraphicsFormat::B10G11R11UFloatPack32: return GL_INVALID_ENUM; case GraphicsFormat::E5B9G9R9UFloatPack32: return GL_INVALID_ENUM; case GraphicsFormat::R64UInt: case GraphicsFormat::R64SInt: case GraphicsFormat::R64SFloat: case GraphicsFormat::R64G64UInt: case GraphicsFormat::R64G64SInt: case GraphicsFormat::R64G64SFloat: case GraphicsFormat::R64G64B64UInt: case GraphicsFormat::R64G64B64SInt: case GraphicsFormat::R64G64B64SFloat: case GraphicsFormat::R64G64B64A64UInt: case GraphicsFormat::R64G64B64A64SInt: case GraphicsFormat::R64G64B64A64SFloat: GL_PLATFORM_ASSERT(false, "Can't support 64bit format"); return GL_INVALID_ENUM; default: GL_PLATFORM_ASSERT(false, "Invlida texture data type."); } return GL_INVALID_ENUM; } GLenum GL20Types::asTextureInternalFormat(GraphicsFormat format) noexcept { GLenum internalFormat = GL_INVALID_ENUM; switch (format) { case GraphicsFormat::R4G4UNormPack8: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R4G4B4A4UNormPack16: internalFormat = GL_RGBA4; break; case GraphicsFormat::B4G4R4A4UNormPack16: internalFormat = GL_RGBA4; break; case GraphicsFormat::R5G6B5UNormPack16: internalFormat = GL_RGB565; break; case GraphicsFormat::B5G6R5UNormPack16: internalFormat = GL_RGB565; break; case GraphicsFormat::R5G5B5A1UNormPack16: internalFormat = GL_RGB5_A1; break; case GraphicsFormat::B5G5R5A1UNormPack16: internalFormat = GL_RGB5_A1; break; case GraphicsFormat::A1R5G5B5UNormPack16: internalFormat = GL_RGB5_A1; break; case GraphicsFormat::R8UNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8SNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8UScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8SScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8SRGB: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8G8UNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8G8SNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8G8UScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8G8SScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8G8UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8G8SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8G8SRGB: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R8G8B8UNorm: internalFormat = GL_RGB; break; case GraphicsFormat::R8G8B8SNorm: internalFormat = GL_RGB; break; case GraphicsFormat::R8G8B8UScaled: internalFormat = GL_RGB; break; case GraphicsFormat::R8G8B8SScaled: internalFormat = GL_RGB; break; case GraphicsFormat::R8G8B8UInt: internalFormat = GL_RGB; break; case GraphicsFormat::R8G8B8SInt: internalFormat = GL_RGB; break; case GraphicsFormat::R8G8B8SRGB: internalFormat = GL_RGB; break; case GraphicsFormat::R8G8B8A8UNorm: internalFormat = GL_RGBA; break; case GraphicsFormat::R8G8B8A8SNorm: internalFormat = GL_RGBA; break; case GraphicsFormat::R8G8B8A8UScaled: internalFormat = GL_RGBA; break; case GraphicsFormat::R8G8B8A8SScaled: internalFormat = GL_RGBA; break; case GraphicsFormat::R8G8B8A8UInt: internalFormat = GL_RGBA; break; case GraphicsFormat::R8G8B8A8SInt: internalFormat = GL_RGBA; break; case GraphicsFormat::R8G8B8A8SRGB: internalFormat = GL_RGBA; break; case GraphicsFormat::B8G8R8UNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B8G8R8SNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B8G8R8UScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B8G8R8SScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B8G8R8UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B8G8R8SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B8G8R8SRGB: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B8G8R8A8UNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B8G8R8A8SNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B8G8R8A8UScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B8G8R8A8SScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B8G8R8A8UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B8G8R8A8SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B8G8R8A8SRGB: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A8B8G8R8UNormPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A8B8G8R8SNormPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A8B8G8R8UScaledPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A8B8G8R8SScaledPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A8B8G8R8UIntPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A8B8G8R8SIntPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A8B8G8R8SRGBPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A2R10G10B10UNormPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A2R10G10B10SNormPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A2R10G10B10UScaledPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A2R10G10B10SScaledPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A2R10G10B10UIntPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A2R10G10B10SIntPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A2B10G10R10UNormPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A2B10G10R10SNormPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A2B10G10R10UScaledPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A2B10G10R10SScaledPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A2B10G10R10UIntPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::A2B10G10R10SIntPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16UNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16SNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16UScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16SScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16SFloat: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16UNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16SNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16UScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16SScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16SFloat: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16UNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16SNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16UScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16SScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16SFloat: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16A16UNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16A16SNorm: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16A16UScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16A16SScaled: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16A16UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16A16SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R16G16B16A16SFloat: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R32UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R32SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R32SFloat: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R32G32UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R32G32SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R32G32SFloat: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R32G32B32UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R32G32B32SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R32G32B32SFloat: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R32G32B32A32UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R32G32B32A32SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R32G32B32A32SFloat: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R64UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R64SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R64SFloat: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R64G64UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R64G64SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R64G64SFloat: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R64G64B64UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R64G64B64SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R64G64B64SFloat: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R64G64B64A64UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R64G64B64A64SInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::R64G64B64A64SFloat: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::B10G11R11UFloatPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::E5B9G9R9UFloatPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::D16UNorm: internalFormat = GL_DEPTH_COMPONENT16; break; case GraphicsFormat::X8_D24UNormPack32: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::D32_SFLOAT: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::S8UInt: internalFormat = GL_STENCIL_INDEX8; break; case GraphicsFormat::D16UNorm_S8UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::D24UNorm_S8UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::D32_SFLOAT_S8UInt: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC1RGBUNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC1RGBSRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC1RGBAUNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC1RGBASRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC2UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC2SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC3UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC3SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC4UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC4SNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC5UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC5SNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC6HUFloatBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC6HSFloatBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC7UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::BC7SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ETC2R8G8B8UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ETC2R8G8B8SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ETC2R8G8B8A1UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ETC2R8G8B8A1SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ETC2R8G8B8A8UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ETC2R8G8B8A8SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::EACR11UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::EACR11SNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::EACR11G11UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::EACR11G11SNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC4x4UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC4x4SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC5x4UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC5x4SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC5x5UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC5x5SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC6x5UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC6x5SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC6x6UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC6x6SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC8x5UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC8x5SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC8x6UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC8x6SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC8x8UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC8x8SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC10x5UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC10x5SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC10x6UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC10x6SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC10x8UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC10x8SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC10x10UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC10x10SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC12x10UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC12x10SRGBBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC12x12UNormBlock: internalFormat = GL_INVALID_ENUM; break; case GraphicsFormat::ASTC12x12SRGBBlock: internalFormat = GL_INVALID_ENUM; break; default: assert(false); return GL_INVALID_ENUM; } return internalFormat; } GLenum GL20Types::asCompareFunction(GraphicsCompareFunc func) noexcept { switch (func) { case GraphicsCompareFunc::None: return GL_NONE; case GraphicsCompareFunc::Lequal: return GL_LEQUAL; case GraphicsCompareFunc::Equal: return GL_EQUAL; case GraphicsCompareFunc::Greater: return GL_GREATER; case GraphicsCompareFunc::Less: return GL_LESS; case GraphicsCompareFunc::Gequal: return GL_GEQUAL; case GraphicsCompareFunc::NotEqual: return GL_NOTEQUAL; case GraphicsCompareFunc::Always: return GL_ALWAYS; case GraphicsCompareFunc::Never: return GL_NEVER; default: GL_PLATFORM_ASSERT(false, "Invalid compare function"); return GL_INVALID_ENUM; } } GLenum GL20Types::asBlendFactor(GraphicsBlendFactor func) noexcept { switch (func) { case GraphicsBlendFactor::Zero: return GL_ZERO; case GraphicsBlendFactor::One: return GL_ONE; case GraphicsBlendFactor::DstCol: return GL_DST_COLOR; case GraphicsBlendFactor::SrcColor: return GL_SRC_COLOR; case GraphicsBlendFactor::SrcAlpha: return GL_SRC_ALPHA; case GraphicsBlendFactor::DstAlpha: return GL_DST_ALPHA; case GraphicsBlendFactor::OneMinusSrcCol: return GL_ONE_MINUS_SRC_COLOR; case GraphicsBlendFactor::OneMinusDstCol: return GL_ONE_MINUS_DST_COLOR; case GraphicsBlendFactor::OneMinusSrcAlpha: return GL_ONE_MINUS_SRC_ALPHA; case GraphicsBlendFactor::OneMinusDstAlpha: return GL_ONE_MINUS_DST_ALPHA; case GraphicsBlendFactor::ConstantColor: return GL_CONSTANT_COLOR; case GraphicsBlendFactor::ConstantAlpha: return GL_CONSTANT_ALPHA; case GraphicsBlendFactor::OneMinusConstantColor: return GL_CONSTANT_ALPHA; case GraphicsBlendFactor::OneMinusConstantAlpha: return GL_CONSTANT_ALPHA; case GraphicsBlendFactor::SrcAlphaSaturate: return GL_SRC_ALPHA_SATURATE; default: GL_PLATFORM_ASSERT(false, "Invalid blend factor"); return GL_INVALID_ENUM; } } GLenum GL20Types::asBlendOperation(GraphicsBlendOp blendop) noexcept { switch (blendop) { case GraphicsBlendOp::Add: return GL_FUNC_ADD; case GraphicsBlendOp::Subtract: return GL_FUNC_SUBTRACT; case GraphicsBlendOp::RevSubtract:return GL_FUNC_REVERSE_SUBTRACT; default: GL_PLATFORM_ASSERT(false, "Invalid blend operation"); return GL_INVALID_ENUM; } } GLenum GL20Types::asCullMode(GraphicsCullMode mode) noexcept { switch (mode) { case GraphicsCullMode::None: return GL_NONE; case GraphicsCullMode::Front: return GL_FRONT; case GraphicsCullMode::Back: return GL_BACK; case GraphicsCullMode::FrontBack: return GL_FRONT_AND_BACK; default: GL_PLATFORM_ASSERT(false, "Invalid cull mode"); return GL_INVALID_ENUM; } } GLenum GL20Types::asFrontFace(GraphicsFrontFace face) noexcept { switch (face) { case GraphicsFrontFace::CW: return GL_CW; case GraphicsFrontFace::CCW: return GL_CCW; default: GL_PLATFORM_ASSERT(false, "Invalid front face"); return GL_INVALID_ENUM; } } GLenum GL20Types::asFillMode(GraphicsPolygonMode mode) noexcept { switch (mode) { case GraphicsPolygonMode::Point: case GraphicsPolygonMode::Wireframe: case GraphicsPolygonMode::Solid: GL_PLATFORM_ASSERT(false, "Can't support glPolygonMode"); return GL_INVALID_ENUM; default: GL_PLATFORM_ASSERT(false, "Invalid fill mode"); return GL_INVALID_ENUM; } } GLenum GL20Types::asStencilOperation(GraphicsStencilOp stencilop) noexcept { switch (stencilop) { case GraphicsStencilOp::Keep: return GL_KEEP; case GraphicsStencilOp::Replace: return GL_REPLACE; case GraphicsStencilOp::Incr: return GL_INCR; case GraphicsStencilOp::Decr: return GL_DECR; case GraphicsStencilOp::Zero: return GL_ZERO; case GraphicsStencilOp::IncrWrap: return GL_INCR_WRAP; case GraphicsStencilOp::DecrWrap: return GL_DECR_WRAP; default: GL_PLATFORM_ASSERT(false, "Invalid stencil operation"); return GL_INVALID_ENUM; } } GLenum GL20Types::asSamplerWrap(GraphicsSamplerWrap wrap) noexcept { switch (wrap) { case GraphicsSamplerWrap::Repeat: return GL_REPEAT; case GraphicsSamplerWrap::Mirror: return GL_MIRRORED_REPEAT; case GraphicsSamplerWrap::ClampToEdge: return GL_CLAMP_TO_EDGE; default: GL_PLATFORM_ASSERT(false, "Invalid sampler wrap"); return GL_INVALID_ENUM; } } GLenum GL20Types::asSamplerMinFilter(GraphicsSamplerFilter filter) noexcept { switch (filter) { case GraphicsSamplerFilter::Nearest: return GL_NEAREST; case GraphicsSamplerFilter::Linear: return GL_LINEAR; case GraphicsSamplerFilter::NearestMipmapLinear: return GL_NEAREST_MIPMAP_LINEAR; case GraphicsSamplerFilter::NearestMipmapNearest: return GL_NEAREST_MIPMAP_NEAREST; case GraphicsSamplerFilter::LinearMipmapNearest: return GL_LINEAR_MIPMAP_NEAREST; case GraphicsSamplerFilter::LinearMipmapLinear: return GL_LINEAR_MIPMAP_LINEAR; default: GL_PLATFORM_ASSERT(false, "Invalid sampler filter"); return GL_INVALID_ENUM; } } GLenum GL20Types::asSamplerMagFilter(GraphicsSamplerFilter filter) noexcept { switch (filter) { case GraphicsSamplerFilter::Nearest: return GL_NEAREST; case GraphicsSamplerFilter::Linear: return GL_LINEAR; case GraphicsSamplerFilter::NearestMipmapLinear: return GL_NEAREST; case GraphicsSamplerFilter::NearestMipmapNearest: return GL_NEAREST; case GraphicsSamplerFilter::LinearMipmapNearest: return GL_LINEAR; case GraphicsSamplerFilter::LinearMipmapLinear: return GL_LINEAR; default: GL_PLATFORM_ASSERT(false, "Invalid sampler filter"); return GL_INVALID_ENUM; } } GLsizei GL20Types::getFormatNum(GLenum format, GLenum type) noexcept { GLsizei typeSize = 0; if (type == GL_UNSIGNED_BYTE || type == GL_BYTE) typeSize = 1; else if (type == GL_UNSIGNED_SHORT || type == GL_SHORT) typeSize = 2; else if (type == GL_UNSIGNED_INT || type == GL_INT || type == GL_FLOAT) typeSize = 4; else { assert(false); return 1; } if (format == GL_RGB) return 3 * typeSize; else if (format == GL_RGBA) return 4 * typeSize; else { assert(false); return 0; } } GLsizei GL20Types::getCompressedTextureSize(GLsizei width, GLsizei height, GLsizei depth, GLenum internalFormat) noexcept { GL_PLATFORM_ASSERT(false, "bad texformat in compressed_texture_size"); return 0; } GLboolean GL20Types::isNormFormat(GraphicsFormat format) noexcept { switch (format) { case GraphicsFormat::R8UNorm: case GraphicsFormat::R8SNorm: case GraphicsFormat::R8G8UNorm: case GraphicsFormat::R8G8SNorm: case GraphicsFormat::R8G8B8UNorm: case GraphicsFormat::R8G8B8SNorm: case GraphicsFormat::B8G8R8UNorm: case GraphicsFormat::B8G8R8SNorm: case GraphicsFormat::R8G8B8A8UNorm: case GraphicsFormat::R8G8B8A8SNorm: case GraphicsFormat::B8G8R8A8UNorm: case GraphicsFormat::B8G8R8A8SNorm: case GraphicsFormat::A8B8G8R8UNormPack32: case GraphicsFormat::A8B8G8R8SNormPack32: case GraphicsFormat::A2R10G10B10UNormPack32: case GraphicsFormat::A2R10G10B10SNormPack32: case GraphicsFormat::A2B10G10R10UNormPack32: case GraphicsFormat::A2B10G10R10SNormPack32: case GraphicsFormat::R16UNorm: case GraphicsFormat::R16SNorm: case GraphicsFormat::R16G16UNorm: case GraphicsFormat::R16G16SNorm: case GraphicsFormat::R16G16B16UNorm: case GraphicsFormat::R16G16B16SNorm: case GraphicsFormat::R16G16B16A16UNorm: case GraphicsFormat::R16G16B16A16SNorm: return GL_TRUE; default: return GL_FALSE; } } GLboolean GL20Types::isSupportFeature(GL20Features features) noexcept { assert(features >= GL20Features::GL20_BeginRange && features <= GL20Features::GL20_EndRange); return _gl20Features[features]; } GLboolean GL20Types::isStencilFormat(GraphicsFormat format) noexcept { if (format == GraphicsFormat::S8UInt) return GL_TRUE; return GL_FALSE; } GLboolean GL20Types::isDepthFormat(GraphicsFormat format) noexcept { if (format == GraphicsFormat::D16UNorm || format == GraphicsFormat::X8_D24UNormPack32 || format == GraphicsFormat::D32_SFLOAT) { return GL_TRUE; } return GL_FALSE; } GLboolean GL20Types::isDepthStencilFormat(GraphicsFormat format) noexcept { if (format == GraphicsFormat::D16UNorm_S8UInt || format == GraphicsFormat::D24UNorm_S8UInt || format == GraphicsFormat::D32_SFLOAT_S8UInt) { return GL_TRUE; } return GL_FALSE; } GLboolean GL20Types::isCompressedTexture(GraphicsFormat format) noexcept { switch (format) { case GraphicsFormat::BC1RGBUNormBlock: case GraphicsFormat::BC1RGBSRGBBlock: case GraphicsFormat::BC1RGBAUNormBlock: case GraphicsFormat::BC1RGBASRGBBlock: case GraphicsFormat::BC2UNormBlock: case GraphicsFormat::BC2SRGBBlock: case GraphicsFormat::BC3UNormBlock: case GraphicsFormat::BC3SRGBBlock: case GraphicsFormat::BC4UNormBlock: case GraphicsFormat::BC4SNormBlock: case GraphicsFormat::BC5UNormBlock: case GraphicsFormat::BC5SNormBlock: case GraphicsFormat::BC6HUFloatBlock: case GraphicsFormat::BC6HSFloatBlock: case GraphicsFormat::BC7UNormBlock: case GraphicsFormat::BC7SRGBBlock: case GraphicsFormat::ETC2R8G8B8UNormBlock: case GraphicsFormat::ETC2R8G8B8SRGBBlock: case GraphicsFormat::ETC2R8G8B8A1UNormBlock: case GraphicsFormat::ETC2R8G8B8A1SRGBBlock: case GraphicsFormat::ETC2R8G8B8A8UNormBlock: case GraphicsFormat::ETC2R8G8B8A8SRGBBlock: case GraphicsFormat::EACR11UNormBlock: case GraphicsFormat::EACR11SNormBlock: case GraphicsFormat::EACR11G11UNormBlock: case GraphicsFormat::EACR11G11SNormBlock: case GraphicsFormat::ASTC4x4UNormBlock: case GraphicsFormat::ASTC4x4SRGBBlock: case GraphicsFormat::ASTC5x4UNormBlock: case GraphicsFormat::ASTC5x4SRGBBlock: case GraphicsFormat::ASTC5x5UNormBlock: case GraphicsFormat::ASTC5x5SRGBBlock: case GraphicsFormat::ASTC6x5UNormBlock: case GraphicsFormat::ASTC6x5SRGBBlock: case GraphicsFormat::ASTC6x6UNormBlock: case GraphicsFormat::ASTC6x6SRGBBlock: case GraphicsFormat::ASTC8x5UNormBlock: case GraphicsFormat::ASTC8x5SRGBBlock: case GraphicsFormat::ASTC8x6UNormBlock: case GraphicsFormat::ASTC8x6SRGBBlock: case GraphicsFormat::ASTC8x8UNormBlock: case GraphicsFormat::ASTC8x8SRGBBlock: case GraphicsFormat::ASTC10x5UNormBlock: case GraphicsFormat::ASTC10x5SRGBBlock: case GraphicsFormat::ASTC10x6UNormBlock: case GraphicsFormat::ASTC10x6SRGBBlock: case GraphicsFormat::ASTC10x8UNormBlock: case GraphicsFormat::ASTC10x8SRGBBlock: case GraphicsFormat::ASTC10x10UNormBlock: case GraphicsFormat::ASTC10x10SRGBBlock: case GraphicsFormat::ASTC12x10UNormBlock: case GraphicsFormat::ASTC12x10SRGBBlock: case GraphicsFormat::ASTC12x12UNormBlock: case GraphicsFormat::ASTC12x12SRGBBlock: return GL_TRUE; default: return GL_FALSE; } } bool GL20Check::checkError() noexcept { bool success = true; GLenum result = ::glGetError(); if (GL_NO_ERROR != result) { success = false; switch (result) { case GL_INVALID_ENUM: GL_PLATFORM_LOG("glGetError() fail : GL_INVALID_ENUM"); break; case GL_INVALID_VALUE: GL_PLATFORM_LOG("glGetError() fail : GL_INVALID_VALUE"); break; case GL_INVALID_OPERATION: GL_PLATFORM_LOG("glGetError() fail : GL_INVALID_OPERATION"); break; case GL_OUT_OF_MEMORY: GL_PLATFORM_LOG("glGetError() fail : GL_OUT_OF_MEMORY"); break; case GL_INVALID_FRAMEBUFFER_OPERATION: GL_PLATFORM_LOG("glGetError() fail : GL_INVALID_FRAMEBUFFER_OPERATION"); break; default: GL_PLATFORM_LOG("glGetError() fail : Unknown"); }; } result = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (GL_FRAMEBUFFER_COMPLETE != result) { success = false; switch (result) { case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: GL_PLATFORM_LOG("FBO:Incomplete attachment"); break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: GL_PLATFORM_LOG("FBO:Incomplete missing attachment"); break; case GL_FRAMEBUFFER_UNSUPPORTED: GL_PLATFORM_LOG("FBO:Unsupported"); break; default: GL_PLATFORM_LOG("FBO:Unknown"); } } return success; } void GL20Check::debugOutput(const char* message, ...) noexcept { va_list va; va_start(va, message); vprintf(message, va); printf("\n"); va_end(va); } } }
47.546304
156
0.735642
[ "solid" ]
d5234ca92ffc7523026240e543d414cc54bbdfb8
5,747
cpp
C++
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/plugins/platforms/qnx/qqnxnavigatorpps.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/plugins/platforms/qnx/qqnxnavigatorpps.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/plugins/platforms/qnx/qqnxnavigatorpps.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
/*************************************************************************** ** ** Copyright (C) 2012 Research In Motion ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qqnxnavigatorpps.h" #include <QDebug> #include <private/qcore_unix_p.h> #if defined(QQNXNAVIGATOR_DEBUG) #define qNavigatorDebug qDebug #else #define qNavigatorDebug QT_NO_QDEBUG_MACRO #endif static const char *navigatorControlPath = "/pps/services/navigator/control"; static const int ppsBufferSize = 4096; QT_BEGIN_NAMESPACE QQnxNavigatorPps::QQnxNavigatorPps(QObject *parent) : QQnxAbstractNavigator(parent) , m_fd(-1) { } QQnxNavigatorPps::~QQnxNavigatorPps() { // close connection to navigator if (m_fd != -1) qt_safe_close(m_fd); } bool QQnxNavigatorPps::openPpsConnection() { if (m_fd != -1) return true; // open connection to navigator errno = 0; m_fd = qt_safe_open(navigatorControlPath, O_RDWR); if (m_fd == -1) { qWarning("QQNX: failed to open navigator pps, errno=%d", errno); return false; } qNavigatorDebug("successfully connected to Navigator. fd=%d", m_fd); return true; } bool QQnxNavigatorPps::requestInvokeUrl(const QByteArray &encodedUrl) { if (!openPpsConnection()) return false; return sendPpsMessage("invoke", encodedUrl); } bool QQnxNavigatorPps::sendPpsMessage(const QByteArray &message, const QByteArray &data) { QByteArray ppsMessage = "msg::" + message; if (!data.isEmpty()) ppsMessage += "\ndat::" + data; ppsMessage += "\n"; qNavigatorDebug() << "sending PPS message:\n" << ppsMessage; // send pps message to navigator errno = 0; int bytes = qt_safe_write(m_fd, ppsMessage.constData(), ppsMessage.size()); if (Q_UNLIKELY(bytes == -1)) qFatal("QQNX: failed to write navigator pps, errno=%d", errno); // allocate buffer for pps data char buffer[ppsBufferSize]; // attempt to read pps data do { errno = 0; bytes = qt_safe_read(m_fd, buffer, ppsBufferSize - 1); if (Q_UNLIKELY(bytes == -1)) qFatal("QQNX: failed to read navigator pps, errno=%d", errno); } while (bytes == 0); // ensure data is null terminated buffer[bytes] = '\0'; qNavigatorDebug() << "received PPS message:\n" << buffer; // process received message QByteArray ppsData(buffer); QHash<QByteArray, QByteArray> responseFields; parsePPS(ppsData, responseFields); if (responseFields.contains("res") && responseFields.value("res") == message) { if (Q_UNLIKELY(responseFields.contains("err"))) { qCritical() << "navigator responded with error: " << responseFields.value("err"); return false; } } return true; } void QQnxNavigatorPps::parsePPS(const QByteArray &ppsData, QHash<QByteArray, QByteArray> &messageFields) { qNavigatorDebug() << "data=" << ppsData; // tokenize pps data into lines QList<QByteArray> lines = ppsData.split('\n'); // validate pps object if (Q_UNLIKELY(lines.empty() || lines.at(0) != "@control")) qFatal("QQNX: unrecognized pps object, data=%s", ppsData.constData()); // parse pps object attributes and extract values for (int i = 1; i < lines.size(); i++) { // tokenize current attribute const QByteArray &attr = lines.at(i); qNavigatorDebug() << "attr=" << attr; int firstColon = attr.indexOf(':'); if (firstColon == -1) { // abort - malformed attribute continue; } int secondColon = attr.indexOf(':', firstColon + 1); if (secondColon == -1) { // abort - malformed attribute continue; } QByteArray key = attr.left(firstColon); QByteArray value = attr.mid(secondColon + 1); qNavigatorDebug() << "key=" << key; qNavigatorDebug() << "val=" << value; messageFields[key] = value; } } QT_END_NAMESPACE
31.233696
104
0.65408
[ "object" ]
d528157b11e74da058e9b2e54e5961a9abbc392c
3,196
hpp
C++
src/mlpack/methods/ann/loss_functions/log_cosh_loss.hpp
ShivCharanSharma/mlpack
22fda194c40001b93a51183a58b13e4a9c72a320
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-11T19:31:13.000Z
2021-01-11T19:31:13.000Z
src/mlpack/methods/ann/loss_functions/log_cosh_loss.hpp
876arham/mlpack
1379831e578037c9d0ed3a1683ce76e3d1c8247e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/methods/ann/loss_functions/log_cosh_loss.hpp
876arham/mlpack
1379831e578037c9d0ed3a1683ce76e3d1c8247e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/** * @file log_cosh_loss.hpp * @author Kartik Dutt * * Definition of the Log-Hyperbolic-Cosine loss function. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_METHODS_ANN_LOSS_FUNCTION_LOG_COSH_LOSS_HPP #define MLPACK_METHODS_ANN_LOSS_FUNCTION_LOG_COSH_LOSS_HPP #include <mlpack/prereqs.hpp> namespace mlpack { namespace ann /** Artificial Neural Network. */ { /** * The Log-Hyperbolic-Cosine loss function is often used to improve * variational auto encoder. This function is the log of hyperbolic * cosine of difference between true values and predicted values. * * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, * arma::sp_mat or arma::cube). * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, * arma::sp_mat or arma::cube). */ template < typename InputDataType = arma::mat, typename OutputDataType = arma::mat > class LogCoshLoss { public: /** * Create the Log-Hyperbolic-Cosine object with the specified * parameters. * * @param a A double type value for smoothening loss function. * It must be positive a real number, Sharpness of loss * function is directly proportional to a. It can also * act as a scaling factor hence making the loss * function more sensitive to small losses around the * origin. Default value = 1.0. */ LogCoshLoss(const double a = 1.0); /** * Computes the Log-Hyperbolic-Cosine loss function. * * @param input Input data used for evaluating the specified function. * @param target Target data to compare with. */ template<typename InputType, typename TargetType> double Forward(const InputType& input, const TargetType& target); /** * Ordinary feed backward pass of a neural network. * * @param input The propagated input activation. * @param target The target vector. * @param output The calculated error. */ template<typename InputType, typename TargetType, typename OutputType> void Backward(const InputType& input, const TargetType& target, OutputType& output); //! Get the output parameter. OutputDataType& OutputParameter() const { return outputParameter; } //! Modify the output parameter. OutputDataType& OutputParameter() { return outputParameter; } //! Get the value of hyperparameter a. double A() const { return a; } //! Modify the value of hyperparameter a. double& A() { return a; } /** * Serialize the loss function. */ template<typename Archive> void serialize(Archive& ar, const unsigned int /* version */); private: //! Locally-stored output parameter object. OutputDataType outputParameter; //! Hyperparameter a for smoothening function curve. double a; }; // class LogCoshLoss } // namespace ann } // namespace mlpack // include implementation #include "log_cosh_loss_impl.hpp" #endif
31.029126
78
0.699937
[ "object", "vector" ]
d52aef69f23891e082eda982e5da08e75aad1cac
2,360
cpp
C++
CWin/CWin/utility/drawing.cpp
benbraide/CWin
0441b48a71fef0dbddabf61033d7286669772c1e
[ "MIT" ]
null
null
null
CWin/CWin/utility/drawing.cpp
benbraide/CWin
0441b48a71fef0dbddabf61033d7286669772c1e
[ "MIT" ]
null
null
null
CWin/CWin/utility/drawing.cpp
benbraide/CWin
0441b48a71fef0dbddabf61033d7286669772c1e
[ "MIT" ]
null
null
null
#include "../app/app_object.h" #include "drawing.h" cwin::utility::drawing::save_dc::save_dc(HDC value) : value_(value){ if (value_ != nullptr) id_ = SaveDC(value_); } cwin::utility::drawing::save_dc::~save_dc(){ if (value_ != nullptr){ RestoreDC(value_, id_); value_ = nullptr; } } cwin::utility::drawing::save_transform::save_transform(ID2D1RenderTarget &target) : target_(target){ target_.GetTransform(&value_); } cwin::utility::drawing::save_transform::~save_transform(){ target_.SetTransform(value_); } cwin::utility::drawing::translate::translate(ID2D1RenderTarget &target, const SIZE &offset) : translate(target, D2D1::SizeF(static_cast<float>(offset.cx), static_cast<float>(offset.cy))){} cwin::utility::drawing::translate::translate(ID2D1RenderTarget &target, const D2D1_SIZE_F &offset) : save_transform(target){ target_.SetTransform(D2D1::Matrix3x2F::Translation(offset)); } cwin::utility::drawing::translate::~translate() = default; cwin::utility::drawing::begin::begin(ID2D1RenderTarget &target) : target_(target){ app::object::get_thread().get_window_manager().begin_draw(target_); } cwin::utility::drawing::begin::~begin(){ app::object::get_thread().get_window_manager().end_draw(target_); } cwin::utility::drawing::begin_token::begin_token(ID2D1RenderTarget &target) : target_(target){ is_active_ = app::object::get_thread().get_window_manager().activate_begin_draw_token(target_); } cwin::utility::drawing::begin_token::~begin_token(){ if (is_active_){ app::object::get_thread().get_window_manager().end_draw(target_); is_active_ = false; } } cwin::utility::drawing::layer::layer(ID2D1RenderTarget &target, ID2D1Geometry &value) : target_(target){ target_.PushLayer( D2D1::LayerParameters(D2D1::InfiniteRect(), &value), nullptr ); } cwin::utility::drawing::layer::~layer(){ target_.PopLayer(); } cwin::utility::drawing::clip::clip(ID2D1RenderTarget &target, const RECT &value) : clip(target, D2D1::RectF(static_cast<float>(value.left), static_cast<float>(value.top), static_cast<float>(value.right), static_cast<float>(value.bottom))){} cwin::utility::drawing::clip::clip(ID2D1RenderTarget &target, const D2D1_RECT_F &value) : target_(target){ target_.PushAxisAlignedClip(value, D2D1_ANTIALIAS_MODE_PER_PRIMITIVE); } cwin::utility::drawing::clip::~clip(){ target_.PopAxisAlignedClip(); }
29.135802
160
0.743644
[ "object" ]
d52c1abeaa5854499a5bd0feef7de60910ab257b
2,302
cpp
C++
Plugins/GStreamer/Source/GStreamer/Private/GstAppSrcImpl.cpp
kevinrev26/UnrealGAMS
74b53f5d0e52bd8826e5991192a62cc04547d93e
[ "BSD-3-Clause" ]
7
2019-02-19T23:28:25.000Z
2021-09-06T16:23:49.000Z
Plugins/GStreamer/Source/GStreamer/Private/GstAppSrcImpl.cpp
kevinrev26/UnrealGAMS
74b53f5d0e52bd8826e5991192a62cc04547d93e
[ "BSD-3-Clause" ]
1
2019-03-26T18:38:31.000Z
2019-03-26T21:41:49.000Z
Plugins/GStreamer/Source/GStreamer/Private/GstAppSrcImpl.cpp
racsoraul/UnrealGAMS
3931d6d45ddc7aed7acf941740bd60250e9db196
[ "BSD-3-Clause" ]
8
2019-02-18T18:00:25.000Z
2019-07-12T19:33:36.000Z
#include "GstAppSrcImpl.h" #include "GstPipelineImpl.h" #include "GstSampleImpl.h" extern "C" { #include <gst/gst.h> #include <gst/app/gstappsrc.h> } #include <vector> #include <mutex> class FGstAppSrcImpl : public IGstAppSrc { public: FGstAppSrcImpl() {} ~FGstAppSrcImpl() { Disconnect(); } virtual void Destroy(); virtual bool Connect(IGstPipeline *Pipeline, const char *ElementName); virtual void Disconnect(); virtual void PushTexture(const uint8_t *TextureData, size_t TextureSize); private: std::string m_Name; GstElement *m_AppSrc = nullptr; int m_Width = 0; int m_Height = 0; }; IGstAppSrc *IGstAppSrc::CreateInstance() { auto Obj = new FGstAppSrcImpl(); GST_LOG_DBG_A("GstAppSrc: CreateInstance %p", Obj); return Obj; } void FGstAppSrcImpl::Destroy() { GST_LOG_DBG_A("GstAppSrc: Destroy %p", this); delete this; } bool FGstAppSrcImpl::Connect(IGstPipeline *Pipeline, const char *ElementName) { GST_LOG_DBG_A("GstAppSrc: Connect <%s>", ElementName); if (m_AppSrc) { GST_LOG_ERR_A("GstAppSrc: Already connected"); return false; } for (;;) { m_Name = ElementName; m_AppSrc = gst_bin_get_by_name(GST_BIN(Pipeline->GetGPipeline()), ElementName); if (!m_AppSrc) { GST_LOG_ERR_A("gst_bin_get_by_name failed"); break; } g_object_set(m_AppSrc, "emit-signals", TRUE, nullptr); GST_LOG_DBG_A("GstAppSrc: Connect SUCCESS"); return true; } GST_LOG_ERR_A("GstAppSrc: Connect FAILED"); Disconnect(); return false; } void FGstAppSrcImpl::Disconnect() { if (m_AppSrc) { GST_LOG_DBG_A("GstAppSrc: Disconnect <%s>", m_Name.c_str()); gst_app_src_end_of_stream(GST_APP_SRC(m_AppSrc)); g_object_set(m_AppSrc, "emit-signals", FALSE, nullptr); gst_object_unref(m_AppSrc); m_AppSrc = nullptr; } m_Width = 0; m_Height = 0; } void FGstAppSrcImpl::PushTexture(const uint8_t *TextureData, size_t TextureSize) { GstBuffer *buffer = gst_buffer_new_allocate(nullptr, TextureSize, nullptr); gst_buffer_fill(buffer, 0, TextureData, TextureSize); const GstFlowReturn result = gst_app_src_push_buffer(GST_APP_SRC(m_AppSrc), buffer); GST_LOG_DBG_A("GstAppSrc: GstFlowReturn <%s> TextureSize <%i>", gst_flow_get_name(result), TextureSize); }
23.252525
106
0.703736
[ "vector" ]
d530fe1f8b2db2b1a7bb4f761076739daeeb3594
3,265
cpp
C++
test/style_parser.cpp
free1978/mapbox-gl-native
2a50fccd24e762d0de5a53bac358e5ddfea8d213
[ "BSD-2-Clause" ]
2
2017-02-28T22:41:54.000Z
2020-02-13T20:54:55.000Z
test/style_parser.cpp
free1978/mapbox-gl-native
2a50fccd24e762d0de5a53bac358e5ddfea8d213
[ "BSD-2-Clause" ]
null
null
null
test/style_parser.cpp
free1978/mapbox-gl-native
2a50fccd24e762d0de5a53bac358e5ddfea8d213
[ "BSD-2-Clause" ]
null
null
null
#include "gtest/gtest.h" #include <mbgl/style/style.hpp> #include <mbgl/util/io.hpp> #include <rapidjson/document.h> #include "./fixtures/fixture_log.hpp" #include <iostream> #include <fstream> #include <dirent.h> const std::string base_directory = []{ std::string fn = __FILE__; fn.erase(fn.find_last_of("/")); return fn + "/fixtures/style_parser"; }(); using namespace mbgl; typedef std::pair<uint32_t, std::string> Message; typedef std::vector<Message> Messages; class StyleParserTest : public ::testing::TestWithParam<std::string> {}; TEST_P(StyleParserTest, ParseStyle) { const std::string &base = base_directory + "/" + GetParam(); const std::string style_path = base + ".style.json"; const std::string info = util::read_file(base + ".info.json"); // Parse settings. rapidjson::Document doc; doc.Parse<0>((const char *const)info.c_str()); ASSERT_EQ(false, doc.HasParseError()); ASSERT_EQ(true, doc.IsObject()); std::ifstream stylefile(style_path); ASSERT_TRUE(stylefile.good()); std::stringstream stylejson; stylejson << stylefile.rdbuf(); const FixtureLogBackend &log = Log::Set<FixtureLogBackend>(); Style style; style.loadJSON((const uint8_t *)stylejson.str().c_str()); for (auto it = doc.MemberBegin(), end = doc.MemberEnd(); it != end; it++) { const std::string name { it->name.GetString(), it->name.GetStringLength() }; const rapidjson::Value &value = it->value; ASSERT_EQ(true, value.IsObject()); if (value.HasMember("log")) { const rapidjson::Value &js_log = value["log"]; ASSERT_EQ(true, js_log.IsArray()); for (rapidjson::SizeType i = 0; i < js_log.Size(); i++) { const rapidjson::Value &js_entry = js_log[i]; ASSERT_EQ(true, js_entry.IsArray()); const uint32_t count = js_entry[rapidjson::SizeType(0)].GetUint(); const FixtureLogBackend::LogMessage message { EventSeverityClass(js_entry[rapidjson::SizeType(1)].GetString()), EventClass(js_entry[rapidjson::SizeType(2)].GetString()), js_entry[rapidjson::SizeType(3)].GetString() }; EXPECT_EQ(count, log.count(message)) << "Message: " << message << std::endl; } } const auto &unchecked = log.unchecked(); if (unchecked.size()) { std::cerr << "Unchecked Log Messages (" << base << "/" << name << "): " << std::endl << unchecked; } ASSERT_EQ(0ul, unchecked.size()); } } INSTANTIATE_TEST_CASE_P(StyleParser, StyleParserTest, ::testing::ValuesIn([] { std::vector<std::string> names; const std::string ending = ".info.json"; DIR *dir = opendir(base_directory.c_str()); if (dir == nullptr) { return names; } for (dirent *dp = nullptr; (dp = readdir(dir)) != nullptr;) { const std::string name = dp->d_name; if (name.length() >= ending.length() && name.compare(name.length() - ending.length(), ending.length(), ending) == 0) { names.push_back(name.substr(0, name.length() - ending.length())); } } closedir(dir); return names; }()));
32.009804
126
0.603369
[ "vector" ]
d53336bbbbf351e8f48d8ed12c3fe45e86e728af
17,314
cpp
C++
src/agent/Core/Controller/InitRequest.cpp
mjgiarlo/passenger
3fef0f2c8b67899a5b38600b86f6390c4a81846d
[ "MIT" ]
1
2019-04-04T17:58:39.000Z
2019-04-04T17:58:39.000Z
src/agent/Core/Controller/InitRequest.cpp
mjgiarlo/passenger
3fef0f2c8b67899a5b38600b86f6390c4a81846d
[ "MIT" ]
9
2020-02-28T22:41:55.000Z
2022-03-30T22:43:28.000Z
src/agent/Core/Controller/InitRequest.cpp
mjgiarlo/passenger
3fef0f2c8b67899a5b38600b86f6390c4a81846d
[ "MIT" ]
3
2020-09-13T17:32:16.000Z
2021-03-03T16:33:04.000Z
/* * Phusion Passenger - https://www.phusionpassenger.com/ * Copyright (c) 2011-2018 Phusion Holding B.V. * * "Passenger", "Phusion Passenger" and "Union Station" are registered * trademarks of Phusion Holding B.V. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <Core/Controller.h> #include <AppTypeDetector/Detector.h> /************************************************************************* * * Implements Core::Controller methods pertaining the initialization * of a request. * *************************************************************************/ namespace Passenger { namespace Core { using namespace std; using namespace boost; /**************************** * * Private methods * ****************************/ struct Controller::RequestAnalysis { const LString *flags; ServerKit::HeaderTable::Cell *appGroupNameCell; }; void Controller::initializeFlags(Client *client, Request *req, RequestAnalysis &analysis) { if (analysis.flags != NULL) { const LString::Part *part = analysis.flags->start; while (part != NULL) { const char *data = part->data; const char *end = part->data + part->size; while (data < end) { switch (*data) { case 'D': req->dechunkResponse = true; break; case 'B': req->requestBodyBuffering = true; break; case 'S': req->https = true; break; case 'C': req->strip100ContinueHeader = true; break; default: break; } data++; } part = part->next; } if (OXT_UNLIKELY(LoggingKit::getLevel() >= LoggingKit::DEBUG2)) { if (req->dechunkResponse) { SKC_TRACE(client, 2, "Dechunk flag detected"); } if (req->requestBodyBuffering) { SKC_TRACE(client, 2, "Request body buffering enabled"); } if (req->https) { SKC_TRACE(client, 2, "HTTPS flag detected"); } if (req->strip100ContinueHeader) { SKC_TRACE(client, 2, "Stripping 100 Continue header"); } } } } bool Controller::respondFromTurboCache(Client *client, Request *req) { if (!turboCaching.isEnabled() || !turboCaching.responseCache.prepareRequest(this, req)) { return false; } SKC_TRACE(client, 2, "Turbocaching: trying to reply from cache (key \"" << cEscapeString(req->cacheKey) << "\")"); SKC_TRACE(client, 2, "Turbocache entries:\n" << turboCaching.responseCache.inspect()); if (turboCaching.responseCache.requestAllowsFetching(req)) { ResponseCache<Request>::Entry entry(turboCaching.responseCache.fetch(req, ev_now(getLoop()))); if (entry.valid()) { SKC_TRACE(client, 2, "Turbocaching: cache hit (key \"" << cEscapeString(req->cacheKey) << "\")"); turboCaching.writeResponse(this, client, req, entry); if (!req->ended()) { endRequest(&client, &req); } return true; } else { SKC_TRACE(client, 2, "Turbocaching: cache miss: " << entry.getCacheMissReasonString() << " (key \"" << cEscapeString(req->cacheKey) << "\")"); return false; } } else { SKC_TRACE(client, 2, "Turbocaching: request not eligible for caching"); return false; } } void Controller::initializePoolOptions(Client *client, Request *req, RequestAnalysis &analysis) { boost::shared_ptr<Options> *options; if (mainConfig.singleAppMode) { P_ASSERT_EQ(poolOptionsCache.size(), 1); poolOptionsCache.lookupRandom(NULL, &options); req->options = **options; } else { ServerKit::HeaderTable::Cell *appGroupNameCell = analysis.appGroupNameCell; if (appGroupNameCell != NULL && appGroupNameCell->header->val.size > 0) { const LString *appGroupName = psg_lstr_make_contiguous( &appGroupNameCell->header->val, req->pool); HashedStaticString hAppGroupName(appGroupName->start->data, appGroupName->size); poolOptionsCache.lookup(hAppGroupName, &options); if (options != NULL) { req->options = **options; } else { createNewPoolOptions(client, req, hAppGroupName); } } else { disconnectWithError(&client, "the !~PASSENGER_APP_GROUP_NAME header must be set"); } } if (!req->ended()) { // See comment for req->envvars to learn how it is different // from req->options.environmentVariables. req->envvars = req->secureHeaders.lookup(PASSENGER_ENV_VARS); if (req->envvars != NULL && req->envvars->size > 0) { req->envvars = psg_lstr_make_contiguous(req->envvars, req->pool); req->options.environmentVariables = StaticString( req->envvars->start->data, req->envvars->size); } // Allow certain options to be overridden on a per-request basis fillPoolOption(req, req->options.maxRequests, PASSENGER_MAX_REQUESTS); } } void Controller::fillPoolOptionsFromConfigCaches(Options &options, psg_pool_t *pool, const ControllerRequestConfigPtr &requestConfig) { options.ruby = requestConfig->defaultRuby; options.nodejs = requestConfig->defaultNodejs; options.python = requestConfig->defaultPython; options.meteorAppSettings = requestConfig->defaultMeteorAppSettings; options.fileDescriptorUlimit = requestConfig->defaultAppFileDescriptorUlimit; options.logLevel = int(LoggingKit::getLevel()); options.integrationMode = psg_pstrdup(pool, mainConfig.integrationMode); options.userSwitching = mainConfig.userSwitching; options.defaultUser = requestConfig->defaultUser; options.defaultGroup = requestConfig->defaultGroup; options.minProcesses = requestConfig->defaultMinInstances; options.maxPreloaderIdleTime = requestConfig->defaultMaxPreloaderIdleTime; options.maxRequestQueueSize = requestConfig->defaultMaxRequestQueueSize; options.abortWebsocketsOnProcessShutdown = requestConfig->defaultAbortWebsocketsOnProcessShutdown; options.forceMaxConcurrentRequestsPerProcess = requestConfig->defaultForceMaxConcurrentRequestsPerProcess; options.environment = requestConfig->defaultEnvironment; options.spawnMethod = requestConfig->defaultSpawnMethod; options.loadShellEnvvars = requestConfig->defaultLoadShellEnvvars; options.statThrottleRate = mainConfig.statThrottleRate; options.maxRequests = requestConfig->defaultMaxRequests; /******************************/ } void Controller::fillPoolOption(Request *req, StaticString &field, const HashedStaticString &name) { const LString *value = req->secureHeaders.lookup(name); if (value != NULL && value->size > 0) { value = psg_lstr_make_contiguous(value, req->pool); field = StaticString(value->start->data, value->size); } } void Controller::fillPoolOption(Request *req, bool &field, const HashedStaticString &name) { const LString *value = req->secureHeaders.lookup(name); if (value != NULL && value->size > 0) { field = psg_lstr_first_byte(value) == 't'; } } void Controller::fillPoolOption(Request *req, int &field, const HashedStaticString &name) { const LString *value = req->secureHeaders.lookup(name); if (value != NULL && value->size > 0) { value = psg_lstr_make_contiguous(value, req->pool); field = stringToInt(StaticString(value->start->data, value->size)); } } void Controller::fillPoolOption(Request *req, unsigned int &field, const HashedStaticString &name) { const LString *value = req->secureHeaders.lookup(name); if (value != NULL && value->size > 0) { value = psg_lstr_make_contiguous(value, req->pool); field = stringToUint(StaticString(value->start->data, value->size)); } } void Controller::fillPoolOption(Request *req, unsigned long &field, const HashedStaticString &name) { const LString *value = req->secureHeaders.lookup(name); if (value != NULL && value->size > 0) { value = psg_lstr_make_contiguous(value, req->pool); field = stringToUint(StaticString(value->start->data, value->size)); } } void Controller::fillPoolOption(Request *req, long &field, const HashedStaticString &name) { const LString *value = req->secureHeaders.lookup(name); if (value != NULL && value->size > 0) { value = psg_lstr_make_contiguous(value, req->pool); field = stringToInt(StaticString(value->start->data, value->size)); } } void Controller::fillPoolOptionSecToMsec(Request *req, unsigned int &field, const HashedStaticString &name) { const LString *value = req->secureHeaders.lookup(name); if (value != NULL && value->size > 0) { value = psg_lstr_make_contiguous(value, req->pool); field = stringToInt(StaticString(value->start->data, value->size)) * 1000; } } void Controller::createNewPoolOptions(Client *client, Request *req, const HashedStaticString &appGroupName) { ServerKit::HeaderTable &secureHeaders = req->secureHeaders; Options &options = req->options; SKC_TRACE(client, 2, "Creating new pool options: app group name=" << appGroupName); options = Options(); const LString *scriptName = secureHeaders.lookup("!~SCRIPT_NAME"); const LString *appRoot = secureHeaders.lookup("!~PASSENGER_APP_ROOT"); if (scriptName == NULL || scriptName->size == 0) { if (appRoot == NULL || appRoot->size == 0) { const LString *documentRoot = secureHeaders.lookup("!~DOCUMENT_ROOT"); if (OXT_UNLIKELY(documentRoot == NULL || documentRoot->size == 0)) { disconnectWithError(&client, "client did not send a !~PASSENGER_APP_ROOT or a !~DOCUMENT_ROOT header"); return; } documentRoot = psg_lstr_make_contiguous(documentRoot, req->pool); appRoot = psg_lstr_create(req->pool, extractDirNameStatic(StaticString(documentRoot->start->data, documentRoot->size))); } else { appRoot = psg_lstr_make_contiguous(appRoot, req->pool); } options.appRoot = HashedStaticString(appRoot->start->data, appRoot->size); } else { if (appRoot == NULL || appRoot->size == 0) { const LString *documentRoot = secureHeaders.lookup("!~DOCUMENT_ROOT"); if (OXT_UNLIKELY(documentRoot == NULL || documentRoot->size == 0)) { disconnectWithError(&client, "client did not send a !~DOCUMENT_ROOT header"); return; } documentRoot = psg_lstr_null_terminate(documentRoot, req->pool); documentRoot = resolveSymlink(StaticString(documentRoot->start->data, documentRoot->size), req->pool); appRoot = psg_lstr_create(req->pool, extractDirNameStatic(StaticString(documentRoot->start->data, documentRoot->size))); } else { appRoot = psg_lstr_make_contiguous(appRoot, req->pool); } options.appRoot = HashedStaticString(appRoot->start->data, appRoot->size); scriptName = psg_lstr_make_contiguous(scriptName, req->pool); options.baseURI = StaticString(scriptName->start->data, scriptName->size); } fillPoolOptionsFromConfigCaches(options, req->pool, req->config); const LString *appType = secureHeaders.lookup("!~PASSENGER_APP_TYPE"); if (appType == NULL || appType->size == 0) { const LString *appStartCommand = secureHeaders.lookup("!~PASSENGER_APP_START_COMMAND"); if (appStartCommand == NULL || appStartCommand->size == 0) { AppTypeDetector::Detector detector(*wrapperRegistry); AppTypeDetector::Detector::Result result = detector.checkAppRoot(options.appRoot); if (result.isNull()) { disconnectWithError(&client, "client did not send a recognized !~PASSENGER_APP_TYPE header"); return; } options.appType = result.wrapperRegistryEntry->language; } else { fillPoolOption(req, options.appStartCommand, "!~PASSENGER_APP_START_COMMAND"); } } else { fillPoolOption(req, options.appType, "!~PASSENGER_APP_TYPE"); } options.appGroupName = appGroupName; fillPoolOption(req, options.appLogFile, "!~PASSENGER_APP_LOG_FILE"); fillPoolOption(req, options.environment, "!~PASSENGER_APP_ENV"); fillPoolOption(req, options.ruby, "!~PASSENGER_RUBY"); fillPoolOption(req, options.python, "!~PASSENGER_PYTHON"); fillPoolOption(req, options.nodejs, "!~PASSENGER_NODEJS"); fillPoolOption(req, options.meteorAppSettings, "!~PASSENGER_METEOR_APP_SETTINGS"); fillPoolOption(req, options.user, "!~PASSENGER_USER"); fillPoolOption(req, options.group, "!~PASSENGER_GROUP"); fillPoolOption(req, options.minProcesses, "!~PASSENGER_MIN_PROCESSES"); fillPoolOption(req, options.spawnMethod, "!~PASSENGER_SPAWN_METHOD"); fillPoolOption(req, options.appStartCommand, "!~PASSENGER_APP_START_COMMAND"); fillPoolOptionSecToMsec(req, options.startTimeout, "!~PASSENGER_START_TIMEOUT"); fillPoolOption(req, options.maxPreloaderIdleTime, "!~PASSENGER_MAX_PRELOADER_IDLE_TIME"); fillPoolOption(req, options.maxRequestQueueSize, "!~PASSENGER_MAX_REQUEST_QUEUE_SIZE"); fillPoolOption(req, options.abortWebsocketsOnProcessShutdown, "!~PASSENGER_ABORT_WEBSOCKETS_ON_PROCESS_SHUTDOWN"); fillPoolOption(req, options.forceMaxConcurrentRequestsPerProcess, "!~PASSENGER_FORCE_MAX_CONCURRENT_REQUESTS_PER_PROCESS"); fillPoolOption(req, options.restartDir, "!~PASSENGER_RESTART_DIR"); fillPoolOption(req, options.startupFile, "!~PASSENGER_STARTUP_FILE"); fillPoolOption(req, options.loadShellEnvvars, "!~PASSENGER_LOAD_SHELL_ENVVARS"); fillPoolOption(req, options.fileDescriptorUlimit, "!~PASSENGER_APP_FILE_DESCRIPTOR_ULIMIT"); fillPoolOption(req, options.raiseInternalError, "!~PASSENGER_RAISE_INTERNAL_ERROR"); fillPoolOption(req, options.lveMinUid, "!~PASSENGER_LVE_MIN_UID"); // maxProcesses is configured per-application by the (Enterprise) maxInstances option (and thus passed // via request headers). In OSS the max processes can also be configured, but on a global level // (i.e. the same for all apps) using the maxInstancesPerApp option. As an easy implementation shortcut // we apply maxInstancesPerApp to options.maxProcesses (which can be overridden by Enterprise). options.maxProcesses = mainConfig.maxInstancesPerApp; /******************/ boost::shared_ptr<Options> optionsCopy = boost::make_shared<Options>(options); optionsCopy->persist(options); optionsCopy->clearPerRequestFields(); poolOptionsCache.insert(options.getAppGroupName(), optionsCopy); } void Controller::setStickySessionId(Client *client, Request *req) { if (req->stickySession) { // TODO: This is not entirely correct. Clients MAY send multiple Cookie // headers, although this is in practice extremely rare. // http://stackoverflow.com/questions/16305814/are-multiple-cookie-headers-allowed-in-an-http-request const LString *cookieHeader = req->headers.lookup(HTTP_COOKIE); if (cookieHeader != NULL && cookieHeader->size > 0) { const LString *cookieName = getStickySessionCookieName(req); vector< pair<StaticString, StaticString> > cookies; pair<StaticString, StaticString> cookie; parseCookieHeader(req->pool, cookieHeader, cookies); foreach (cookie, cookies) { if (psg_lstr_cmp(cookieName, cookie.first)) { // This cookie matches the one we're looking for. req->options.stickySessionId = stringToUint(cookie.second); return; } } } } } const LString * Controller::getStickySessionCookieName(Request *req) { const LString *value = req->headers.lookup(PASSENGER_STICKY_SESSIONS_COOKIE_NAME); if (value == NULL || value->size == 0) { return psg_lstr_create(req->pool, req->config->defaultStickySessionsCookieName); } else { return value; } } /**************************** * * Protected methods * ****************************/ void Controller::onRequestBegin(Client *client, Request *req) { ParentClass::onRequestBegin(client, req); CC_BENCHMARK_POINT(client, req, BM_AFTER_ACCEPT); { // Perform hash table operations as close to header parsing as possible, // and localize them as much as possible, for better CPU caching. RequestAnalysis analysis; analysis.flags = req->secureHeaders.lookup(FLAGS); analysis.appGroupNameCell = mainConfig.singleAppMode ? NULL : req->secureHeaders.lookupCell(PASSENGER_APP_GROUP_NAME); req->stickySession = getBoolOption(req, PASSENGER_STICKY_SESSIONS, mainConfig.defaultStickySessions); req->host = req->headers.lookup(HTTP_HOST); /***************/ /***************/ SKC_TRACE(client, 2, "Initiating request"); req->startedAt = ev_now(getLoop()); req->bodyChannel.stop(); initializeFlags(client, req, analysis); if (respondFromTurboCache(client, req)) { return; } initializePoolOptions(client, req, analysis); if (req->ended()) { return; } if (req->ended()) { return; } setStickySessionId(client, req); } if (!req->hasBody() || !req->requestBodyBuffering) { req->requestBodyBuffering = false; checkoutSession(client, req); } else { beginBufferingBody(client, req); } } } // namespace Core } // namespace Passenger
35.552361
124
0.720688
[ "vector" ]
d53988016f0869f1fea0bffc9d63a40812c246ad
5,581
cc
C++
src/runtime/module.cc
sufeidechabei/dgl
f9f92803b422c04b6d8e3f95b18f71cf158f3b1f
[ "Apache-2.0" ]
1
2020-03-06T01:30:23.000Z
2020-03-06T01:30:23.000Z
src/runtime/module.cc
sufeidechabei/dgl
f9f92803b422c04b6d8e3f95b18f71cf158f3b1f
[ "Apache-2.0" ]
null
null
null
src/runtime/module.cc
sufeidechabei/dgl
f9f92803b422c04b6d8e3f95b18f71cf158f3b1f
[ "Apache-2.0" ]
null
null
null
/*! * Copyright (c) 2017 by Contributors * \file module.cc * \brief TVM module system */ #include <dgl/runtime/module.h> #include <dgl/runtime/registry.h> #include <dgl/runtime/packed_func.h> #include <unordered_set> #include <cstring> #ifndef _LIBCPP_SGX_CONFIG #include "file_util.h" #endif namespace tvm { namespace runtime { void Module::Import(Module other) { // specially handle rpc if (!std::strcmp((*this)->type_key(), "rpc")) { static const PackedFunc* fimport_ = nullptr; if (fimport_ == nullptr) { fimport_ = runtime::Registry::Get("rpc._ImportRemoteModule"); CHECK(fimport_ != nullptr); } (*fimport_)(*this, other); return; } // cyclic detection. std::unordered_set<const ModuleNode*> visited{other.node_.get()}; std::vector<const ModuleNode*> stack{other.node_.get()}; while (!stack.empty()) { const ModuleNode* n = stack.back(); stack.pop_back(); for (const Module& m : n->imports_) { const ModuleNode* next = m.node_.get(); if (visited.count(next)) continue; visited.insert(next); stack.push_back(next); } } CHECK(!visited.count(node_.get())) << "Cyclic dependency detected during import"; node_->imports_.emplace_back(std::move(other)); } Module Module::LoadFromFile(const std::string& file_name, const std::string& format) { #ifndef _LIBCPP_SGX_CONFIG std::string fmt = GetFileFormat(file_name, format); CHECK(fmt.length() != 0) << "Cannot deduce format of file " << file_name; if (fmt == "dll" || fmt == "dylib" || fmt == "dso") { fmt = "so"; } std::string load_f_name = "module.loadfile_" + fmt; const PackedFunc* f = Registry::Get(load_f_name); CHECK(f != nullptr) << "Loader of " << format << "(" << load_f_name << ") is not presented."; Module m = (*f)(file_name, format); return m; #else LOG(FATAL) << "SGX does not support LoadFromFile"; #endif } void ModuleNode::SaveToFile(const std::string& file_name, const std::string& format) { LOG(FATAL) << "Module[" << type_key() << "] does not support SaveToFile"; } void ModuleNode::SaveToBinary(dmlc::Stream* stream) { LOG(FATAL) << "Module[" << type_key() << "] does not support SaveToBinary"; } std::string ModuleNode::GetSource(const std::string& format) { LOG(FATAL) << "Module[" << type_key() << "] does not support GetSource"; return ""; } const PackedFunc* ModuleNode::GetFuncFromEnv(const std::string& name) { auto it = import_cache_.find(name); if (it != import_cache_.end()) return it->second.get(); PackedFunc pf; for (Module& m : this->imports_) { pf = m.GetFunction(name, false); if (pf != nullptr) break; } if (pf == nullptr) { const PackedFunc* f = Registry::Get(name); CHECK(f != nullptr) << "Cannot find function " << name << " in the imported modules or global registry"; return f; } else { std::unique_ptr<PackedFunc> f(new PackedFunc(pf)); import_cache_[name] = std::move(f); return import_cache_.at(name).get(); } } bool RuntimeEnabled(const std::string& target) { std::string f_name; if (target == "cpu") { return true; } else if (target == "cuda" || target == "gpu") { f_name = "device_api.gpu"; } else if (target == "cl" || target == "opencl" || target == "sdaccel") { f_name = "device_api.opencl"; } else if (target == "gl" || target == "opengl") { f_name = "device_api.opengl"; } else if (target == "mtl" || target == "metal") { f_name = "device_api.metal"; } else if (target == "vulkan") { f_name = "device_api.vulkan"; } else if (target == "stackvm") { f_name = "codegen.build_stackvm"; } else if (target == "rpc") { f_name = "device_api.rpc"; } else if (target == "vpi" || target == "verilog") { f_name = "device_api.vpi"; } else if (target.length() >= 5 && target.substr(0, 5) == "nvptx") { f_name = "device_api.gpu"; } else if (target.length() >= 4 && target.substr(0, 4) == "rocm") { f_name = "device_api.rocm"; } else if (target.length() >= 4 && target.substr(0, 4) == "llvm") { const PackedFunc* pf = runtime::Registry::Get("codegen.llvm_target_enabled"); if (pf == nullptr) return false; return (*pf)(target); } else { LOG(FATAL) << "Unknown optional runtime " << target; } return runtime::Registry::Get(f_name) != nullptr; } TVM_REGISTER_GLOBAL("module._Enabled") .set_body([](TVMArgs args, TVMRetValue *ret) { *ret = RuntimeEnabled(args[0]); }); TVM_REGISTER_GLOBAL("module._GetSource") .set_body([](TVMArgs args, TVMRetValue *ret) { *ret = args[0].operator Module()->GetSource(args[1]); }); TVM_REGISTER_GLOBAL("module._ImportsSize") .set_body([](TVMArgs args, TVMRetValue *ret) { *ret = static_cast<int64_t>( args[0].operator Module()->imports().size()); }); TVM_REGISTER_GLOBAL("module._GetImport") .set_body([](TVMArgs args, TVMRetValue *ret) { *ret = args[0].operator Module()-> imports().at(args[1].operator int()); }); TVM_REGISTER_GLOBAL("module._GetTypeKey") .set_body([](TVMArgs args, TVMRetValue *ret) { *ret = std::string(args[0].operator Module()->type_key()); }); TVM_REGISTER_GLOBAL("module._LoadFromFile") .set_body([](TVMArgs args, TVMRetValue *ret) { *ret = Module::LoadFromFile(args[0], args[1]); }); TVM_REGISTER_GLOBAL("module._SaveToFile") .set_body([](TVMArgs args, TVMRetValue *ret) { args[0].operator Module()-> SaveToFile(args[1], args[2]); }); } // namespace runtime } // namespace tvm
31.710227
81
0.626232
[ "vector" ]
d53a796aa0baceebb4758d711bc95bff8f666bdb
12,229
cpp
C++
src/libtsduck/dtv/signalization/tsDescriptor.cpp
harmonicinc-com/tsduck
67f25161a3b37b1f3c486d5ef2e013486c3d9893
[ "BSD-2-Clause" ]
542
2017-06-21T07:40:10.000Z
2022-03-29T13:44:39.000Z
src/libtsduck/dtv/signalization/tsDescriptor.cpp
harmonicinc-com/tsduck
67f25161a3b37b1f3c486d5ef2e013486c3d9893
[ "BSD-2-Clause" ]
939
2017-09-01T21:00:42.000Z
2022-03-31T14:39:27.000Z
src/libtsduck/dtv/signalization/tsDescriptor.cpp
harmonicinc-com/tsduck
67f25161a3b37b1f3c486d5ef2e013486c3d9893
[ "BSD-2-Clause" ]
167
2017-10-30T12:07:29.000Z
2022-03-23T11:36:10.000Z
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2021, Thierry Lelegard // 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. // // 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 "tsDescriptor.h" #include "tsMemory.h" #include "tsAbstractDescriptor.h" #include "tsAbstractTable.h" #include "tsPSIRepository.h" #include "tsxmlElement.h" #include "tsNames.h" //---------------------------------------------------------------------------- // Constructors for Descriptor // Note that the max size of a descriptor is 257 bytes: 2 (header) + 255 //---------------------------------------------------------------------------- ts::Descriptor::Descriptor(const void* addr, size_t size) : _data(size >= 2 && size < 258 && (reinterpret_cast<const uint8_t*>(addr))[1] == size - 2 ? new ByteBlock(addr, size) : nullptr) { } ts::Descriptor::Descriptor(const ByteBlock& bb) : _data(bb.size() >= 2 && bb.size() < 258 && bb[1] == bb.size() - 2 ? new ByteBlock(bb) : nullptr) { } ts::Descriptor::Descriptor(DID tag, const void* data, size_t size) : _data(size < 256 ? new ByteBlock(size + 2) : nullptr) { if (!_data.isNull()) { (*_data)[0] = tag; (*_data)[1] = uint8_t(size); ::memcpy(_data->data() + 2, data, size); } } ts::Descriptor::Descriptor(DID tag, const ByteBlock& data) : _data(data.size() < 256 ? new ByteBlock(2) : nullptr) { if (!_data.isNull()) { (*_data)[0] = tag; (*_data)[1] = uint8_t(data.size()); _data->append(data); } } ts::Descriptor::Descriptor(const ByteBlockPtr& bbp, ShareMode mode) : _data(nullptr) { if (!bbp.isNull() && bbp->size() >= 2 && bbp->size() < 258 && (*bbp)[1] == bbp->size() - 2) { switch (mode) { case ShareMode::SHARE: _data = bbp; break; case ShareMode::COPY: _data = new ByteBlock(*bbp); break; default: // should not get there assert(false); } } } ts::Descriptor::Descriptor(const Descriptor& desc, ShareMode mode) : _data(nullptr) { switch (mode) { case ShareMode::SHARE: _data = desc._data; break; case ShareMode::COPY: _data = new ByteBlock(*desc._data); break; default: // should not get there assert(false); } } ts::Descriptor::Descriptor(Descriptor&& desc) noexcept : _data(std::move(desc._data)) { } //---------------------------------------------------------------------------- // Assignment operators. //---------------------------------------------------------------------------- ts::Descriptor& ts::Descriptor::operator=(const Descriptor& desc) { if (&desc != this) { _data = desc._data; } return *this; } ts::Descriptor& ts::Descriptor::operator=(Descriptor&& desc) noexcept { if (&desc != this) { _data = std::move(desc._data); } return *this; } ts::Descriptor& ts::Descriptor::copy(const Descriptor& desc) { if (&desc != this) { _data = new ByteBlock(*desc._data); } return *this; } //---------------------------------------------------------------------------- // Get the extended descriptor id. //---------------------------------------------------------------------------- ts::EDID ts::Descriptor::edid(PDS pds, const AbstractTable* table) const { return edid(pds, table == nullptr ? TID(TID_NULL) : table->tableId()); } ts::EDID ts::Descriptor::edid(PDS pds, TID tid) const { if (!isValid()) { return EDID(); // invalid value. } const DID did = tag(); if (tid != TID_NULL && names::HasTableSpecificName(did, tid)) { // Table-specific descriptor. return EDID::TableSpecific(did, tid); } else if (did >= 0x80) { // Private descriptor. return EDID::Private(did, pds); } else if (did == DID_DVB_EXTENSION && payloadSize() > 0) { // DVB extension descriptor. return EDID::ExtensionDVB(payload()[0]); } else if (did == DID_MPEG_EXTENSION && payloadSize() > 0) { // MPEG extension descriptor. return EDID::ExtensionMPEG(payload()[0]); } else { // Standard descriptor. return EDID::Standard(did); } } //---------------------------------------------------------------------------- // Replace the payload of the descriptor. The tag is unchanged, // the size is adjusted. //---------------------------------------------------------------------------- void ts::Descriptor::replacePayload(const void* addr, size_t size) { if (size > 255) { // Payload size too long, invalidate descriptor _data.clear(); } else if (!_data.isNull()) { assert(_data->size() >= 2); // Erase previous payload _data->erase(2, _data->size() - 2); // Add new payload _data->append (addr, size); // Adjust descriptor size (*_data)[1] = uint8_t (_data->size() - 2); } } //---------------------------------------------------------------------------- // Resize (truncate or extend) the payload of the descriptor. // The tag is unchanged, the size is adjusted. // If the payload is extended, new bytes are zeroes. //---------------------------------------------------------------------------- void ts::Descriptor::resizePayload(size_t new_size) { if (new_size > 255) { // Payload size too long, invalidate descriptor _data.clear(); } else if (!_data.isNull()) { assert(_data->size() >= 2); size_t old_size = _data->size() - 2; _data->resize (new_size + 2); // If payload extended, zero additional bytes if (new_size > old_size) { Zero(_data->data() + 2 + old_size, new_size - old_size); } // Adjust descriptor size (*_data)[1] = uint8_t (_data->size() - 2); } } //---------------------------------------------------------------------------- // Comparison //---------------------------------------------------------------------------- bool ts::Descriptor::operator== (const Descriptor& desc) const { return _data == desc._data || (_data.isNull() && desc._data.isNull()) || (!_data.isNull() && !desc._data.isNull() && *_data == *desc._data); } //---------------------------------------------------------------------------- // Deserialize the descriptor. //---------------------------------------------------------------------------- ts::AbstractDescriptorPtr ts::Descriptor::deserialize(DuckContext& duck, PDS pds, const AbstractTable* table) const { return deserialize(duck, pds, table == nullptr ? TID(TID_NULL) : table->tableId()); } ts::AbstractDescriptorPtr ts::Descriptor::deserialize(DuckContext& duck, PDS pds, TID tid) const { // Do we know how to deserialize this descriptor? PSIRepository::DescriptorFactory fac = PSIRepository::Instance()->getDescriptorFactory(edid(pds), tid); if (fac != nullptr) { // We know how to deserialize it. AbstractDescriptorPtr dp(fac()); if (!dp.isNull()) { // Deserialize from binary to object. dp->deserialize(duck, *this); if (dp->isValid()) { // Successfully deserialized. return dp; } } } return AbstractDescriptorPtr(); // null pointer } //---------------------------------------------------------------------------- // This method converts a descriptor to XML. //---------------------------------------------------------------------------- ts::xml::Element* ts::Descriptor::toXML(DuckContext& duck, xml::Element* parent, PDS pds, TID tid, bool forceGeneric) const { // Filter invalid descriptors. if (!isValid()) { return nullptr; } // The XML node we will generate. xml::Element* node = nullptr; // Try to generate a specialized XML structure. if (!forceGeneric) { const AbstractDescriptorPtr dp(deserialize(duck, pds, tid)); if (!dp.isNull()) { // Serialize from object to XML. node = dp->toXML(duck, parent); } } // If we could not generate a typed node, generate a generic one. if (node == nullptr) { // Create the XML node. node = parent->addElement(AbstractDescriptor::XML_GENERIC_DESCRIPTOR); node->setIntAttribute(u"tag", tag(), true); node->addHexaText(payload(), payloadSize()); } return node; } //---------------------------------------------------------------------------- // This method converts an XML node as a binary descriptor. //---------------------------------------------------------------------------- bool ts::Descriptor::fromXML(DuckContext& duck, const xml::Element* node, TID tid) { // Filter invalid parameters. invalidate(); if (node == nullptr) { // Not a valid XML name (not even an XML element). return false; } // If the table is specified and the XML descriptor is not allowed in this table, this is an error. if (!PSIRepository::Instance()->isDescriptorAllowed(node->name(), tid)) { node->report().error(u"<%s>, line %d, is not allowed here, must be in %s", { node->name(), node->lineNumber(), PSIRepository::Instance()->descriptorTables(duck, node->name())}); return false; } // Try to get the descriptor factory for that kind of XML tag. const PSIRepository::DescriptorFactory fac = PSIRepository::Instance()->getDescriptorFactory(node->name()); if (fac != nullptr) { // Create a descriptor instance of the right type. AbstractDescriptorPtr desc = fac(); if (!desc.isNull()) { desc->fromXML(duck, node); } if (!desc.isNull() && desc->isValid()) { // Serialize the descriptor. desc->serialize(duck, *this); } // The XML element name was valid. return true; } // Try to decode a generic descriptor. if (node->name().similar(AbstractDescriptor::XML_GENERIC_DESCRIPTOR)) { DID tag = 0xFF; ByteBlock payload; if (node->getIntAttribute<DID>(tag, u"tag", true, 0xFF, 0x00, 0xFF) && node->getHexaText(payload, 0, 255)) { // Build descriptor. _data = new ByteBlock(2); (*_data)[0] = tag; (*_data)[1] = uint8_t(payload.size()); _data->append(payload); return true; } else { node->report().error(u"<%s>, line %d, is not a valid descriptor", {node->name(), node->lineNumber()}); } } // The XML element name was not valid. return false; }
33.596154
131
0.52768
[ "object" ]
d53b0ab98f03988015679d265acc1ef88344ac96
1,914
cc
C++
example/reader_writer.cc
yun1129/hessian2-codec
8e61255ebe0b257173da7d5f78950f6d776c5c3d
[ "Apache-2.0" ]
1
2021-01-07T13:24:34.000Z
2021-01-07T13:24:34.000Z
example/reader_writer.cc
yun1129/hessian2-codec
8e61255ebe0b257173da7d5f78950f6d776c5c3d
[ "Apache-2.0" ]
null
null
null
example/reader_writer.cc
yun1129/hessian2-codec
8e61255ebe0b257173da7d5f78950f6d776c5c3d
[ "Apache-2.0" ]
null
null
null
#include <vector> #include <iostream> #include "hessian2/codec.hpp" #include "hessian2/basic_codec/object_codec.hpp" #include "hessian2/reader.hpp" #include "hessian2/writer.hpp" #include "absl/strings/string_view.h" struct Slice { const uint8_t* data_; size_t size_; }; class SliceReader : public ::hessian2::Reader { public: SliceReader(Slice buffer) : buffer_(buffer){}; virtual ~SliceReader() = default; virtual void RawReadNbytes(void* out, size_t len, size_t peek_offset) override { ABSL_ASSERT(ByteAvailable() + peek_offset >= len); uint8_t* dest = static_cast<uint8_t*>(out); // Offset() Returns the current position that has been read. memcpy(dest, buffer_.data_ + Offset() + peek_offset, len); } virtual uint64_t Length() const override { return buffer_.size_; } private: Slice buffer_; }; class VectorWriter : public ::hessian2::Writer { public: VectorWriter(std::vector<uint8_t>& data) : data_(data) {} ~VectorWriter() = default; virtual void RawWrite(const void* data, uint64_t size) { const char* src = static_cast<const char*>(data); for (size_t i = 0; i < size; i++) { data_.push_back(src[i]); } } virtual void RawWrite(absl::string_view data) { for (auto& ch : data) { data_.push_back(ch); } } private: std::vector<uint8_t>& data_; }; int main() { std::vector<uint8_t> data; auto writer = std::make_unique<VectorWriter>(data); ::hessian2::Encoder encode(std::move(writer)); encode.encode<std::string>("test string"); Slice s{static_cast<const uint8_t*>(data.data()), data.size()}; auto reader = std::make_unique<SliceReader>(s); ::hessian2::Decoder decode(std::move(reader)); auto ret = decode.decode<std::string>(); if (ret) { std::cout << *ret << std::endl; } else { std::cerr << "decode failed: " << decode.getErrorMessage() << std::endl; } }
27.342857
76
0.661442
[ "vector" ]
d53fa4a75a2d35a5c412fcaf57269a6727fb5dcb
14,199
cpp
C++
openlr/openlr_match_quality/openlr_assessment_tool/traffic_mode.cpp
xblonde/omim
d940a4761786c994884d2488a469635a4ac76d28
[ "Apache-2.0" ]
1
2021-01-19T08:31:19.000Z
2021-01-19T08:31:19.000Z
openlr/openlr_match_quality/openlr_assessment_tool/traffic_mode.cpp
frankiewb/omim
0d9302e7b1be470735655337f0183ad04c55b6ad
[ "Apache-2.0" ]
null
null
null
openlr/openlr_match_quality/openlr_assessment_tool/traffic_mode.cpp
frankiewb/omim
0d9302e7b1be470735655337f0183ad04c55b6ad
[ "Apache-2.0" ]
null
null
null
#include "openlr/openlr_match_quality/openlr_assessment_tool/traffic_mode.hpp" #include "openlr/openlr_model_xml.hpp" #include "indexer/index.hpp" #include "indexer/scales.hpp" #include "base/scope_guard.hpp" #include "3party/pugixml/src/utils.hpp" #include <QItemSelection> #include <QMessageBox> #include <tuple> namespace { void RemovePointFromPull(m2::PointD const & toBeRemoved, std::vector<m2::PointD> & pool) { pool.erase( remove_if(begin(pool), end(pool), [&toBeRemoved](m2::PointD const & p) { return p.EqualDxDy(toBeRemoved, 1e-6); }), end(pool)); } std::vector<m2::PointD> GetReachablePoints(m2::PointD const & srcPoint, std::vector<m2::PointD> const path, PointsControllerDelegateBase const & pointsDelegate, size_t const lookbackIndex) { auto reachablePoints = pointsDelegate.GetReachablePoints(srcPoint); if (lookbackIndex < path.size()) { auto const & toBeRemoved = path[path.size() - lookbackIndex - 1]; RemovePointFromPull(toBeRemoved, reachablePoints); } return reachablePoints; } } namespace impl { // static size_t const RoadPointCandidate::kInvalidId = std::numeric_limits<size_t>::max(); /// This class denotes a "non-deterministic" feature point. /// I.e. it is a set of all pairs <FeatureID, point index> /// located at a specified coordinate. /// Only one point at a time is considered active. RoadPointCandidate::RoadPointCandidate(std::vector<FeaturePoint> const & points, m2::PointD const & coord) : m_coord(coord) , m_points(points) { LOG(LDEBUG, ("Candidate points:", points)); } void RoadPointCandidate::ActivateCommonPoint(RoadPointCandidate const & rpc) { for (auto const & fp1 : m_points) { for (auto const & fp2 : rpc.m_points) { if (fp1.first == fp2.first) { SetActivePoint(fp1.first); return; } } } CHECK(false, ("One common feature id should exist.")); } FeaturePoint const & RoadPointCandidate::GetPoint() const { CHECK_NOT_EQUAL(m_activePointIndex, kInvalidId, ("No point is active.")); return m_points[m_activePointIndex]; } m2::PointD const & RoadPointCandidate::GetCoordinate() const { return m_coord; } void RoadPointCandidate::SetActivePoint(FeatureID const & fid) { for (size_t i = 0; i < m_points.size(); ++i) { if (m_points[i].first == fid) { m_activePointIndex = i; return; } } CHECK(false, ("One point should match.")); } } // namespace impl // TrafficMode ------------------------------------------------------------------------------------- TrafficMode::TrafficMode(std::string const & dataFileName, Index const & index, std::unique_ptr<TrafficDrawerDelegateBase> drawerDelegate, std::unique_ptr<PointsControllerDelegateBase> pointsDelegate, QObject * parent) : QAbstractTableModel(parent) , m_index(index) , m_drawerDelegate(move(drawerDelegate)) , m_pointsDelegate(move(pointsDelegate)) { // TODO(mgsergio): Collect stat how many segments of each kind were parsed. pugi::xml_document doc; if (!doc.load_file(dataFileName.data())) MYTHROW(TrafficModeError, ("Can't load file:", strerror(errno))); // Select all Segment elements that are direct children of the context node. auto const segments = doc.select_nodes("./Segment"); try { for (auto const xpathNode : segments) { m_segments.emplace_back(); auto const xmlSegment = xpathNode.node(); auto & segment = m_segments.back(); { // TODO(mgsergio): Unify error handling interface of openlr_xml_mode and decoded_path parsers. auto const partnerSegment = xmlSegment.child("reportSegments"); if (!openlr::SegmentFromXML(partnerSegment, segment.GetPartnerSegment())) MYTHROW(TrafficModeError, ("An error occured while parsing: can't parse segment")); segment.SetPartnerXML(partnerSegment); } if (auto const route = xmlSegment.child("Route")) { auto & path = segment.GetMatchedPath(); path.emplace(); openlr::PathFromXML(route, m_index, *path); } if (auto const route = xmlSegment.child("FakeRoute")) { auto & path = segment.GetFakePath(); path.emplace(); openlr::PathFromXML(route, m_index, *path); } if (auto const route = xmlSegment.child("GoldenRoute")) { auto & path = segment.GetGoldenPath(); path.emplace(); openlr::PathFromXML(route, m_index, *path); } } } catch (openlr::DecodedPathLoadError const & e) { MYTHROW(TrafficModeError, ("An exception occured while parsing", dataFileName, e.Msg())); } // TODO(mgsergio): LOG(LINFO, (xxx, "segments are loaded")); } // TODO(mgsergio): Check if a path was commited, or commit it. bool TrafficMode::SaveSampleAs(std::string const & fileName) const { CHECK(!fileName.empty(), ("Can't save to an empty file.")); pugi::xml_document result; for (auto const & sc : m_segments) { auto segment = result.append_child("Segment"); segment.append_copy(sc.GetPartnerXMLSegment()); if (auto const & path = sc.GetMatchedPath()) { auto node = segment.append_child("Route"); openlr::PathToXML(*path, node); } if (auto const & path = sc.GetFakePath()) { auto node = segment.append_child("FakeRoute"); openlr::PathToXML(*path, node); } if (auto const & path = sc.GetGoldenPath()) { auto node = segment.append_child("GoldenRoute"); openlr::PathToXML(*path, node); } } result.save_file(fileName.data(), " " /* indent */); return true; } int TrafficMode::rowCount(const QModelIndex & parent) const { return static_cast<int>(m_segments.size()); } int TrafficMode::columnCount(const QModelIndex & parent) const { return 1; } QVariant TrafficMode::data(const QModelIndex & index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() >= rowCount()) return QVariant(); if (role != Qt::DisplayRole && role != Qt::EditRole) return QVariant(); if (index.column() == 0) return m_segments[index.row()].GetPartnerSegmentId(); return QVariant(); } void TrafficMode::OnItemSelected(QItemSelection const & selected, QItemSelection const &) { CHECK(!selected.empty(), ("The selection should not be empty. RTFM for qt5.")); CHECK(!m_segments.empty(), ("No segments are loaded, can't select.")); auto const row = selected.front().top(); CHECK_LESS(row, m_segments.size(), ()); m_currentSegment = &m_segments[row]; auto const & partnerSegment = m_currentSegment->GetPartnerSegment().GetMercatorPoints(); auto const & viewportCenter = partnerSegment.front(); m_drawerDelegate->ClearAllPaths(); // TODO(mgsergio): Use a better way to set viewport and scale. m_drawerDelegate->SetViewportCenter(viewportCenter); m_drawerDelegate->DrawEncodedSegment(partnerSegment); if (auto const & path = m_currentSegment->GetMatchedPath()) m_drawerDelegate->DrawDecodedSegments(GetPoints(*path)); if (auto const & path = m_currentSegment->GetGoldenPath()) m_drawerDelegate->DrawGoldenPath(GetPoints(*path)); } Qt::ItemFlags TrafficMode::flags(QModelIndex const & index) const { if (!index.isValid()) return Qt::ItemIsEnabled; return QAbstractItemModel::flags(index); } void TrafficMode::StartBuildingPath() { CHECK(m_currentSegment, ("A segment should be selected before path building is started.")); if (m_buildingPath) MYTHROW(TrafficModeError, ("Path building already in progress.")); if (m_currentSegment->GetGoldenPath()) { auto const btn = QMessageBox::question( nullptr, "Override warning", "The selected segment already has a golden path. Do you want to override?"); if (btn == QMessageBox::No) return; } m_currentSegment->GetGoldenPath() = boost::none; m_buildingPath = true; m_drawerDelegate->ClearGoldenPath(); m_drawerDelegate->VisualizePoints( m_pointsDelegate->GetAllJunctionPointsInViewport()); } void TrafficMode::PushPoint(m2::PointD const & coord, std::vector<FeaturePoint> const & points) { impl::RoadPointCandidate point(points, coord); if (!m_goldenPath.empty()) m_goldenPath.back().ActivateCommonPoint(point); m_goldenPath.push_back(point); } void TrafficMode::PopPoint() { CHECK(!m_goldenPath.empty(), ("Attempt to pop point from an empty path.")); m_goldenPath.pop_back(); } void TrafficMode::CommitPath() { CHECK(m_currentSegment, ("No segments selected")); if (!m_buildingPath) MYTHROW(TrafficModeError, ("Path building is not started")); MY_SCOPE_GUARD(guard, [this]{ emit EditingStopped(); }); m_buildingPath = false; m_drawerDelegate->ClearAllVisualizedPoints(); if (m_goldenPath.size() == 1) { LOG(LDEBUG, ("Golden path is empty")); return; } CHECK_GREATER(m_goldenPath.size(), 1, ("Path cannot consist of only one point")); // Activate last point. Since no more points will be availabe we link it to the same // feature as the previous one was linked to. m_goldenPath.back().ActivateCommonPoint(m_goldenPath[GetPointsCount() - 2]); openlr::Path path; for (size_t i = 1; i < GetPointsCount(); ++i) { FeatureID fid, prevFid; size_t segId, prevSegId; auto const prevPoint = m_goldenPath[i - 1]; auto point = m_goldenPath[i]; // The start and the end of the edge should lie on the same feature. point.ActivateCommonPoint(prevPoint); std::tie(prevFid, prevSegId) = prevPoint.GetPoint(); std::tie(fid, segId) = point.GetPoint(); path.emplace_back( fid, prevSegId < segId /* forward */, prevSegId, routing::Junction(prevPoint.GetCoordinate(), 0 /* altitude */), routing::Junction(point.GetCoordinate(), 0 /* altitude */) ); } m_currentSegment->GetGoldenPath() = path; m_goldenPath.clear(); } void TrafficMode::RollBackPath() { CHECK(m_currentSegment, ("No segments selected")); // TODO(mgsergio): CHECK ? if (!m_buildingPath) MYTHROW(TrafficModeError, ("No path building is in progress.")); m_buildingPath = false; // TODO(mgsergio): Add a method for common visual manipulations. m_drawerDelegate->ClearAllVisualizedPoints(); m_drawerDelegate->ClearGoldenPath(); if (auto const & path = m_currentSegment->GetGoldenPath()) m_drawerDelegate->DrawGoldenPath(GetPoints(*path)); m_goldenPath.clear(); emit EditingStopped(); } size_t TrafficMode::GetPointsCount() const { return m_goldenPath.size(); } m2::PointD const & TrafficMode::GetPoint(size_t const index) const { return m_goldenPath[index].GetCoordinate(); } m2::PointD const & TrafficMode::GetLastPoint() const { CHECK(!m_goldenPath.empty(), ("Attempt to get point from an empty path.")); return m_goldenPath.back().GetCoordinate(); } std::vector<m2::PointD> TrafficMode::GetGoldenPathPoints() const { std::vector<m2::PointD> coordinates; for (auto const & roadPoint : m_goldenPath) coordinates.push_back(roadPoint.GetCoordinate()); return coordinates; } // TODO(mgsergio): Draw the first point when the path size is 1. void TrafficMode::HandlePoint(m2::PointD clickPoint, Qt::MouseButton const button) { if (!m_buildingPath) return; auto const currentPathLength = GetPointsCount(); auto const lastClickedPoint = currentPathLength != 0 ? GetLastPoint() : m2::PointD::Zero(); auto const & p = m_pointsDelegate->GetCandidatePoints(clickPoint); auto const & candidatePoints = p.first; clickPoint = p.second; if (candidatePoints.empty()) return; auto reachablePoints = GetReachablePoints(clickPoint, GetGoldenPathPoints(), *m_pointsDelegate, 0 /* lookBackIndex */); auto const & clickablePoints = currentPathLength != 0 ? GetReachablePoints(lastClickedPoint, GetGoldenPathPoints(), *m_pointsDelegate, 1 /* lookbackIndex */) // TODO(mgsergio): This is not quite correct since view port can change // since first call to visualize points. But it's ok in general. : m_pointsDelegate->GetAllJunctionPointsInViewport(); using ClickType = PointsControllerDelegateBase::ClickType; switch (m_pointsDelegate->CheckClick(clickPoint, lastClickedPoint, clickablePoints)) { case ClickType::Add: // TODO(mgsergio): Think of refactoring this with if (accumulator.empty) // instead of pushing point first ad then removing last selection. PushPoint(clickPoint, candidatePoints); if (currentPathLength > 0) { // TODO(mgsergio): Should I remove lastClickedPoint from clickablePoints // as well? RemovePointFromPull(lastClickedPoint, reachablePoints); m_drawerDelegate->DrawGoldenPath(GetGoldenPathPoints()); } m_drawerDelegate->ClearAllVisualizedPoints(); m_drawerDelegate->VisualizePoints(reachablePoints); m_drawerDelegate->VisualizePoints({clickPoint}); break; case ClickType::Remove: // TODO(mgsergio): Rename this case. if (button == Qt::MouseButton::LeftButton) // RemovePoint { m_drawerDelegate->ClearAllVisualizedPoints(); m_drawerDelegate->ClearGoldenPath(); PopPoint(); if (m_goldenPath.empty()) { m_drawerDelegate->VisualizePoints(m_pointsDelegate->GetAllJunctionPointsInViewport()); } else { m_drawerDelegate->VisualizePoints(GetReachablePoints( GetLastPoint(), GetGoldenPathPoints(), *m_pointsDelegate, 1 /* lookBackIndex */)); } if (GetPointsCount() > 1) m_drawerDelegate->DrawGoldenPath(GetGoldenPathPoints()); } else if (button == Qt::MouseButton::RightButton) { CommitPath(); } break; case ClickType::Miss: // TODO(mgsergio): This situation should be handled by checking candidatePoitns.empty() above. // Not shure though if all cases are handled by that check. return; } }
30.535484
102
0.672371
[ "vector" ]
d54027c5de727c195b9d2acc5c8aadcf033e3b84
14,788
hh
C++
system-test/maxtest/include/maxtest/maxscales.hh
sdrik/MaxScale
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
[ "BSD-3-Clause" ]
null
null
null
system-test/maxtest/include/maxtest/maxscales.hh
sdrik/MaxScale
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
[ "BSD-3-Clause" ]
null
null
null
system-test/maxtest/include/maxtest/maxscales.hh
sdrik/MaxScale
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <maxtest/ccdefs.hh> #include <functional> #include <string> #include <thread> #include <vector> #include <maxtest/mariadb_func.hh> #include <maxtest/nodes.hh> namespace maxtest { class MariaDB; class TestLogger; /** * Contains information about one server as seen by MaxScale. */ struct ServerInfo { using bitfield = uint32_t; static constexpr bitfield UNKNOWN = 0; static constexpr bitfield RUNNING = (1 << 0); static constexpr bitfield MASTER = (1 << 1); static constexpr bitfield SLAVE = (1 << 2); static constexpr bitfield RELAY = (1 << 3); static constexpr bitfield MAINT = (1 << 4); static constexpr bitfield DRAINING = (1 << 5); static constexpr bitfield DRAINED = (1 << 6); static constexpr bitfield SERVER_SLAVE_OF_EXT_MASTER = (1 << 10); static constexpr bitfield BLR = (1 << 12); static constexpr bitfield DOWN = (1 << 13); static constexpr bitfield master_st = MASTER | RUNNING; static constexpr bitfield slave_st = SLAVE | RUNNING; static constexpr int GROUP_NONE = -1; static constexpr int RLAG_NONE = -1; static constexpr int SRV_ID_NONE = -1; static std::string status_to_string(bitfield status); std::string status_to_string() const; void status_from_string(const std::string& source); std::string to_string_short() const; std::string name {"<unknown>"}; /**< Server name */ bitfield status {UNKNOWN}; /**< Status bitfield */ int64_t server_id {SRV_ID_NONE}; int64_t master_group {GROUP_NONE}; int64_t rlag {RLAG_NONE}; int64_t pool_conns {0}; int64_t connections {0}; std::string gtid; struct SlaveConnection { std::string name; std::string gtid; int64_t master_id {SRV_ID_NONE}; enum class IO_State { NO, CONNECTING, YES }; IO_State io_running {IO_State::NO}; bool sql_running {false}; }; std::vector<SlaveConnection> slave_connections; }; /** * Contains information about multiple servers as seen by MaxScale. */ class ServersInfo { public: ServersInfo(TestLogger* log); ServersInfo(const ServersInfo& rhs) = default; ServersInfo& operator=(const ServersInfo& rhs); ServersInfo(ServersInfo&& rhs) noexcept; ServersInfo& operator=(ServersInfo&& rhs) noexcept; void add(const ServerInfo& info); void add(ServerInfo&& info); const ServerInfo& get(size_t i) const; ServerInfo get(const std::string& cnf_name) const; size_t size() const; /** * Return the server info of the master. If no masters are found, returns a default server info object. * If multiple masters are found, returns the first. * * @return Server info of master. */ ServerInfo get_master() const; /** * Check that server status is as expected. Increments global error counter if differences found. * * @param expected_status Expected server statuses. Each status should be a bitfield of values defined * in the ServerInfo-class. */ void check_servers_status(const std::vector<ServerInfo::bitfield>& expected_status); void check_master_groups(const std::vector<int>& expected_groups); void check_pool_connections(const std::vector<int>& expected_conns); void check_connections(const std::vector<int>& expected_conns); void print(); /** * Get starting server states for a master-slave cluster: master + 3 slaves. */ static const std::vector<ServerInfo::bitfield>& default_repl_states(); private: std::vector<ServerInfo> m_servers; TestLogger* m_log {nullptr}; void check_servers_property(size_t n_expected, const std::function<void(size_t)>& tester); }; class MaxScale { public: using SMariaDB = std::unique_ptr<mxt::MariaDB>; enum service { RWSPLIT, READCONN_MASTER, READCONN_SLAVE }; MaxScale(mxt::SharedData* shared); ~MaxScale(); bool setup(const mxt::NetworkConfig& nwconfig, const std::string& vm_name); void set_use_ipv6(bool use_ipv6); void set_ssl(bool ssl); const char* ip4() const; const char* ip() const; const char* ip_private() const; const char* hostname() const; const char* access_user() const; const char* access_homedir() const; const char* access_sudo() const; const char* sshkey() const; static const std::string& prefix(); const std::string& node_name() const; bool ssl() const; int rwsplit_port {-1}; /**< RWSplit port */ int readconn_master_port {-1}; /**< ReadConnection in master mode port */ int readconn_slave_port {-1}; /**< ReadConnection in slave mode port */ /** * @brief Get port number of a MaxScale service * * @param type Type of service * @return Port number of the service */ int port(enum service type = RWSPLIT) const; MYSQL* conn_rwsplit {nullptr}; /**< Connection to RWSplit */ MYSQL* conn_master {nullptr}; /**< Connection to ReadConnection in master mode */ MYSQL* conn_slave {nullptr}; /**< Connection to ReadConnection in slave mode */ /**< conn_rwsplit, conn_master, conn_slave */ MYSQL* routers[3] {nullptr, nullptr, nullptr}; int ports[3] {-1, -1, -1}; /**< rwsplit_port, readconn_master_port, readconn_slave_port */ const std::string& cnf_path() const; const std::string& log_dir() const; const std::string& user_name() const; const std::string& password() const; /** * @brief ConnectMaxscale Opens connections to RWSplit, ReadConn master and ReadConn slave Maxscale * services * Opens connections to RWSplit, ReadConn master and ReadConn slave Maxscale services * Connections stored in maxscales->conn_rwsplit, maxscales->conn_master[0] and * maxscales->conn_slave[0] MYSQL structs * @return 0 in case of success */ int connect_maxscale(const std::string& db = "test"); int connect(const std::string& db = "test"); /** * @brief CloseMaxscaleConn Closes connection that were opened by ConnectMaxscale() * @return 0 */ int close_maxscale_connections(); int disconnect(); /** * @brief ConnectRWSplit Opens connections to RWSplit and store MYSQL struct in * maxscales->conn_rwsplit * @return 0 in case of success */ int connect_rwsplit(const std::string& db = "test"); /** * @brief ConnectReadMaster Opens connections to ReadConn master and store MYSQL struct in * maxscales->conn_master[0] * @return 0 in case of success */ int connect_readconn_master(const std::string& db = "test"); /** * @brief ConnectReadSlave Opens connections to ReadConn slave and store MYSQL struct in * maxscales->conn_slave[0] * @return 0 in case of success */ int connect_readconn_slave(const std::string& db = "test"); /** * @brief OpenRWSplitConn Opens new connections to RWSplit and returns MYSQL struct * To close connection mysql_close() have to be called * @return MYSQL struct */ MYSQL* open_rwsplit_connection(const std::string& db = "test"); SMariaDB open_rwsplit_connection2(const std::string& db = "test"); /** * Same as above except no default database. * * @return Connection object */ SMariaDB open_rwsplit_connection2_nodb(); /** * Try to open an RWSplit-connection using the given database. Failure is not a test error. * * @param db Database to connect to * @return Connection object. Call 'is_open' to check success. */ SMariaDB try_open_rwsplit_connection(const std::string& db = ""); SMariaDB try_open_rwsplit_connection(const std::string& user, const std::string& pass, const std::string& db = ""); enum class SslMode {AUTO, ON, OFF}; SMariaDB try_open_rwsplit_connection(SslMode ssl, const std::string& user, const std::string& pass, const std::string& db = ""); SMariaDB try_open_connection(SslMode ssl, int port, const std::string& user, const std::string& pass, const std::string& db = ""); SMariaDB try_open_connection(int port, const std::string& user, const std::string& pass, const std::string& db = ""); /** * Get a readwritesplit Connection */ Connection rwsplit(const std::string& db = "test"); /** * Get a Connection to a specific port */ Connection get_connection(int port, const std::string& db = "test"); /** * @brief OpenReadMasterConn Opens new connections to ReadConn master and returns MYSQL struct * To close connection mysql_close() have to be called * @return MYSQL struct */ MYSQL* open_readconn_master_connection(); /** * Get a readconnroute master Connection */ Connection readconn_master(const std::string& db = "test"); /** * @brief OpenReadSlaveConn Opens new connections to ReadConn slave and returns MYSQL struct * To close connection mysql_close() have to be called * @return MYSQL struct */ MYSQL* open_readconn_slave_connection(); /** * Get a readconnroute slave Connection */ Connection readconn_slave(const std::string& db = "test"); /** * @brief CloseRWSplit Closes RWplit connections stored in maxscales->conn_rwsplit */ void close_rwsplit(); /** * @brief CloseReadMaster Closes ReadConn master connections stored in maxscales->conn_master[0] */ void close_readconn_master(); /** * @brief restart_maxscale Issues 'service maxscale restart' command */ int restart_maxscale(); int restart(); /** * Issues 'service maxscale start' command */ int start_maxscale(); void start(); /** * @brief stop_maxscale Issues 'service maxscale stop' command */ int stop_maxscale(); void stop(); bool start_and_check_started(); bool stop_and_check_stopped(); void delete_log(); /** * Execute a MaxCtrl command * * @param cmd Command to execute, without the `maxctrl` part * @param sudo Run the command as root * * @return The exit code and output of MaxCtrl */ mxt::CmdResult maxctrl(const std::string& cmd, bool sudo = true); /** * @brief get_maxscale_memsize Gets size of the memory consumed by Maxscale process * @param m Number of Maxscale node * @return memory size in kilobytes */ long unsigned get_maxscale_memsize(int m = 0); void copy_log(int mxs_ind, int timestamp, const std::string& test_name); /** * @brief Get the set of labels that are assigned to server @c name * * @param name The name of the server * @return A set of string labels assigned to this server */ StringSet get_server_status(const std::string& name); mxt::ServersInfo get_servers(); int get_master_server_id(); /** * Wait until all running monitors have ticked. * * @param intervals The number of monitor intervals to wait */ void wait_for_monitor(int intervals = 1); /** * First sleep a given number of seconds, then wait for monitor. This is required in some cases * where the test needs to wait for some external effect along with the monitor. * * @param sleep_s Sleep time in seconds * @param intervals Monitor intervals */ void sleep_and_wait_for_monitor(int sleep_s, int intervals); mxt::CmdResult ssh_output(const std::string& cmd, bool sudo = true); int ssh_node(const std::string& cmd, bool sudo); int ssh_node_f(bool sudo, const char* format, ...) mxb_attribute((format(printf, 3, 4))); bool copy_to_node(const char* src, const char* dest); bool copy_from_node(const char* src, const char* dest); /** * Copy rules file for firewall filter to MaxScale machine. * * @param rules_name Rule file source filename * @param rules_dir Rule file source directory */ void copy_fw_rules(const std::string& rules_name, const std::string& rules_dir); /** * Check if MaxScale process is running or stopped. Wrong status is a test failure. * * @param expected True if expected to be running */ void expect_running_status(bool expected); bool reinstall(const std::string& target, const std::string& mdbci_config_name); bool use_valgrind() const; bool prepare_for_test(); void write_env_vars(); mxt::VMNode& vm_node(); /** * Check that server status is as expected. Increments global error counter if differences found. * * @param expected_status Expected server statuses. Each status should be a bitfield of values defined * in the ServerInfo-class. */ void check_servers_status(const std::vector<mxt::ServerInfo::bitfield>& expected_status); void check_print_servers_status(const std::vector<mxt::ServerInfo::bitfield>& expected_status); void alter_monitor(const std::string& mon_name, const std::string& setting, const std::string& value); void alter_service(const std::string& svc_name, const std::string& setting, const std::string& value); void alter_server(const std::string& srv_name, const std::string& setting, const std::string& value); private: bool m_use_ipv6 {false}; /**< Default to ipv6-addresses */ bool m_ssl {false}; /**< Use ssl when connecting to MaxScale */ int m_valgrind_log_num {0}; /**< Counter for Maxscale restarts to avoid Valgrind log overwriting */ bool m_use_valgrind {false}; /**< Run MaxScale under Valgrind? */ bool m_use_callgrind {false}; /**< Run MaxScale under Valgrind with --callgrind option */ std::string m_rest_user {"admin"}; std::string m_rest_pw {"mariadb"}; std::string m_rest_ip {"127.0.0.1"}; std::string m_rest_port {"8989"}; std::string m_user_name; /**< User name to access backend nodes */ std::string m_password; /**< Password to access backend nodes */ std::string m_cnf_path; /**< Maxscale configuration file path */ std::string m_log_dir; /**< MaxScale log files directory path */ std::string m_binlog_dir; /**< Directory of binlog files (for binlog router) */ mxt::SharedData& m_shared; std::unique_ptr<mxt::VMNode> m_vmnode; mxt::TestLogger& log() const; bool verbose() const; mxt::CmdResult curl_rest_api(const std::string& path); }; }
32.789357
107
0.653503
[ "object", "vector" ]
d541af336873d9f0a0ed851abd8dc331df78f582
2,188
cc
C++
lite/operators/where_op.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
6
2020-07-01T02:52:16.000Z
2021-06-22T12:15:59.000Z
lite/operators/where_op.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
null
null
null
lite/operators/where_op.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
1
2021-12-30T01:41:11.000Z
2021-12-30T01:41:11.000Z
// Copyright (c) 2019 PaddlePaddle Authors. 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 "lite/operators/where_op.h" #include "lite/core/op_registry.h" namespace paddle { namespace lite { namespace operators { bool WhereOp::CheckShape() const { CHECK_OR_FALSE(param_.x); CHECK_OR_FALSE(param_.y); CHECK_OR_FALSE(param_.condition); CHECK_OR_FALSE(param_.out); return true; } bool WhereOp::InferShapeImpl() const { auto x_dims = param_.x->dims(); auto y_dims = param_.y->dims(); auto cond_dims = param_.condition->dims(); CHECK_EQ(x_dims, y_dims) << "The dims of Inputs(X) and Inputs(Y) should be same. " "But received X's shape is " << x_dims << ", Y's shape is [%s]" << y_dims; CHECK_EQ(x_dims, cond_dims) << "The dims of Inputs(Condition) and Inputs(X) should be same. " << "But received Condition's shape is" << cond_dims << ", X's shape is " << x_dims; param_.out->Resize(x_dims); return true; } bool WhereOp::AttachImpl(const cpp::OpDesc &opdesc, lite::Scope *scope) { AttachParam(&param_); auto x = opdesc.Input("X").front(); auto y = opdesc.Input("Y").front(); auto condition = opdesc.Input("Condition").front(); auto out = opdesc.Output("Out").front(); param_.x = scope->FindVar(x)->GetMutable<lite::Tensor>(); param_.y = scope->FindVar(y)->GetMutable<lite::Tensor>(); param_.condition = scope->FindVar(condition)->GetMutable<lite::Tensor>(); param_.out = scope->FindVar(out)->GetMutable<lite::Tensor>(); return true; } } // namespace operators } // namespace lite } // namespace paddle REGISTER_LITE_OP(where, paddle::lite::operators::WhereOp);
34.730159
78
0.693784
[ "shape" ]
d542992984481b6b7061b7ae8333bf26d9a7cfe9
2,089
cpp
C++
LRUcache.cpp
pjzzz/DSandAlgo
823d5a1c17a871d75541387d5db08870dfd6b50e
[ "MIT" ]
4
2019-10-09T18:03:11.000Z
2020-12-09T05:38:02.000Z
LRUcache.cpp
pjzzz/DSandAlgo
823d5a1c17a871d75541387d5db08870dfd6b50e
[ "MIT" ]
9
2019-10-23T20:05:20.000Z
2020-11-04T21:43:02.000Z
LRUcache.cpp
pjzzz/DSandAlgo
823d5a1c17a871d75541387d5db08870dfd6b50e
[ "MIT" ]
12
2019-10-23T19:28:52.000Z
2020-11-02T09:43:17.000Z
#include<bits/stdc++.h> #define int long long #define pb emplace_back #define mp make_pair #define tci(v,i) for(auto i=v.begin();i!=v.end();i++) #define all(v) v.begin(),v.end() #define rep(i,start,lim) for(long long (i)=(start);i<(lim);i++) #define revrep(i,n) for(long long i=n-1;i>=0;i--) #define boost ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define osit ostream_iterator<int> output (cout," ") #define pv(x) copy(all(x),output) #define pa(a) rep(i,0,sizeof(a)/sizeof(a[0]))cout<<a[i]<<" " #define endl '\n' #define f first #define s second #define PI 3.141592653589793 #define set0(x) memset(x,0,sizeof(x)) #define set1(x) memset(x,1,sizeof(x)) #define getarr(arr,n) int arr[n];rep(i,0,n)cin>>a[i] #define getvec(vec,n) vi vec;int x;rep(i,0,n){cin>>x;vec.pb(x);} #define sort_uniq(c) (sort(c.begin(), c.end()), c.resize(distance(c.begin(), unique(c.begin(), c.end())))) #define uniq(a) a.resize(distance(a.begin(), unique(a.begin(), a.end()))) #define dg(x) cout<<#x<<':'<<x<<endl; #define dg2(x,y) cout<<#x<<':'<<x<<' '<<#y<<':'<<y<<endl; #define dg3(x,y,z) cout<<#x<<':'<<x<<' '<<#y<<':'<<y<<' '<<#z<<':'<<z<<endl; #define dg4(x,y,z,zz) cout<<#x<<':'<<x<<' '<<#y<<':'<<y<<' '<<#z<<':'<<z<<' '<<#zz<<':'<<zz<<endl; using namespace std; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector<ii> vii; template<typename T> T gcd(T a,T b){if(a==0) return b; return gcd(b%a,a);} int isPowerof2(int x) { return (x && !(x & x-1)); } int32_t main(){ boost;osit; int n,k; cin>>n>>k; list<int> lst; unordered_map<int,list<int>::iterator> mp; rep(i,0,n){ int x; cin>>x; if(lst.size()<min(n,k)){ if(mp.find(x)!=mp.end()){ lst.erase(mp[x]); } }else if(lst.size()==min(n,k)){ if(mp.find(x)==mp.end()){ lst.pop_back(); }else{ lst.erase(mp[x]); } } lst.push_front(x); mp[x]=lst.begin(); } cout<<lst.size()<<endl; tci(lst,itr){ cout<<*itr<<" "; } return 0; }
33.693548
106
0.543322
[ "vector" ]
d5431d3a14f6284c60305d1bc213c8d4b6fd2123
19,455
cpp
C++
lib/Runtime/Language/AsmJsUtils.cpp
paolosevMSFT/ChakraCore
e381509ce04eaee0517a668d5002d3eedf582b8b
[ "MIT" ]
3
2018-08-08T03:36:56.000Z
2019-05-24T08:45:30.000Z
lib/Runtime/Language/AsmJsUtils.cpp
paolosevMSFT/ChakraCore
e381509ce04eaee0517a668d5002d3eedf582b8b
[ "MIT" ]
4
2020-03-13T14:45:49.000Z
2020-03-15T16:31:22.000Z
lib/Runtime/Language/AsmJsUtils.cpp
paolosevMSFT/ChakraCore
e381509ce04eaee0517a668d5002d3eedf582b8b
[ "MIT" ]
1
2020-03-15T16:02:18.000Z
2020-03-15T16:02:18.000Z
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. // Portions of this file are copyright 2014 Mozilla Foundation, available under the Apache 2.0 license. //------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------- // Copyright 2014 Mozilla 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 "RuntimeLanguagePch.h" #ifdef ASMJS_PLAT namespace Js { bool ParserWrapper::ParseVarOrConstStatement( AsmJSParser &parser, ParseNode **var ) { Assert( parser ); *var = nullptr; ParseNode *body = parser->AsParseNodeFnc()->pnodeBody; if( body ) { ParseNode* lhs = GetBinaryLeft( body ); ParseNode* rhs = GetBinaryRight( body ); if( rhs && rhs->nop == knopList ) { AssertMsg( lhs->nop == knopStr, "this should be use asm" ); *var = rhs; return true; } } return false; } bool ParserWrapper::IsDefinition( ParseNode *arg ) { //TODO, eliminate duplicates return true; } ParseNode* ParserWrapper::NextInList( ParseNode *node ) { Assert( node->nop == knopList ); return node->AsParseNodeBin()->pnode2; } ParseNode* ParserWrapper::NextVar( ParseNode *node ) { return node->AsParseNodeVar()->pnodeNext; } ParseNode* ParserWrapper::FunctionArgsList( ParseNode *node, ArgSlot &numformals ) { Assert( node->nop == knopFncDecl ); ParseNodeFnc * func = node->AsParseNodeFnc(); ParseNode* first = func->pnodeParams; // throws OOM on uint16 overflow for( ParseNode* pnode = first; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext, ArgSlotMath::Inc(numformals)); return first; } PropertyName ParserWrapper::VariableName( ParseNode *node ) { return node->name(); } PropertyName ParserWrapper::FunctionName( ParseNode *node ) { if( node->nop == knopFncDecl ) { ParseNodeFnc * function = node->AsParseNodeFnc(); if(function->pnodeName) { Assert(function->pnodeName->nop == knopVarDecl); return function->pnodeName->pid; } } return nullptr; } ParseNode * ParserWrapper::GetVarDeclList( ParseNode * pnode ) { ParseNode* varNode = pnode; while (varNode->nop == knopList) { ParseNode * var = GetBinaryLeft(varNode); if (var->nop == knopVarDecl) { return var; } else if (var->nop == knopList) { var = GetBinaryLeft(var); if (var->nop == knopVarDecl) { return var; } } varNode = GetBinaryRight(varNode); } return nullptr; } void ParserWrapper::ReachEndVarDeclList( ParseNode** outNode ) { ParseNode* pnode = *outNode; // moving down to the last var declaration while( pnode->nop == knopList ) { ParseNode* var = GetBinaryLeft( pnode ); if (var->nop == knopVarDecl) { pnode = GetBinaryRight( pnode ); continue; } else if (var->nop == knopList) { var = GetBinaryLeft( var ); if (var->nop == knopVarDecl) { pnode = GetBinaryRight( pnode ); continue; } } break; } *outNode = pnode; } AsmJsCompilationException::AsmJsCompilationException( const char16* _msg, ... ) { va_list arglist; va_start( arglist, _msg ); vswprintf_s( msg_, _msg, arglist ); } #if ENABLE_DEBUG_CONFIG_OPTIONS int64 ConvertStringToInt64(Var string, ScriptContext* scriptContext) { JavascriptString* str = JavascriptString::FromVar(string); charcount_t length = str->GetLength(); const char16* buf = str->GetString(); int radix = 10; if (length >= 2 && buf[0] == '0' && buf[1] == 'x') { radix = 16; } return (int64)_wcstoui64(buf, nullptr, radix); } Var CreateI64ReturnObject(int64 val, ScriptContext* scriptContext) { Js::Var i64Object = JavascriptOperators::NewJavascriptObjectNoArg(scriptContext); Var low = JavascriptNumber::ToVar((uint)val, scriptContext); Var high = JavascriptNumber::ToVar(val >> 32, scriptContext); JavascriptOperators::OP_SetProperty(i64Object, PropertyIds::low, low, scriptContext); JavascriptOperators::OP_SetProperty(i64Object, PropertyIds::high, high, scriptContext); return i64Object; } #endif void * UnboxAsmJsArguments(ScriptFunction* func, Var * origArgs, char * argDst, CallInfo callInfo) { void * address = reinterpret_cast<void*>(func->GetEntryPointInfo()->jsMethod); Assert(address); AsmJsFunctionInfo* info = func->GetFunctionBody()->GetAsmJsFunctionInfo(); ScriptContext* scriptContext = func->GetScriptContext(); #if ENABLE_DEBUG_CONFIG_OPTIONS bool allowTestInputs = CONFIG_FLAG(WasmI64); #endif ArgumentReader reader(&callInfo, origArgs); uint actualArgCount = reader.Info.Count - 1; // -1 for ScriptFunction argDst = argDst + MachPtr; // add one first so as to skip the ScriptFunction argument for (ArgSlot i = 0; i < info->GetArgCount(); i++) { if (info->GetArgType(i).isInt()) { int32 intVal; if (i < actualArgCount) { #if ENABLE_DEBUG_CONFIG_OPTIONS if (allowTestInputs && JavascriptString::Is(*origArgs)) { intVal = (int32)ConvertStringToInt64(*origArgs, scriptContext); } else #endif intVal = JavascriptMath::ToInt32(*origArgs, scriptContext); } else { intVal = 0; } #if TARGET_64 *(int64*)(argDst) = 0; #endif *(int32*)argDst = intVal; argDst = argDst + MachPtr; } else if (info->GetArgType(i).isInt64()) { #if ENABLE_DEBUG_CONFIG_OPTIONS if (!allowTestInputs) #endif { JavascriptError::ThrowTypeError(scriptContext, WASMERR_InvalidTypeConversion); } #if ENABLE_DEBUG_CONFIG_OPTIONS int64 val; if (i < actualArgCount) { if (JavascriptString::Is(*origArgs)) { val = ConvertStringToInt64(*origArgs, scriptContext); } else if (JavascriptObject::Is(*origArgs)) { RecyclableObject* object = RecyclableObject::FromVar(*origArgs); PropertyRecord const * lowPropRecord = nullptr; PropertyRecord const * highPropRecord = nullptr; scriptContext->GetOrAddPropertyRecord(_u("low"), (int)wcslen(_u("low")), &lowPropRecord); scriptContext->GetOrAddPropertyRecord(_u("high"), (int)wcslen(_u("high")), &highPropRecord); Var low = JavascriptOperators::OP_GetProperty(object, lowPropRecord->GetPropertyId(), scriptContext); Var high = JavascriptOperators::OP_GetProperty(object, highPropRecord->GetPropertyId(), scriptContext); uint64 lowVal = JavascriptMath::ToInt32(low, scriptContext); uint64 highVal = JavascriptMath::ToInt32(high, scriptContext); val = (highVal << 32) | (lowVal & 0xFFFFFFFF); } else { int32 intVal = JavascriptMath::ToInt32(*origArgs, scriptContext); val = (int64)intVal; } } else { val = 0; } *(int64*)(argDst) = val; argDst += sizeof(int64); #endif } else if (info->GetArgType(i).isFloat()) { float floatVal; if (i < actualArgCount) { #if ENABLE_DEBUG_CONFIG_OPTIONS if (allowTestInputs && JavascriptString::Is(*origArgs)) { int32 val = (int32)ConvertStringToInt64(*origArgs, scriptContext); floatVal = *(float*)&val; } else #endif floatVal = (float)(JavascriptConversion::ToNumber(*origArgs, scriptContext)); } else { floatVal = (float)(JavascriptNumber::NaN); } #if TARGET_64 *(int64*)(argDst) = 0; #endif *(float*)argDst = floatVal; argDst = argDst + MachPtr; } else if (info->GetArgType(i).isDouble()) { double doubleVal; if (i < actualArgCount) { #if ENABLE_DEBUG_CONFIG_OPTIONS if (allowTestInputs && JavascriptString::Is(*origArgs)) { int64 val = ConvertStringToInt64(*origArgs, scriptContext); doubleVal = *(double*)&val; } else #endif doubleVal = JavascriptConversion::ToNumber(*origArgs, scriptContext); } else { doubleVal = JavascriptNumber::NaN; } *(double*)argDst = doubleVal; argDst = argDst + sizeof(double); } else if (info->GetArgType(i).isSIMD()) { // Todo:: support test input for wasm.simd JavascriptError::ThrowTypeError(scriptContext, WASMERR_InvalidTypeConversion); } else { Assert(UNREACHED); JavascriptError::ThrowTypeError(scriptContext, WASMERR_InvalidTypeConversion); } ++origArgs; } AsmJsModuleInfo::EnsureHeapAttached(func); // for convenience, lets take the opportunity to return the asm.js entrypoint address return address; } #if _M_X64 // returns an array containing the size of each argument uint *GetArgsSizesArray(ScriptFunction* func) { AsmJsFunctionInfo* info = func->GetFunctionBody()->GetAsmJsFunctionInfo(); return info->GetArgsSizesArray(); } int GetStackSizeForAsmJsUnboxing(ScriptFunction* func) { AsmJsFunctionInfo* info = func->GetFunctionBody()->GetAsmJsFunctionInfo(); int argSize = info->GetArgByteSize() + MachPtr; argSize = ::Math::Align<int32>(argSize, 16); if (argSize < 32) { argSize = 32; // convention is to always allocate spill space for rcx,rdx,r8,r9 } PROBE_STACK_CALL(func->GetScriptContext(), func, argSize + Js::Constants::MinStackDefault); return argSize; } Var BoxAsmJsReturnValue(ScriptFunction* func, int64 intRetVal, double doubleRetVal, float floatRetVal, __m128 simdRetVal) { // ExternalEntryPoint doesn't know the return value, so it will send garbage for everything except actual return type Var returnValue = nullptr; // make call and convert primitive type back to Var AsmJsFunctionInfo* info = func->GetFunctionBody()->GetAsmJsFunctionInfo(); ScriptContext* scriptContext = func->GetScriptContext(); switch (info->GetReturnType().which()) { case AsmJsRetType::Void: returnValue = JavascriptOperators::OP_LdUndef(scriptContext); break; case AsmJsRetType::Signed: { returnValue = JavascriptNumber::ToVar((int)intRetVal, scriptContext); break; } case AsmJsRetType::Int64: { #if ENABLE_DEBUG_CONFIG_OPTIONS if (CONFIG_FLAG(WasmI64)) { returnValue = CreateI64ReturnObject(intRetVal, scriptContext); break; } #endif JavascriptError::ThrowTypeError(scriptContext, WASMERR_InvalidTypeConversion); } case AsmJsRetType::Double: { returnValue = JavascriptNumber::NewWithCheck(doubleRetVal, scriptContext); break; } case AsmJsRetType::Float: { returnValue = JavascriptNumber::NewWithCheck(floatRetVal, scriptContext); break; } #ifdef ENABLE_WASM_SIMD case AsmJsRetType::Bool32x4: case AsmJsRetType::Bool16x8: case AsmJsRetType::Bool8x16: case AsmJsRetType::Float64x2: case AsmJsRetType::Float32x4: case AsmJsRetType::Int64x2: case AsmJsRetType::Int32x4: case AsmJsRetType::Int16x8: case AsmJsRetType::Int8x16: case AsmJsRetType::Uint32x4: case AsmJsRetType::Uint16x8: case AsmJsRetType::Uint8x16: // Todo:: support test return object (like int64) for wasm.simd JavascriptError::ThrowTypeError(scriptContext, WASMERR_InvalidTypeConversion); #endif default: Assume(UNREACHED); JavascriptError::ThrowTypeError(scriptContext, WASMERR_InvalidTypeConversion); } return returnValue; } #elif _M_IX86 Var AsmJsExternalEntryPoint(RecyclableObject* entryObject, CallInfo callInfo, ...) { ARGUMENTS(args, callInfo); ScriptFunction* func = (ScriptFunction*)entryObject; FunctionBody* body = func->GetFunctionBody(); AsmJsFunctionInfo* info = body->GetAsmJsFunctionInfo(); int argSize = info->GetArgByteSize(); void* dst; Var returnValue = 0; argSize = ::Math::Align<int32>(argSize, 8); // Allocate stack space for args PROBE_STACK_CALL(func->GetScriptContext(), func, argSize + Js::Constants::MinStackDefault); dst = _alloca(argSize); const void * asmJSEntryPoint = UnboxAsmJsArguments(func, args.Values + 1, ((char*)dst) - MachPtr, callInfo); // make call and convert primitive type back to Var switch (info->GetReturnType().which()) { case AsmJsRetType::Void: __asm { mov ecx, asmJSEntryPoint #ifdef _CONTROL_FLOW_GUARD call[__guard_check_icall_fptr] #endif push func call ecx } returnValue = JavascriptOperators::OP_LdUndef(func->GetScriptContext()); break; case AsmJsRetType::Signed:{ int32 ival = 0; __asm { mov ecx, asmJSEntryPoint #ifdef _CONTROL_FLOW_GUARD call[__guard_check_icall_fptr] #endif push func call ecx mov ival, eax } returnValue = JavascriptNumber::ToVar(ival, func->GetScriptContext()); break; } case AsmJsRetType::Int64: { int32 iLow = 0, iHigh = 0; __asm { mov ecx, asmJSEntryPoint #ifdef _CONTROL_FLOW_GUARD call[__guard_check_icall_fptr] #endif push func call ecx mov iLow, eax; mov iHigh, edx; } #if ENABLE_DEBUG_CONFIG_OPTIONS if (CONFIG_FLAG(WasmI64)) { uint64 lHigh = ((uint64)iHigh) << 32; uint64 lLow = (uint64)(uint32)iLow; returnValue = CreateI64ReturnObject((int64)(lHigh | lLow), func->GetScriptContext()); break; } #endif JavascriptError::ThrowTypeError(func->GetScriptContext(), WASMERR_InvalidTypeConversion); } case AsmJsRetType::Double:{ double dval = 0; __asm { mov ecx, asmJSEntryPoint #ifdef _CONTROL_FLOW_GUARD call[__guard_check_icall_fptr] #endif push func call ecx movsd dval, xmm0 } returnValue = JavascriptNumber::NewWithCheck(dval, func->GetScriptContext()); break; } case AsmJsRetType::Float:{ float fval = 0; __asm { mov ecx, asmJSEntryPoint #ifdef _CONTROL_FLOW_GUARD call[__guard_check_icall_fptr] #endif push func call ecx movss fval, xmm0 } returnValue = JavascriptNumber::NewWithCheck((double)fval, func->GetScriptContext()); break; } #ifdef ENABLE_WASM_SIMD case AsmJsRetType::Bool32x4: case AsmJsRetType::Bool16x8: case AsmJsRetType::Bool8x16: case AsmJsRetType::Float32x4: case AsmJsRetType::Float64x2: case AsmJsRetType::Int64x2: case AsmJsRetType::Int32x4: case AsmJsRetType::Int16x8: case AsmJsRetType::Int8x16: case AsmJsRetType::Uint32x4: case AsmJsRetType::Uint16x8: case AsmJsRetType::Uint8x16: AsmJsSIMDValue simdVal; simdVal.Zero(); __asm { mov ecx, asmJSEntryPoint #ifdef _CONTROL_FLOW_GUARD call[__guard_check_icall_fptr] #endif push func call ecx movups simdVal, xmm0 } // Todo:: support test return object (like int64) for wasm.simd JavascriptError::ThrowTypeError(func->GetScriptContext(), WASMERR_InvalidTypeConversion); break; #endif default: Assume(UNREACHED); JavascriptError::ThrowTypeError(func->GetScriptContext(), WASMERR_InvalidTypeConversion); } return returnValue; } #endif } #endif
34.741071
127
0.540478
[ "object" ]
d54481d2469a5c3b3fab845d32e5def5b4827ed5
3,652
cpp
C++
libraries/render-utils/src/ToneMappingEffect.cpp
alphaversiond/hifi
735944c912a29e948a557dbff13e0a1cb71d954e
[ "Apache-2.0" ]
2
2018-05-07T16:12:38.000Z
2019-04-28T17:32:01.000Z
libraries/render-utils/src/ToneMappingEffect.cpp
alphaversiond/hifi
735944c912a29e948a557dbff13e0a1cb71d954e
[ "Apache-2.0" ]
null
null
null
libraries/render-utils/src/ToneMappingEffect.cpp
alphaversiond/hifi
735944c912a29e948a557dbff13e0a1cb71d954e
[ "Apache-2.0" ]
null
null
null
// // ToneMappingEffect.cpp // libraries/render-utils/src // // Created by Sam Gateau on 12/7/2015. // Copyright 2015 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "ToneMappingEffect.h" #include <gpu/Context.h> #include <gpu/StandardShaderLib.h> #include <RenderArgs.h> #include "FramebufferCache.h" #include "toneMapping_frag.h" const int ToneMappingEffect_ParamsSlot = 0; const int ToneMappingEffect_LightingMapSlot = 0; ToneMappingEffect::ToneMappingEffect() { Parameters parameters; _parametersBuffer = gpu::BufferView(std::make_shared<gpu::Buffer>(sizeof(Parameters), (const gpu::Byte*) &parameters)); } void ToneMappingEffect::init() { auto blitPS = gpu::ShaderPointer(gpu::Shader::createPixel(std::string(toneMapping_frag))); auto blitVS = gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS(); auto blitProgram = gpu::ShaderPointer(gpu::Shader::createProgram(blitVS, blitPS)); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("toneMappingParamsBuffer"), ToneMappingEffect_ParamsSlot)); slotBindings.insert(gpu::Shader::Binding(std::string("colorMap"), ToneMappingEffect_LightingMapSlot)); gpu::Shader::makeProgram(*blitProgram, slotBindings); auto blitState = std::make_shared<gpu::State>(); blitState->setColorWriteMask(true, true, true, true); _blitLightBuffer = gpu::PipelinePointer(gpu::Pipeline::create(blitProgram, blitState)); } void ToneMappingEffect::setExposure(float exposure) { auto& params = _parametersBuffer.get<Parameters>(); if (params._exposure != exposure) { _parametersBuffer.edit<Parameters>()._exposure = exposure; _parametersBuffer.edit<Parameters>()._twoPowExposure = pow(2.0, exposure); } } void ToneMappingEffect::setToneCurve(ToneCurve curve) { auto& params = _parametersBuffer.get<Parameters>(); if (params._toneCurve != curve) { _parametersBuffer.edit<Parameters>()._toneCurve = curve; } } void ToneMappingEffect::render(RenderArgs* args, const gpu::TexturePointer& lightingBuffer, const gpu::FramebufferPointer& destinationFramebuffer) { if (!_blitLightBuffer) { init(); } auto framebufferSize = glm::ivec2(lightingBuffer->getDimensions()); gpu::doInBatch(args->_context, [&](gpu::Batch& batch) { batch.enableStereo(false); batch.setFramebuffer(destinationFramebuffer); // FIXME: Generate the Luminosity map //batch.generateTextureMips(lightingBuffer); batch.setViewportTransform(args->_viewport); batch.setProjectionTransform(glm::mat4()); batch.resetViewTransform(); batch.setModelTransform(gpu::Framebuffer::evalSubregionTexcoordTransform(framebufferSize, args->_viewport)); batch.setPipeline(_blitLightBuffer); batch.setUniformBuffer(ToneMappingEffect_ParamsSlot, _parametersBuffer); batch.setResourceTexture(ToneMappingEffect_LightingMapSlot, lightingBuffer); batch.draw(gpu::TRIANGLE_STRIP, 4); }); } void ToneMappingDeferred::configure(const Config& config) { _toneMappingEffect.setExposure(config.exposure); _toneMappingEffect.setToneCurve((ToneMappingEffect::ToneCurve)config.curve); } void ToneMappingDeferred::run(const render::RenderContextPointer& renderContext, const Inputs& inputs) { auto lightingBuffer = inputs.get0()->getRenderBuffer(0); auto destFbo = inputs.get1(); _toneMappingEffect.render(renderContext->args, lightingBuffer, destFbo); }
37.649485
148
0.737952
[ "render" ]
d54571a2e1f53fc5de7d40619ad1777bc014e6ee
13,947
cpp
C++
planning/scenario_planning/lane_driving/behavior_planning/lane_change_planner/src/state/blocked_by_obstacle.cpp
KevinXie86/AutowareArchitectureProposal.iv
28c8c367652bcc5c2548abdab732e0fea7302653
[ "Apache-2.0" ]
88
2021-01-16T20:05:40.000Z
2022-03-21T05:40:35.000Z
planning/scenario_planning/lane_driving/behavior_planning/lane_change_planner/src/state/blocked_by_obstacle.cpp
KevinXie86/AutowareArchitectureProposal.iv
28c8c367652bcc5c2548abdab732e0fea7302653
[ "Apache-2.0" ]
271
2021-01-13T16:54:09.000Z
2022-02-25T16:26:07.000Z
planning/scenario_planning/lane_driving/behavior_planning/lane_change_planner/src/state/blocked_by_obstacle.cpp
KevinXie86/AutowareArchitectureProposal.iv
28c8c367652bcc5c2548abdab732e0fea7302653
[ "Apache-2.0" ]
68
2021-01-14T09:16:40.000Z
2022-03-29T02:15:36.000Z
// Copyright 2019 Autoware Foundation. All rights reserved. // Copyright 2020 Tier IV, 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 "lane_change_planner/state/blocked_by_obstacle.hpp" #include <vector> #include <memory> #include <limits> #include <algorithm> #include "lanelet2_extension/utility/message_conversion.hpp" #include "lanelet2_extension/utility/utilities.hpp" #include "lane_change_planner/data_manager.hpp" #include "lane_change_planner/route_handler.hpp" #include "lane_change_planner/state/common_functions.hpp" #include "lane_change_planner/utilities.hpp" namespace lane_change_planner { BlockedByObstacleState::BlockedByObstacleState( const Status & status, const std::shared_ptr<DataManager> & data_manager_ptr, const std::shared_ptr<RouteHandler> & route_handler_ptr, const rclcpp::Logger & logger, const rclcpp::Clock::SharedPtr & clock) : StateBase(status, data_manager_ptr, route_handler_ptr, logger, clock) { } State BlockedByObstacleState::getCurrentState() const {return State::BLOCKED_BY_OBSTACLE;} void BlockedByObstacleState::entry() { ros_parameters_ = data_manager_ptr_->getLaneChangerParameters(); lane_change_approved_ = false; force_lane_change_ = false; found_valid_path_ = false; found_safe_path_ = false; current_lanes_ = route_handler_ptr_->getLaneletsFromIds(status_.lane_follow_lane_ids); } autoware_planning_msgs::msg::PathWithLaneId BlockedByObstacleState::getPath() const { return status_.lane_follow_path; } void BlockedByObstacleState::update() { // update input data current_twist_ = data_manager_ptr_->getCurrentSelfVelocity(); current_pose_ = data_manager_ptr_->getCurrentSelfPose(); dynamic_objects_ = data_manager_ptr_->getDynamicObjects(); lane_change_approved_ = data_manager_ptr_->getLaneChangeApproval(); force_lane_change_ = data_manager_ptr_->getForceLaneChangeSignal(); lanelet::ConstLanelet current_lane; lanelet::ConstLanelets right_lanes; lanelet::ConstLanelets left_lanes; const double backward_path_length = ros_parameters_.backward_path_length; const double forward_path_length = ros_parameters_.forward_path_length; // update lanes { if (!route_handler_ptr_->getClosestLaneletWithinRoute(current_pose_.pose, &current_lane)) { RCLCPP_ERROR(logger_, "failed to find closest lanelet within route!!!"); return; } lanelet::ConstLanelet right_lane; if (route_handler_ptr_->getRightLaneletWithinRoute(current_lane, &right_lane)) { right_lanes = route_handler_ptr_->getLaneletSequence( right_lane, current_pose_.pose, backward_path_length, forward_path_length); } lanelet::ConstLanelet left_lane; if (route_handler_ptr_->getLeftLaneletWithinRoute(current_lane, &left_lane)) { left_lanes = route_handler_ptr_->getLaneletSequence( left_lane, current_pose_.pose, backward_path_length, forward_path_length); } } // update lane_follow_path { status_.lane_follow_path = route_handler_ptr_->getReferencePath( current_lanes_, current_pose_.pose, backward_path_length, forward_path_length, ros_parameters_); status_.lane_follow_path = setStopPointFromObstacle(status_.lane_follow_path); status_.lane_follow_lane_ids = util::getIds(current_lanes_); } // update drivable area { const double width = ros_parameters_.drivable_area_width; const double height = ros_parameters_.drivable_area_height; const double resolution = ros_parameters_.drivable_area_resolution; status_.lane_follow_path.drivable_area = util::generateDrivableArea( current_lanes_, current_pose_, width, height, resolution, ros_parameters_.vehicle_length, *route_handler_ptr_); } // update lane_change_lane status_.lane_change_path = LaneChangePath(); // clear path status_.lane_change_lane_ids.clear(); found_safe_path_ = false; constexpr double check_distance = 100.0; // can we avoid right? if (!right_lanes.empty() && hasEnoughDistanceToComeBack(right_lanes)) { // find candidate paths const auto lane_change_paths = route_handler_ptr_->getLaneChangePaths( current_lanes_, right_lanes, current_pose_.pose, current_twist_->twist, ros_parameters_); debug_data_.lane_change_candidate_paths = lane_change_paths; status_.lane_change_lane_ids = util::getIds(right_lanes); // get lanes used for detection lanelet::ConstLanelets check_lanes; if (!lane_change_paths.empty()) { const auto & longest_path = lane_change_paths.front(); const double check_distance_with_path = check_distance + longest_path.preparation_length + longest_path.lane_change_length; check_lanes = route_handler_ptr_->getCheckTargetLanesFromPath( longest_path.path, right_lanes, check_distance_with_path); } // select valid path const auto valid_paths = state_machine::common_functions::selectValidPaths( lane_change_paths, current_lanes_, check_lanes, route_handler_ptr_->getOverallGraph(), current_pose_.pose, route_handler_ptr_->isInGoalRouteSection(current_lanes_.back()), route_handler_ptr_->getGoalPose()); debug_data_.lane_change_candidate_paths = valid_paths; found_valid_path_ = !valid_paths.empty(); // select safe path LaneChangePath selected_path; if (state_machine::common_functions::selectSafePath( valid_paths, current_lanes_, check_lanes, dynamic_objects_, current_pose_.pose, current_twist_->twist, ros_parameters_, &selected_path, logger_, clock_)) { found_safe_path_ = true; } debug_data_.selected_path = selected_path.path; status_.lane_change_path = selected_path; } // can we avoid left? if (!found_safe_path_ && !left_lanes.empty() && hasEnoughDistanceToComeBack(left_lanes)) { // find candidate paths const auto lane_change_paths = route_handler_ptr_->getLaneChangePaths( current_lanes_, left_lanes, current_pose_.pose, current_twist_->twist, ros_parameters_); debug_data_.lane_change_candidate_paths = lane_change_paths; status_.lane_change_lane_ids = util::getIds(left_lanes); // get lanes used for detection lanelet::ConstLanelets check_lanes; if (!lane_change_paths.empty()) { const auto & longest_path = lane_change_paths.front(); const double check_distance_with_path = check_distance + longest_path.preparation_length + longest_path.lane_change_length; check_lanes = route_handler_ptr_->getCheckTargetLanesFromPath( longest_path.path, left_lanes, check_distance_with_path); } // select valid path const auto valid_paths = state_machine::common_functions::selectValidPaths( lane_change_paths, current_lanes_, check_lanes, route_handler_ptr_->getOverallGraph(), current_pose_.pose, route_handler_ptr_->isInGoalRouteSection(current_lanes_.back()), route_handler_ptr_->getGoalPose()); debug_data_.lane_change_candidate_paths = valid_paths; found_valid_path_ = !valid_paths.empty(); // select safe path LaneChangePath selected_path; if (state_machine::common_functions::selectSafePath( valid_paths, current_lanes_, check_lanes, dynamic_objects_, current_pose_.pose, current_twist_->twist, ros_parameters_, &selected_path, logger_, clock_)) { found_safe_path_ = true; } debug_data_.selected_path = selected_path.path; status_.lane_change_path = selected_path; } // update lane_change_ready flags { status_.lane_change_ready = false; status_.lane_change_available = false; if (foundValidPath()) { status_.lane_change_available = true; if (foundSafeLaneChangePath()) { status_.lane_change_ready = true; } } } } State BlockedByObstacleState::getNextState() const { if (isOutOfCurrentLanes()) { return State::FOLLOWING_LANE; } if (!isLaneBlocked()) { return State::FOLLOWING_LANE; } if (isLaneChangeAvailable() && laneChangeForcedByOperator()) { return State::FORCING_LANE_CHANGE; } if (isLaneChangeApproved() && isLaneChangeReady()) { return State::EXECUTING_LANE_CHANGE; } return State::BLOCKED_BY_OBSTACLE; } autoware_planning_msgs::msg::PathWithLaneId BlockedByObstacleState::setStopPointFromObstacle( const autoware_planning_msgs::msg::PathWithLaneId & path) { const auto blocking_objects = getBlockingObstacles(); const auto path_linestring = util::convertToGeometryPointArray(path); util::FrenetCoordinate3d vehicle_frenet; if (!util::convertToFrenetCoordinate3d( path_linestring, current_pose_.pose.position, &vehicle_frenet)) { return path; } // find the closest static obstacle in front of ego vehicle autoware_perception_msgs::msg::DynamicObject closest_object; bool found_closest_object = false; double closest_distance = std::numeric_limits<double>::max(); for (const auto & object : blocking_objects) { util::FrenetCoordinate3d object_frenet; if (!util::convertToFrenetCoordinate3d( path_linestring, object.state.pose_covariance.pose.position, &object_frenet)) { continue; } if (object_frenet.length > vehicle_frenet.length && object_frenet.length < closest_distance) { closest_distance = object_frenet.length; closest_object = object; found_closest_object = true; } } if (!found_closest_object) { return path; } double stop_insert_length = closest_distance - ros_parameters_.minimum_lane_change_length - ros_parameters_.base_link2front; stop_insert_length = std::max(stop_insert_length, 0.0); autoware_planning_msgs::msg::PathWithLaneId modified_path = path; debug_data_.stop_factor_point = closest_object.state.pose_covariance.pose.position; debug_data_.stop_point = util::insertStopPoint(stop_insert_length, &modified_path); return modified_path; } bool BlockedByObstacleState::isOutOfCurrentLanes() const { lanelet::ConstLanelet closest_lane; if (!route_handler_ptr_->getClosestLaneletWithinRoute(current_pose_.pose, &closest_lane)) { RCLCPP_ERROR(logger_, "failed to find closest lanelet within route!!!"); return true; } for (const auto & llt : current_lanes_) { if (llt == closest_lane) { return false; } } return true; } bool BlockedByObstacleState::isLaneBlocked() const { const auto blocking_objects = getBlockingObstacles(); return !blocking_objects.empty(); } std::vector<autoware_perception_msgs::msg::DynamicObject> BlockedByObstacleState:: getBlockingObstacles() const { std::vector<autoware_perception_msgs::msg::DynamicObject> blocking_obstacles; const auto arc = lanelet::utils::getArcCoordinates(current_lanes_, current_pose_.pose); constexpr double max_check_distance = 100; double static_obj_velocity_thresh = ros_parameters_.static_obstacle_velocity_thresh; const double lane_changeable_distance_left = route_handler_ptr_->getLaneChangeableDistance(current_pose_.pose, LaneChangeDirection::LEFT); const double lane_changeable_distance_right = route_handler_ptr_->getLaneChangeableDistance(current_pose_.pose, LaneChangeDirection::RIGHT); const double lane_changeable_distance = std::max(lane_changeable_distance_left, lane_changeable_distance_right); const double check_distance = std::min(max_check_distance, lane_changeable_distance); const auto polygon = lanelet::utils::getPolygonFromArcLength( current_lanes_, arc.length, arc.length + check_distance); if (polygon.size() < 3) { RCLCPP_WARN_STREAM( logger_, "could not get polygon from lanelet with arc lengths: " << arc.length << " to " << arc.length + check_distance); return blocking_obstacles; } for (const auto & obj : dynamic_objects_->objects) { const auto velocity = util::l2Norm(obj.state.twist_covariance.twist.linear); if (velocity < static_obj_velocity_thresh) { const auto position = lanelet::utils::conversion::toLaneletPoint(obj.state.pose_covariance.pose.position); const auto distance = boost::geometry::distance( lanelet::utils::to2D(position).basicPoint(), lanelet::utils::to2D(polygon).basicPolygon()); if (distance < std::numeric_limits<double>::epsilon()) { blocking_obstacles.push_back(obj); } } } return blocking_obstacles; } bool BlockedByObstacleState::isLaneChangeApproved() const {return lane_change_approved_;} bool BlockedByObstacleState::laneChangeForcedByOperator() const {return force_lane_change_;} bool BlockedByObstacleState::isLaneChangeAvailable() const {return status_.lane_change_available;} bool BlockedByObstacleState::hasEnoughDistanceToComeBack( const lanelet::ConstLanelets & target_lanes) const { if (target_lanes.empty()) {return false;} const auto static_objects = getBlockingObstacles(); // make sure that there is at least minimum lane change length after obstacle. for (const auto & obj : static_objects) { const double remaining_distance = util::getDistanceToEndOfLane(obj.state.pose_covariance.pose, target_lanes); if (remaining_distance < ros_parameters_.minimum_lane_change_length) { return false; } } return true; } bool BlockedByObstacleState::foundValidPath() const {return found_valid_path_;} bool BlockedByObstacleState::foundSafeLaneChangePath() const {return found_safe_path_;} bool BlockedByObstacleState::isLaneChangeReady() const {return status_.lane_change_ready;} } // namespace lane_change_planner
39.398305
100
0.765111
[ "geometry", "object", "vector" ]
d54a19ed950dc94a628964dfa1937b0ca809946c
234
cpp
C++
src/backends/x11/window/object.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
src/backends/x11/window/object.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
src/backends/x11/window/object.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
#include <awl/backends/x11/window/base.hpp> #include <awl/backends/x11/window/object.hpp> awl::backends::x11::window::object::object() : awl::backends::x11::window::base{} {} awl::backends::x11::window::object::~object() = default;
33.428571
84
0.705128
[ "object" ]
d54b09055681ad645d03123fe00029310e0223e6
68,467
cpp
C++
be/src/agent/task_worker_pool.cpp
liyuance/incubator-doris
03fa1fefa9e90673916323a0f00840b4c91e76a9
[ "Apache-2.0" ]
null
null
null
be/src/agent/task_worker_pool.cpp
liyuance/incubator-doris
03fa1fefa9e90673916323a0f00840b4c91e76a9
[ "Apache-2.0" ]
null
null
null
be/src/agent/task_worker_pool.cpp
liyuance/incubator-doris
03fa1fefa9e90673916323a0f00840b4c91e76a9
[ "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 "agent/task_worker_pool.h" #include <pthread.h> #include <sys/stat.h> #include <boost/lexical_cast.hpp> #include <chrono> #include <csignal> #include <ctime> #include <sstream> #include <string> #include "common/status.h" #include "env/env.h" #include "gen_cpp/FrontendService.h" #include "gen_cpp/Types_types.h" #include "gutil/strings/substitute.h" #include "http/http_client.h" #include "olap/data_dir.h" #include "olap/olap_common.h" #include "olap/snapshot_manager.h" #include "olap/storage_engine.h" #include "olap/tablet.h" #include "olap/task/engine_alter_tablet_task.h" #include "olap/task/engine_batch_load_task.h" #include "olap/task/engine_checksum_task.h" #include "olap/task/engine_clone_task.h" #include "olap/task/engine_publish_version_task.h" #include "olap/task/engine_storage_migration_task.h" #include "olap/utils.h" #include "runtime/exec_env.h" #include "runtime/snapshot_loader.h" #include "service/backend_options.h" #include "util/doris_metrics.h" #include "util/file_utils.h" #include "util/monotime.h" #include "util/stopwatch.hpp" using std::deque; using std::list; using std::lock_guard; using std::map; using std::set; using std::string; using std::stringstream; using std::to_string; using std::vector; namespace doris { const uint32_t TASK_FINISH_MAX_RETRY = 3; const uint32_t PUBLISH_VERSION_MAX_RETRY = 3; const uint32_t REPORT_TASK_WORKER_COUNT = 1; const uint32_t REPORT_DISK_STATE_WORKER_COUNT = 1; const uint32_t REPORT_OLAP_TABLE_WORKER_COUNT = 1; std::atomic_ulong TaskWorkerPool::_s_report_version(time(NULL) * 10000); Mutex TaskWorkerPool::_s_task_signatures_lock; map<TTaskType::type, set<int64_t>> TaskWorkerPool::_s_task_signatures; FrontendServiceClientCache TaskWorkerPool::_master_service_client_cache; TaskWorkerPool::TaskWorkerPool(const TaskWorkerType task_worker_type, ExecEnv* env, const TMasterInfo& master_info) : _master_info(master_info), _agent_utils(new AgentUtils()), _master_client(new MasterServerClient(_master_info, &_master_service_client_cache)), _env(env), _worker_thread_condition_variable(&_worker_thread_lock), _task_worker_type(task_worker_type) { _backend.__set_host(BackendOptions::get_localhost()); _backend.__set_be_port(config::be_port); _backend.__set_http_port(config::webserver_port); } TaskWorkerPool::~TaskWorkerPool() {} void TaskWorkerPool::start() { // Init task pool and task workers switch (_task_worker_type) { case TaskWorkerType::CREATE_TABLE: _worker_count = config::create_tablet_worker_count; _callback_function = _create_tablet_worker_thread_callback; break; case TaskWorkerType::DROP_TABLE: _worker_count = config::drop_tablet_worker_count; _callback_function = _drop_tablet_worker_thread_callback; break; case TaskWorkerType::PUSH: case TaskWorkerType::REALTIME_PUSH: _worker_count = config::push_worker_count_normal_priority + config::push_worker_count_high_priority; _callback_function = _push_worker_thread_callback; break; case TaskWorkerType::PUBLISH_VERSION: _worker_count = config::publish_version_worker_count; _callback_function = _publish_version_worker_thread_callback; break; case TaskWorkerType::CLEAR_TRANSACTION_TASK: _worker_count = config::clear_transaction_task_worker_count; _callback_function = _clear_transaction_task_worker_thread_callback; break; case TaskWorkerType::DELETE: _worker_count = config::delete_worker_count; _callback_function = _push_worker_thread_callback; break; case TaskWorkerType::ALTER_TABLE: _worker_count = config::alter_tablet_worker_count; _callback_function = _alter_tablet_worker_thread_callback; break; case TaskWorkerType::CLONE: _worker_count = config::clone_worker_count; _callback_function = _clone_worker_thread_callback; break; case TaskWorkerType::STORAGE_MEDIUM_MIGRATE: _worker_count = config::storage_medium_migrate_count; _callback_function = _storage_medium_migrate_worker_thread_callback; break; case TaskWorkerType::CHECK_CONSISTENCY: _worker_count = config::check_consistency_worker_count; _callback_function = _check_consistency_worker_thread_callback; break; case TaskWorkerType::REPORT_TASK: _worker_count = REPORT_TASK_WORKER_COUNT; _callback_function = _report_task_worker_thread_callback; break; case TaskWorkerType::REPORT_DISK_STATE: _worker_count = REPORT_DISK_STATE_WORKER_COUNT; _callback_function = _report_disk_state_worker_thread_callback; break; case TaskWorkerType::REPORT_OLAP_TABLE: _worker_count = REPORT_OLAP_TABLE_WORKER_COUNT; _callback_function = _report_tablet_worker_thread_callback; break; case TaskWorkerType::UPLOAD: _worker_count = config::upload_worker_count; _callback_function = _upload_worker_thread_callback; break; case TaskWorkerType::DOWNLOAD: _worker_count = config::download_worker_count; _callback_function = _download_worker_thread_callback; break; case TaskWorkerType::MAKE_SNAPSHOT: _worker_count = config::make_snapshot_worker_count; _callback_function = _make_snapshot_thread_callback; break; case TaskWorkerType::RELEASE_SNAPSHOT: _worker_count = config::release_snapshot_worker_count; _callback_function = _release_snapshot_thread_callback; break; case TaskWorkerType::MOVE: _worker_count = 1; _callback_function = _move_dir_thread_callback; break; case TaskWorkerType::RECOVER_TABLET: _worker_count = 1; _callback_function = _recover_tablet_thread_callback; break; case TaskWorkerType::UPDATE_TABLET_META_INFO: _worker_count = 1; _callback_function = _update_tablet_meta_worker_thread_callback; break; default: // pass break; } #ifndef BE_TEST for (uint32_t i = 0; i < _worker_count; i++) { _spawn_callback_worker_thread(_callback_function); } #endif } void TaskWorkerPool::submit_task(const TAgentTaskRequest& task) { const TTaskType::type task_type = task.task_type; int64_t signature = task.signature; std::string type_str; EnumToString(TTaskType, task_type, type_str); LOG(INFO) << "submitting task. type=" << type_str << ", signature=" << signature; if (_register_task_info(task_type, signature)) { // Set the receiving time of task so that we can determine whether it is timed out later (const_cast<TAgentTaskRequest&>(task)).__set_recv_time(time(nullptr)); size_t task_count_in_queue = 0; { lock_guard<Mutex> worker_thread_lock(_worker_thread_lock); _tasks.push_back(task); task_count_in_queue = _tasks.size(); _worker_thread_condition_variable.notify_one(); } LOG(INFO) << "success to submit task. type=" << type_str << ", signature=" << signature << ", task_count_in_queue=" << task_count_in_queue; } else { LOG(INFO) << "fail to register task. type=" << type_str << ", signature=" << signature; } } bool TaskWorkerPool::_register_task_info(const TTaskType::type task_type, int64_t signature) { lock_guard<Mutex> task_signatures_lock(_s_task_signatures_lock); set<int64_t>& signature_set = _s_task_signatures[task_type]; return signature_set.insert(signature).second; } void TaskWorkerPool::_remove_task_info(const TTaskType::type task_type, int64_t signature) { size_t queue_size; { lock_guard<Mutex> task_signatures_lock(_s_task_signatures_lock); set<int64_t>& signature_set = _s_task_signatures[task_type]; signature_set.erase(signature); queue_size = signature_set.size(); } std::string type_str; EnumToString(TTaskType, task_type, type_str); LOG(INFO) << "remove task info. type=" << type_str << ", signature=" << signature << ", queue_size=" << queue_size; } void TaskWorkerPool::_spawn_callback_worker_thread(CALLBACK_FUNCTION callback_func) { pthread_t thread; sigset_t mask; sigset_t omask; int err = 0; // TODO: why need to catch these signals, should leave a comment sigemptyset(&mask); sigaddset(&mask, SIGCHLD); sigaddset(&mask, SIGHUP); sigaddset(&mask, SIGPIPE); pthread_sigmask(SIG_SETMASK, &mask, &omask); while (true) { err = pthread_create(&thread, NULL, callback_func, this); if (err != 0) { LOG(WARNING) << "failed to spawn a thread. error: " << err; #ifndef BE_TEST sleep(config::sleep_one_second); #endif } else { pthread_detach(thread); break; } } } void TaskWorkerPool::_finish_task(const TFinishTaskRequest& finish_task_request) { // Return result to FE TMasterResult result; uint32_t try_time = 0; while (try_time < TASK_FINISH_MAX_RETRY) { DorisMetrics::instance()->finish_task_requests_total.increment(1); AgentStatus client_status = _master_client->finish_task(finish_task_request, &result); if (client_status == DORIS_SUCCESS) { LOG(INFO) << "finish task success."; break; } else { DorisMetrics::instance()->finish_task_requests_failed.increment(1); LOG(WARNING) << "finish task failed. status_code=" << result.status.status_code; try_time += 1; } #ifndef BE_TEST sleep(config::sleep_one_second); #endif } } uint32_t TaskWorkerPool::_get_next_task_index(int32_t thread_count, std::deque<TAgentTaskRequest>& tasks, TPriority::type priority) { int32_t index = -1; deque<TAgentTaskRequest>::size_type task_count = tasks.size(); for (uint32_t i = 0; i < task_count; ++i) { TAgentTaskRequest task = tasks[i]; if (priority == TPriority::HIGH) { if (task.__isset.priority && task.priority == TPriority::HIGH) { index = i; break; } } } if (index == -1) { if (priority == TPriority::HIGH) { return index; } index = 0; } return index; } void* TaskWorkerPool::_create_tablet_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; #ifndef BE_TEST while (true) { #endif TAgentTaskRequest agent_task_req; TCreateTabletReq create_tablet_req; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); create_tablet_req = agent_task_req.create_tablet_req; worker_pool_this->_tasks.pop_front(); } TStatusCode::type status_code = TStatusCode::OK; vector<string> error_msgs; TStatus task_status; std::vector<TTabletInfo> finish_tablet_infos; OLAPStatus create_status = worker_pool_this->_env->storage_engine()->create_tablet(create_tablet_req); if (create_status != OLAPStatus::OLAP_SUCCESS) { LOG(WARNING) << "create table failed. status: " << create_status << ", signature: " << agent_task_req.signature; // TODO liutao09 distinguish the OLAPStatus status_code = TStatusCode::RUNTIME_ERROR; } else { ++_s_report_version; // get path hash of the created tablet BaseTabletSharedPtr tablet = StorageEngine::instance()->tablet_manager()-> get_base_tablet(create_tablet_req.tablet_id, create_tablet_req.tablet_schema.schema_hash); DCHECK(tablet != nullptr); TTabletInfo tablet_info; tablet_info.tablet_id = tablet->table_id(); tablet_info.schema_hash = tablet->schema_hash(); tablet_info.version = create_tablet_req.version; tablet_info.version_hash = create_tablet_req.version_hash; tablet_info.row_count = 0; tablet_info.data_size = 0; tablet_info.__set_path_hash(tablet->data_dir()->path_hash()); finish_tablet_infos.push_back(tablet_info); } task_status.__set_status_code(status_code); task_status.__set_error_msgs(error_msgs); TFinishTaskRequest finish_task_request; finish_task_request.__set_finish_tablet_infos(finish_tablet_infos); finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_report_version(_s_report_version); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); finish_task_request.__set_task_status(task_status); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); #ifndef BE_TEST } #endif return (void*)0; } void* TaskWorkerPool::_drop_tablet_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; #ifndef BE_TEST while (true) { #endif TAgentTaskRequest agent_task_req; TDropTabletReq drop_tablet_req; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); drop_tablet_req = agent_task_req.drop_tablet_req; worker_pool_this->_tasks.pop_front(); } TStatusCode::type status_code = TStatusCode::OK; vector<string> error_msgs; TStatus task_status; BaseTabletSharedPtr dropped_tablet = StorageEngine::instance()->tablet_manager()-> get_base_tablet(drop_tablet_req.tablet_id, drop_tablet_req.schema_hash); if (dropped_tablet != nullptr) { OLAPStatus drop_status = StorageEngine::instance()->tablet_manager()->drop_tablet( drop_tablet_req.tablet_id, drop_tablet_req.schema_hash); if (drop_status != OLAP_SUCCESS) { LOG(WARNING) << "drop table failed! signature: " << agent_task_req.signature; error_msgs.push_back("drop table failed!"); status_code = TStatusCode::RUNTIME_ERROR; } // if tablet is dropped by fe, then the related txn should also be removed StorageEngine::instance()->txn_manager()->force_rollback_tablet_related_txns( dropped_tablet->data_dir()->get_meta(), drop_tablet_req.tablet_id, drop_tablet_req.schema_hash, dropped_tablet->tablet_uid()); } task_status.__set_status_code(status_code); task_status.__set_error_msgs(error_msgs); TFinishTaskRequest finish_task_request; finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); finish_task_request.__set_task_status(task_status); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); #ifndef BE_TEST } #endif return (void*)0; } void* TaskWorkerPool::_alter_tablet_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; #ifndef BE_TEST while (true) { #endif TAgentTaskRequest agent_task_req; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); worker_pool_this->_tasks.pop_front(); } int64_t signatrue = agent_task_req.signature; LOG(INFO) << "get alter table task, signature: " << agent_task_req.signature; bool is_task_timeout = false; if (agent_task_req.__isset.recv_time) { int64_t time_elapsed = time(nullptr) - agent_task_req.recv_time; if (time_elapsed > config::report_task_interval_seconds * 20) { LOG(INFO) << "task elapsed " << time_elapsed << " seconds since it is inserted to queue, it is timeout"; is_task_timeout = true; } } if (!is_task_timeout) { TFinishTaskRequest finish_task_request; TTaskType::type task_type = agent_task_req.task_type; switch (task_type) { case TTaskType::ALTER: worker_pool_this->_alter_tablet(worker_pool_this, agent_task_req, signatrue, task_type, &finish_task_request); break; default: // pass break; } worker_pool_this->_finish_task(finish_task_request); } worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); #ifndef BE_TEST } #endif return (void*)0; } void TaskWorkerPool::_alter_tablet(TaskWorkerPool* worker_pool_this, const TAgentTaskRequest& agent_task_req, int64_t signature, const TTaskType::type task_type, TFinishTaskRequest* finish_task_request) { AgentStatus status = DORIS_SUCCESS; TStatus task_status; vector<string> error_msgs; string process_name; switch (task_type) { case TTaskType::ALTER: process_name = "alter"; break; default: std::string task_name; EnumToString(TTaskType, task_type, task_name); LOG(WARNING) << "schema change type invalid. type: " << task_name << ", signature: " << signature; status = DORIS_TASK_REQUEST_ERROR; break; } // Check last schema change status, if failed delete tablet file // Do not need to adjust delete success or not // Because if delete failed create rollup will failed TTabletId new_tablet_id; TSchemaHash new_schema_hash = 0; if (status == DORIS_SUCCESS) { new_tablet_id = agent_task_req.alter_tablet_req_v2.new_tablet_id; new_schema_hash = agent_task_req.alter_tablet_req_v2.new_schema_hash; EngineAlterTabletTask engine_task(agent_task_req.alter_tablet_req_v2, signature, task_type, &error_msgs, process_name); OLAPStatus sc_status = worker_pool_this->_env->storage_engine()->execute_task(&engine_task); if (sc_status != OLAP_SUCCESS) { status = DORIS_ERROR; } else { status = DORIS_SUCCESS; } } if (status == DORIS_SUCCESS) { ++_s_report_version; LOG(INFO) << process_name << " finished. signature: " << signature; } // Return result to fe finish_task_request->__set_backend(_backend); finish_task_request->__set_report_version(_s_report_version); finish_task_request->__set_task_type(task_type); finish_task_request->__set_signature(signature); vector<TTabletInfo> finish_tablet_infos; if (status == DORIS_SUCCESS) { TTabletInfo tablet_info; status = _get_tablet_info(new_tablet_id, new_schema_hash, signature, &tablet_info); if (status != DORIS_SUCCESS) { LOG(WARNING) << process_name << " success, but get new tablet info failed." << "tablet_id: " << new_tablet_id << ", schema_hash: " << new_schema_hash << ", signature: " << signature; } else { finish_tablet_infos.push_back(tablet_info); } } if (status == DORIS_SUCCESS) { finish_task_request->__set_finish_tablet_infos(finish_tablet_infos); LOG(INFO) << process_name << " success. signature: " << signature; error_msgs.push_back(process_name + " success"); task_status.__set_status_code(TStatusCode::OK); } else if (status == DORIS_TASK_REQUEST_ERROR) { LOG(WARNING) << "alter table request task type invalid. " << "signature:" << signature; error_msgs.push_back("alter table request new tablet id or schema count invalid."); task_status.__set_status_code(TStatusCode::ANALYSIS_ERROR); } else { LOG(WARNING) << process_name << " failed. signature: " << signature; error_msgs.push_back(process_name + " failed"); error_msgs.push_back("status: " + _agent_utils->print_agent_status(status)); task_status.__set_status_code(TStatusCode::RUNTIME_ERROR); } task_status.__set_error_msgs(error_msgs); finish_task_request->__set_task_status(task_status); } void* TaskWorkerPool::_push_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; // gen high priority worker thread TPriority::type priority = TPriority::NORMAL; int32_t push_worker_count_high_priority = config::push_worker_count_high_priority; static uint32_t s_worker_count = 0; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); if (s_worker_count < push_worker_count_high_priority) { ++s_worker_count; priority = TPriority::HIGH; } } #ifndef BE_TEST while (true) { #endif AgentStatus status = DORIS_SUCCESS; TAgentTaskRequest agent_task_req; TPushReq push_req; int32_t index = 0; do { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } index = worker_pool_this->_get_next_task_index( config::push_worker_count_normal_priority + config::push_worker_count_high_priority, worker_pool_this->_tasks, priority); if (index < 0) { // there is no high priority task. notify other thread to handle normal task worker_pool_this->_worker_thread_condition_variable.notify_one(); break; } agent_task_req = worker_pool_this->_tasks[index]; push_req = agent_task_req.push_req; worker_pool_this->_tasks.erase(worker_pool_this->_tasks.begin() + index); } while (0); #ifndef BE_TEST if (index < 0) { // there is no high priority task in queue sleep(1); continue; } #endif LOG(INFO) << "get push task. signature: " << agent_task_req.signature << " priority: " << priority; vector<TTabletInfo> tablet_infos; EngineBatchLoadTask engine_task(push_req, &tablet_infos, agent_task_req.signature, &status); worker_pool_this->_env->storage_engine()->execute_task(&engine_task); #ifndef BE_TEST if (status == DORIS_PUSH_HAD_LOADED) { // remove the task and not return to fe worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); continue; } #endif // Return result to fe vector<string> error_msgs; TStatus task_status; TFinishTaskRequest finish_task_request; finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); if (push_req.push_type == TPushType::DELETE) { finish_task_request.__set_request_version(push_req.version); finish_task_request.__set_request_version_hash(push_req.version_hash); } if (status == DORIS_SUCCESS) { VLOG(3) << "push ok.signature: " << agent_task_req.signature; error_msgs.push_back("push success"); ++_s_report_version; task_status.__set_status_code(TStatusCode::OK); finish_task_request.__set_finish_tablet_infos(tablet_infos); } else if (status == DORIS_TASK_REQUEST_ERROR) { LOG(WARNING) << "push request push_type invalid. type: " << push_req.push_type << ", signature: " << agent_task_req.signature; error_msgs.push_back("push request push_type invalid."); task_status.__set_status_code(TStatusCode::ANALYSIS_ERROR); } else { LOG(WARNING) << "push failed, error_code: " << status << ", signature: " << agent_task_req.signature; error_msgs.push_back("push failed"); task_status.__set_status_code(TStatusCode::RUNTIME_ERROR); } task_status.__set_error_msgs(error_msgs); finish_task_request.__set_task_status(task_status); finish_task_request.__set_report_version(_s_report_version); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); #ifndef BE_TEST } #endif return (void*)0; } void* TaskWorkerPool::_publish_version_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; #ifndef BE_TEST while (true) { #endif TAgentTaskRequest agent_task_req; TPublishVersionRequest publish_version_req; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); publish_version_req = agent_task_req.publish_version_req; worker_pool_this->_tasks.pop_front(); } DorisMetrics::instance()->publish_task_request_total.increment(1); LOG(INFO) << "get publish version task, signature:" << agent_task_req.signature; Status st; vector<TTabletId> error_tablet_ids; uint32_t retry_time = 0; OLAPStatus res = OLAP_SUCCESS; while (retry_time < PUBLISH_VERSION_MAX_RETRY) { error_tablet_ids.clear(); EnginePublishVersionTask engine_task(publish_version_req, &error_tablet_ids); res = worker_pool_this->_env->storage_engine()->execute_task(&engine_task); if (res == OLAP_SUCCESS) { break; } else { LOG(WARNING) << "publish version error, retry. [transaction_id=" << publish_version_req.transaction_id << ", error_tablets_size=" << error_tablet_ids.size() << "]"; ++retry_time; SleepFor(MonoDelta::FromSeconds(1)); } } TFinishTaskRequest finish_task_request; if (res != OLAP_SUCCESS) { DorisMetrics::instance()->publish_task_failed_total.increment(1); // if publish failed, return failed, FE will ignore this error and // check error tablet ids and FE will also republish this task LOG(WARNING) << "publish version failed. signature:" << agent_task_req.signature << ", error_code=" << res; st = Status::RuntimeError(strings::Substitute("publish version failed. error=$0", res)); finish_task_request.__set_error_tablet_ids(error_tablet_ids); } else { _s_report_version++; LOG(INFO) << "publish_version success. signature:" << agent_task_req.signature; } st.to_thrift(&finish_task_request.task_status); finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); finish_task_request.__set_report_version(_s_report_version); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); #ifndef BE_TEST } #endif return (void*)0; } void* TaskWorkerPool::_clear_transaction_task_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; #ifndef BE_TEST while (true) { #endif TAgentTaskRequest agent_task_req; TClearTransactionTaskRequest clear_transaction_task_req; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); clear_transaction_task_req = agent_task_req.clear_transaction_task_req; worker_pool_this->_tasks.pop_front(); } LOG(INFO) << "get clear transaction task task, signature:" << agent_task_req.signature << ", transaction_id: " << clear_transaction_task_req.transaction_id << ", partition id size: " << clear_transaction_task_req.partition_id.size(); TStatusCode::type status_code = TStatusCode::OK; vector<string> error_msgs; TStatus task_status; if (clear_transaction_task_req.transaction_id > 0) { // transaction_id should be greater than zero. // If it is not greater than zero, no need to execute // the following clear_transaction_task() function. if (!clear_transaction_task_req.partition_id.empty()) { worker_pool_this->_env->storage_engine()->clear_transaction_task( clear_transaction_task_req.transaction_id, clear_transaction_task_req.partition_id); } else { worker_pool_this->_env->storage_engine()->clear_transaction_task( clear_transaction_task_req.transaction_id); } LOG(INFO) << "finish to clear transaction task. signature:" << agent_task_req.signature << ", transaction_id: " << clear_transaction_task_req.transaction_id; } else { LOG(WARNING) << "invalid transaction id: " << clear_transaction_task_req.transaction_id << ", signature: " << agent_task_req.signature; } task_status.__set_status_code(status_code); task_status.__set_error_msgs(error_msgs); TFinishTaskRequest finish_task_request; finish_task_request.__set_task_status(task_status); finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); #ifndef BE_TEST } #endif return (void*)0; } void* TaskWorkerPool::_update_tablet_meta_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; while (true) { TAgentTaskRequest agent_task_req; TUpdateTabletMetaInfoReq update_tablet_meta_req; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); update_tablet_meta_req = agent_task_req.update_tablet_meta_info_req; worker_pool_this->_tasks.pop_front(); } LOG(INFO) << "get update tablet meta task, signature:" << agent_task_req.signature; TStatusCode::type status_code = TStatusCode::OK; vector<string> error_msgs; TStatus task_status; for (auto tablet_meta_info : update_tablet_meta_req.tabletMetaInfos) { BaseTabletSharedPtr tablet = StorageEngine::instance()->tablet_manager()-> get_base_tablet(tablet_meta_info.tablet_id, tablet_meta_info.schema_hash); if (tablet == nullptr) { LOG(WARNING) << "could not find tablet when update partition id" << " tablet_id=" << tablet_meta_info.tablet_id << " schema_hash=" << tablet_meta_info.schema_hash; continue; } WriteLock wrlock(tablet->get_header_lock_ptr()); // update tablet meta if (!tablet_meta_info.__isset.meta_type) { tablet->set_partition_id(tablet_meta_info.partition_id); } else { switch (tablet_meta_info.meta_type) { case TTabletMetaType::PARTITIONID: tablet->set_partition_id(tablet_meta_info.partition_id); break; case TTabletMetaType::INMEMORY: tablet->tablet_meta()->mutable_tablet_schema()->set_is_in_memory( tablet_meta_info.is_in_memory); break; } } tablet->save_meta(); } LOG(INFO) << "finish update tablet meta task. signature:" << agent_task_req.signature; task_status.__set_status_code(status_code); task_status.__set_error_msgs(error_msgs); TFinishTaskRequest finish_task_request; finish_task_request.__set_task_status(task_status); finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); } return (void*)0; } void* TaskWorkerPool::_clone_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; #ifndef BE_TEST while (true) { #endif AgentStatus status = DORIS_SUCCESS; TAgentTaskRequest agent_task_req; TCloneReq clone_req; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); clone_req = agent_task_req.clone_req; worker_pool_this->_tasks.pop_front(); } DorisMetrics::instance()->clone_requests_total.increment(1); LOG(INFO) << "get clone task. signature:" << agent_task_req.signature; vector<string> error_msgs; vector<TTabletInfo> tablet_infos; EngineCloneTask engine_task(clone_req, worker_pool_this->_master_info, agent_task_req.signature, &error_msgs, &tablet_infos, &status); worker_pool_this->_env->storage_engine()->execute_task(&engine_task); // Return result to fe TStatus task_status; TFinishTaskRequest finish_task_request; finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); TStatusCode::type status_code = TStatusCode::OK; if (status != DORIS_SUCCESS && status != DORIS_CREATE_TABLE_EXIST) { DorisMetrics::instance()->clone_requests_failed.increment(1); status_code = TStatusCode::RUNTIME_ERROR; LOG(WARNING) << "clone failed. signature: " << agent_task_req.signature; error_msgs.push_back("clone failed."); } else { LOG(INFO) << "clone success, set tablet infos." << "signature:" << agent_task_req.signature; finish_task_request.__set_finish_tablet_infos(tablet_infos); } task_status.__set_status_code(status_code); task_status.__set_error_msgs(error_msgs); finish_task_request.__set_task_status(task_status); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); #ifndef BE_TEST } #endif return (void*)0; } void* TaskWorkerPool::_storage_medium_migrate_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; #ifndef BE_TEST while (true) { #endif TAgentTaskRequest agent_task_req; TStorageMediumMigrateReq storage_medium_migrate_req; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); storage_medium_migrate_req = agent_task_req.storage_medium_migrate_req; worker_pool_this->_tasks.pop_front(); } TStatusCode::type status_code = TStatusCode::OK; vector<string> error_msgs; TStatus task_status; EngineStorageMigrationTask engine_task(storage_medium_migrate_req); OLAPStatus res = worker_pool_this->_env->storage_engine()->execute_task(&engine_task); if (res != OLAP_SUCCESS) { LOG(WARNING) << "storage media migrate failed. status: " << res << ", signature: " << agent_task_req.signature; status_code = TStatusCode::RUNTIME_ERROR; } else { LOG(INFO) << "storage media migrate success. status:" << res << "," << ", signature:" << agent_task_req.signature; } task_status.__set_status_code(status_code); task_status.__set_error_msgs(error_msgs); TFinishTaskRequest finish_task_request; finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); finish_task_request.__set_task_status(task_status); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); #ifndef BE_TEST } #endif return (void*)0; } void* TaskWorkerPool::_check_consistency_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; #ifndef BE_TEST while (true) { #endif TAgentTaskRequest agent_task_req; TCheckConsistencyReq check_consistency_req; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); check_consistency_req = agent_task_req.check_consistency_req; worker_pool_this->_tasks.pop_front(); } TStatusCode::type status_code = TStatusCode::OK; vector<string> error_msgs; TStatus task_status; uint32_t checksum = 0; EngineChecksumTask engine_task( check_consistency_req.tablet_id, check_consistency_req.schema_hash, check_consistency_req.version, check_consistency_req.version_hash, &checksum); OLAPStatus res = worker_pool_this->_env->storage_engine()->execute_task(&engine_task); if (res != OLAP_SUCCESS) { LOG(WARNING) << "check consistency failed. status: " << res << ", signature: " << agent_task_req.signature; status_code = TStatusCode::RUNTIME_ERROR; } else { LOG(INFO) << "check consistency success. status:" << res << ", signature:" << agent_task_req.signature << ", checksum:" << checksum; } task_status.__set_status_code(status_code); task_status.__set_error_msgs(error_msgs); TFinishTaskRequest finish_task_request; finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); finish_task_request.__set_task_status(task_status); finish_task_request.__set_tablet_checksum(static_cast<int64_t>(checksum)); finish_task_request.__set_request_version(check_consistency_req.version); finish_task_request.__set_request_version_hash(check_consistency_req.version_hash); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); #ifndef BE_TEST } #endif return (void*)0; } void* TaskWorkerPool::_report_task_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; TReportRequest request; request.__set_force_recovery(config::force_recovery); request.__set_backend(worker_pool_this->_backend); #ifndef BE_TEST while (true) { #endif { lock_guard<Mutex> task_signatures_lock(_s_task_signatures_lock); request.__set_tasks(_s_task_signatures); } DorisMetrics::instance()->report_task_requests_total.increment(1); TMasterResult result; AgentStatus status = worker_pool_this->_master_client->report(request, &result); if (status != DORIS_SUCCESS) { DorisMetrics::instance()->report_task_requests_failed.increment(1); LOG(WARNING) << "finish report task failed. status:" << status << ", master host:" << worker_pool_this->_master_info.network_address.hostname << "port:" << worker_pool_this->_master_info.network_address.port; } #ifndef BE_TEST sleep(config::report_task_interval_seconds); } #endif return (void*)0; } void* TaskWorkerPool::_report_disk_state_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; TReportRequest request; request.__set_force_recovery(config::force_recovery); request.__set_backend(worker_pool_this->_backend); #ifndef BE_TEST while (true) { if (worker_pool_this->_master_info.network_address.port == 0) { // port == 0 means not received heartbeat yet // sleep a short time and try again LOG(INFO) << "waiting to receive first heartbeat from frontend"; sleep(config::sleep_one_second); continue; } #endif vector<DataDirInfo> data_dir_infos; worker_pool_this->_env->storage_engine()->get_all_data_dir_info(&data_dir_infos, true /* update */); map<string, TDisk> disks; for (auto& root_path_info : data_dir_infos) { TDisk disk; disk.__set_root_path(root_path_info.path); disk.__set_path_hash(root_path_info.path_hash); disk.__set_storage_medium(root_path_info.storage_medium); disk.__set_disk_total_capacity(static_cast<double>(root_path_info.disk_capacity)); disk.__set_data_used_capacity(static_cast<double>(root_path_info.data_used_capacity)); disk.__set_disk_available_capacity(static_cast<double>(root_path_info.available)); disk.__set_used(root_path_info.is_used); disks[root_path_info.path] = disk; DorisMetrics::instance()->disks_total_capacity.set_metric( root_path_info.path, root_path_info.disk_capacity); DorisMetrics::instance()->disks_avail_capacity.set_metric( root_path_info.path, root_path_info.available); DorisMetrics::instance()->disks_data_used_capacity.set_metric( root_path_info.path, root_path_info.data_used_capacity); DorisMetrics::instance()->disks_state.set_metric( root_path_info.path, root_path_info.is_used ? 1L : 0L); } request.__set_disks(disks); DorisMetrics::instance()->report_disk_requests_total.increment(1); TMasterResult result; AgentStatus status = worker_pool_this->_master_client->report(request, &result); if (status != DORIS_SUCCESS) { DorisMetrics::instance()->report_disk_requests_failed.increment(1); LOG(WARNING) << "finish report disk state failed. status:" << status << ", master host:" << worker_pool_this->_master_info.network_address.hostname << ", port:" << worker_pool_this->_master_info.network_address.port; } #ifndef BE_TEST // wait for notifying until timeout StorageEngine::instance()->wait_for_report_notify( config::report_disk_state_interval_seconds, false); } #endif return (void*)0; } void* TaskWorkerPool::_report_tablet_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; TReportRequest request; request.__set_force_recovery(config::force_recovery); request.__set_backend(worker_pool_this->_backend); request.__isset.tablets = true; AgentStatus status = DORIS_SUCCESS; #ifndef BE_TEST while (true) { if (worker_pool_this->_master_info.network_address.port == 0) { // port == 0 means not received heartbeat yet // sleep a short time and try again LOG(INFO) << "waiting to receive first heartbeat from frontend"; sleep(config::sleep_one_second); continue; } #endif request.tablets.clear(); request.__set_report_version(_s_report_version); OLAPStatus report_all_tablets_info_status = StorageEngine::instance()->tablet_manager()->report_all_tablets_info( &request.tablets); if (report_all_tablets_info_status != OLAP_SUCCESS) { LOG(WARNING) << "report get all tablets info failed. status: " << report_all_tablets_info_status; #ifndef BE_TEST // wait for notifying until timeout StorageEngine::instance()->wait_for_report_notify( config::report_tablet_interval_seconds, true); continue; #else return (void*)0; #endif } int64_t max_compaction_score = std::max(DorisMetrics::instance()->tablet_cumulative_max_compaction_score.value(), DorisMetrics::instance()->tablet_base_max_compaction_score.value()); request.__set_tablet_max_compaction_score(max_compaction_score); TMasterResult result; status = worker_pool_this->_master_client->report(request, &result); if (status != DORIS_SUCCESS) { DorisMetrics::instance()->report_all_tablets_requests_failed.increment(1); LOG(WARNING) << "finish report olap table state failed. status:" << status << ", master host:" << worker_pool_this->_master_info.network_address.hostname << ", port:" << worker_pool_this->_master_info.network_address.port; } #ifndef BE_TEST // wait for notifying until timeout StorageEngine::instance()->wait_for_report_notify(config::report_tablet_interval_seconds, true); } #endif return (void*)0; } void* TaskWorkerPool::_upload_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; #ifndef BE_TEST while (true) { #endif TAgentTaskRequest agent_task_req; TUploadReq upload_request; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); upload_request = agent_task_req.upload_req; worker_pool_this->_tasks.pop_front(); } LOG(INFO) << "get upload task, signature:" << agent_task_req.signature << ", job id:" << upload_request.job_id; std::map<int64_t, std::vector<std::string>> tablet_files; SnapshotLoader loader(worker_pool_this->_env, upload_request.job_id, agent_task_req.signature); Status status = loader.upload(upload_request.src_dest_map, upload_request.broker_addr, upload_request.broker_prop, &tablet_files); TStatusCode::type status_code = TStatusCode::OK; std::vector<string> error_msgs; if (!status.ok()) { status_code = TStatusCode::RUNTIME_ERROR; LOG(WARNING) << "upload failed. job id: " << upload_request.job_id << ", msg: " << status.get_error_msg(); error_msgs.push_back(status.get_error_msg()); } TStatus task_status; task_status.__set_status_code(status_code); task_status.__set_error_msgs(error_msgs); TFinishTaskRequest finish_task_request; finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); finish_task_request.__set_task_status(task_status); finish_task_request.__set_tablet_files(tablet_files); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); LOG(INFO) << "finished upload task, signature: " << agent_task_req.signature << ", job id:" << upload_request.job_id; #ifndef BE_TEST } #endif return (void*)0; } void* TaskWorkerPool::_download_worker_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; #ifndef BE_TEST while (true) { #endif TAgentTaskRequest agent_task_req; TDownloadReq download_request; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); download_request = agent_task_req.download_req; worker_pool_this->_tasks.pop_front(); } LOG(INFO) << "get download task, signature: " << agent_task_req.signature << ", job id:" << download_request.job_id; TStatusCode::type status_code = TStatusCode::OK; std::vector<string> error_msgs; TStatus task_status; // TODO: download std::vector<int64_t> downloaded_tablet_ids; SnapshotLoader loader(worker_pool_this->_env, download_request.job_id, agent_task_req.signature); Status status = loader.download(download_request.src_dest_map, download_request.broker_addr, download_request.broker_prop, &downloaded_tablet_ids); if (!status.ok()) { status_code = TStatusCode::RUNTIME_ERROR; LOG(WARNING) << "download failed. job id: " << download_request.job_id << ", msg: " << status.get_error_msg(); error_msgs.push_back(status.get_error_msg()); } task_status.__set_status_code(status_code); task_status.__set_error_msgs(error_msgs); TFinishTaskRequest finish_task_request; finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); finish_task_request.__set_task_status(task_status); finish_task_request.__set_downloaded_tablet_ids(downloaded_tablet_ids); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); LOG(INFO) << "finished download task, signature: " << agent_task_req.signature << ", job id:" << download_request.job_id; #ifndef BE_TEST } #endif return (void*)0; } void* TaskWorkerPool::_make_snapshot_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; #ifndef BE_TEST while (true) { #endif TAgentTaskRequest agent_task_req; TSnapshotRequest snapshot_request; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); snapshot_request = agent_task_req.snapshot_req; worker_pool_this->_tasks.pop_front(); } LOG(INFO) << "get snapshot task, signature:" << agent_task_req.signature; TStatusCode::type status_code = TStatusCode::OK; vector<string> error_msgs; TStatus task_status; string snapshot_path; std::vector<string> snapshot_files; OLAPStatus make_snapshot_status = SnapshotManager::instance()->make_snapshot(snapshot_request, &snapshot_path); if (make_snapshot_status != OLAP_SUCCESS) { status_code = make_snapshot_status == OLAP_ERR_VERSION_ALREADY_MERGED ? TStatusCode::OLAP_ERR_VERSION_ALREADY_MERGED : TStatusCode::RUNTIME_ERROR; LOG(WARNING) << "make_snapshot failed. tablet_id:" << snapshot_request.tablet_id << ", schema_hash:" << snapshot_request.schema_hash << ", version:" << snapshot_request.version << ", version_hash:" << snapshot_request.version_hash << ", status: " << make_snapshot_status; error_msgs.push_back("make_snapshot failed. status: " + boost::lexical_cast<string>(make_snapshot_status)); } else { LOG(INFO) << "make_snapshot success. tablet_id:" << snapshot_request.tablet_id << ", schema_hash:" << snapshot_request.schema_hash << ", version:" << snapshot_request.version << ", version_hash:" << snapshot_request.version_hash << ", snapshot_path:" << snapshot_path; if (snapshot_request.__isset.list_files) { // list and save all snapshot files // snapshot_path like: data/snapshot/20180417205230.1.86400 // we need to add subdir: tablet_id/schema_hash/ std::stringstream ss; ss << snapshot_path << "/" << snapshot_request.tablet_id << "/" << snapshot_request.schema_hash << "/"; Status st = FileUtils::list_files(Env::Default(), ss.str(), &snapshot_files); if (!st.ok()) { status_code = TStatusCode::RUNTIME_ERROR; LOG(WARNING) << "make_snapshot failed. tablet_id:" << snapshot_request.tablet_id << ", schema_hash:" << snapshot_request.schema_hash << ", version:" << snapshot_request.version << ", version_hash:" << snapshot_request.version_hash << ",list file failed: " << st.get_error_msg(); error_msgs.push_back("make_snapshot failed. list file failed: " + st.get_error_msg()); } } } task_status.__set_status_code(status_code); task_status.__set_error_msgs(error_msgs); TFinishTaskRequest finish_task_request; finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); finish_task_request.__set_snapshot_path(snapshot_path); finish_task_request.__set_snapshot_files(snapshot_files); finish_task_request.__set_task_status(task_status); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); #ifndef BE_TEST } #endif return (void*)0; } void* TaskWorkerPool::_release_snapshot_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; #ifndef BE_TEST while (true) { #endif TAgentTaskRequest agent_task_req; TReleaseSnapshotRequest release_snapshot_request; { lock_guard<Mutex> worker_thread_lock(worker_pool_this->_worker_thread_lock); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); release_snapshot_request = agent_task_req.release_snapshot_req; worker_pool_this->_tasks.pop_front(); } LOG(INFO) << "get release snapshot task, signature:" << agent_task_req.signature; TStatusCode::type status_code = TStatusCode::OK; vector<string> error_msgs; TStatus task_status; string& snapshot_path = release_snapshot_request.snapshot_path; OLAPStatus release_snapshot_status = SnapshotManager::instance()->release_snapshot(snapshot_path); if (release_snapshot_status != OLAP_SUCCESS) { status_code = TStatusCode::RUNTIME_ERROR; LOG(WARNING) << "release_snapshot failed. snapshot_path: " << snapshot_path << ". status: " << release_snapshot_status; error_msgs.push_back("release_snapshot failed. status: " + boost::lexical_cast<string>(release_snapshot_status)); } else { LOG(INFO) << "release_snapshot success. snapshot_path: " << snapshot_path << ". status: " << release_snapshot_status; } task_status.__set_status_code(status_code); task_status.__set_error_msgs(error_msgs); TFinishTaskRequest finish_task_request; finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); finish_task_request.__set_task_status(task_status); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); #ifndef BE_TEST } #endif return (void*)0; } AgentStatus TaskWorkerPool::_get_tablet_info(const TTabletId tablet_id, const TSchemaHash schema_hash, int64_t signature, TTabletInfo* tablet_info) { AgentStatus status = DORIS_SUCCESS; tablet_info->__set_tablet_id(tablet_id); tablet_info->__set_schema_hash(schema_hash); OLAPStatus olap_status = StorageEngine::instance()->tablet_manager()->report_tablet_info(tablet_info); if (olap_status != OLAP_SUCCESS) { LOG(WARNING) << "get tablet info failed. status: " << olap_status << ", signature: " << signature; status = DORIS_ERROR; } return status; } void* TaskWorkerPool::_move_dir_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; #ifndef BE_TEST while (true) { #endif TAgentTaskRequest agent_task_req; TMoveDirReq move_dir_req; { MutexLock worker_thread_lock(&(worker_pool_this->_worker_thread_lock)); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); move_dir_req = agent_task_req.move_dir_req; worker_pool_this->_tasks.pop_front(); } LOG(INFO) << "get move dir task, signature:" << agent_task_req.signature << ", job id:" << move_dir_req.job_id; TStatusCode::type status_code = TStatusCode::OK; vector<string> error_msgs; TStatus task_status; // TODO: move dir AgentStatus status = worker_pool_this->_move_dir( move_dir_req.tablet_id, move_dir_req.schema_hash, move_dir_req.src, move_dir_req.job_id, true /* TODO */, &error_msgs); if (status != DORIS_SUCCESS) { status_code = TStatusCode::RUNTIME_ERROR; LOG(WARNING) << "failed to move dir: " << move_dir_req.src << ", tablet id: " << move_dir_req.tablet_id << ", signature: " << agent_task_req.signature << ", job id: " << move_dir_req.job_id; } else { LOG(INFO) << "finished to move dir:" << move_dir_req.src << ", tablet_id:" << move_dir_req.tablet_id << ", signature:" << agent_task_req.signature << ", job id:" << move_dir_req.job_id; } task_status.__set_status_code(status_code); task_status.__set_error_msgs(error_msgs); TFinishTaskRequest finish_task_request; finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); finish_task_request.__set_task_status(task_status); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); #ifndef BE_TEST } #endif return (void*)0; } AgentStatus TaskWorkerPool::_move_dir(const TTabletId tablet_id, const TSchemaHash schema_hash, const std::string& src, int64_t job_id, bool overwrite, std::vector<std::string>* error_msgs) { TabletSharedPtr tablet = StorageEngine::instance()->tablet_manager()->get_tablet(tablet_id, schema_hash); if (tablet == nullptr) { LOG(INFO) << "failed to get tablet. tablet_id:" << tablet_id << ", schema hash:" << schema_hash; error_msgs->push_back("failed to get tablet"); return DORIS_TASK_REQUEST_ERROR; } std::string dest_tablet_dir = tablet->tablet_path(); SnapshotLoader loader(_env, job_id, tablet_id); Status status = loader.move(src, tablet, overwrite); if (!status.ok()) { LOG(WARNING) << "move failed. job id: " << job_id << ", msg: " << status.get_error_msg(); error_msgs->push_back(status.get_error_msg()); return DORIS_INTERNAL_ERROR; } return DORIS_SUCCESS; } void* TaskWorkerPool::_recover_tablet_thread_callback(void* arg_this) { TaskWorkerPool* worker_pool_this = (TaskWorkerPool*)arg_this; while (true) { TAgentTaskRequest agent_task_req; TRecoverTabletReq recover_tablet_req; { MutexLock worker_thread_lock(&(worker_pool_this->_worker_thread_lock)); while (worker_pool_this->_tasks.empty()) { worker_pool_this->_worker_thread_condition_variable.wait(); } agent_task_req = worker_pool_this->_tasks.front(); recover_tablet_req = agent_task_req.recover_tablet_req; worker_pool_this->_tasks.pop_front(); } TStatusCode::type status_code = TStatusCode::OK; vector<string> error_msgs; TStatus task_status; LOG(INFO) << "begin to recover tablet." << ", tablet_id:" << recover_tablet_req.tablet_id << "." << recover_tablet_req.schema_hash << ", version:" << recover_tablet_req.version << "-" << recover_tablet_req.version_hash; OLAPStatus status = worker_pool_this->_env->storage_engine()->recover_tablet_until_specfic_version( recover_tablet_req); if (status != OLAP_SUCCESS) { status_code = TStatusCode::RUNTIME_ERROR; LOG(WARNING) << "failed to recover tablet." << "signature:" << agent_task_req.signature << ", table:" << recover_tablet_req.tablet_id << "." << recover_tablet_req.schema_hash << ", version:" << recover_tablet_req.version << "-" << recover_tablet_req.version_hash; } else { LOG(WARNING) << "succeed to recover tablet." << "signature:" << agent_task_req.signature << ", table:" << recover_tablet_req.tablet_id << "." << recover_tablet_req.schema_hash << ", version:" << recover_tablet_req.version << "-" << recover_tablet_req.version_hash; } task_status.__set_status_code(status_code); task_status.__set_error_msgs(error_msgs); TFinishTaskRequest finish_task_request; finish_task_request.__set_backend(worker_pool_this->_backend); finish_task_request.__set_task_type(agent_task_req.task_type); finish_task_request.__set_signature(agent_task_req.signature); finish_task_request.__set_task_status(task_status); worker_pool_this->_finish_task(finish_task_request); worker_pool_this->_remove_task_info(agent_task_req.task_type, agent_task_req.signature); } return (void*)0; } } // namespace doris
42.107626
100
0.656579
[ "vector" ]
d54b63479a3beddb5cd25e71e9de129819da2ddd
3,579
cc
C++
gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/ipc/service/gpu_memory_buffer_factory_dxgi.h" #include <wrl.h> #include <vector> #include "base/trace_event/trace_event.h" #include "ui/gfx/buffer_format_util.h" #include "ui/gl/gl_angle_util_win.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_image_dxgi.h" namespace gpu { GpuMemoryBufferFactoryDXGI::GpuMemoryBufferFactoryDXGI() {} GpuMemoryBufferFactoryDXGI::~GpuMemoryBufferFactoryDXGI() {} gfx::GpuMemoryBufferHandle GpuMemoryBufferFactoryDXGI::CreateGpuMemoryBuffer( gfx::GpuMemoryBufferId id, const gfx::Size& size, gfx::BufferFormat format, gfx::BufferUsage usage, int client_id, SurfaceHandle surface_handle) { TRACE_EVENT0("gpu", "GpuMemoryBufferFactoryDXGI::CreateGpuMemoryBuffer"); gfx::GpuMemoryBufferHandle handle; Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device = gl::QueryD3D11DeviceObjectFromANGLE(); if (!d3d11_device) return handle; DXGI_FORMAT dxgi_format; switch (format) { case gfx::BufferFormat::RGBA_8888: case gfx::BufferFormat::RGBX_8888: dxgi_format = DXGI_FORMAT_R8G8B8A8_UNORM; break; default: NOTREACHED(); return handle; } // We are binding as a shader resource and render target regardless of usage, // so make sure that the usage is one that we support. DCHECK(usage == gfx::BufferUsage::GPU_READ || usage == gfx::BufferUsage::SCANOUT); D3D11_TEXTURE2D_DESC desc = { size.width(), size.height(), 1, 1, dxgi_format, {1, 0}, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET, 0, D3D11_RESOURCE_MISC_SHARED_NTHANDLE | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX}; Microsoft::WRL::ComPtr<ID3D11Texture2D> d3d11_texture; if (FAILED(d3d11_device->CreateTexture2D(&desc, nullptr, d3d11_texture.GetAddressOf()))) return handle; Microsoft::WRL::ComPtr<IDXGIResource1> dxgi_resource; if (FAILED(d3d11_texture.CopyTo(dxgi_resource.GetAddressOf()))) return handle; HANDLE texture_handle; if (FAILED(dxgi_resource->CreateSharedHandle( nullptr, DXGI_SHARED_RESOURCE_READ | DXGI_SHARED_RESOURCE_WRITE, nullptr, &texture_handle))) return handle; size_t buffer_size; if (!BufferSizeForBufferFormatChecked(size, format, &buffer_size)) return handle; handle.dxgi_handle.Set(texture_handle); handle.type = gfx::DXGI_SHARED_HANDLE; handle.id = id; return handle; } void GpuMemoryBufferFactoryDXGI::DestroyGpuMemoryBuffer( gfx::GpuMemoryBufferId id, int client_id) {} ImageFactory* GpuMemoryBufferFactoryDXGI::AsImageFactory() { return this; } scoped_refptr<gl::GLImage> GpuMemoryBufferFactoryDXGI::CreateImageForGpuMemoryBuffer( gfx::GpuMemoryBufferHandle handle, const gfx::Size& size, gfx::BufferFormat format, int client_id, SurfaceHandle surface_handle) { if (handle.type != gfx::DXGI_SHARED_HANDLE) return nullptr; // Transfer ownership of handle to GLImageDXGI. auto image = base::MakeRefCounted<gl::GLImageDXGI>(size, nullptr); if (!image->InitializeHandle(std::move(handle.dxgi_handle), 0, format)) return nullptr; return image; } unsigned GpuMemoryBufferFactoryDXGI::RequiredTextureType() { return GL_TEXTURE_2D; } bool GpuMemoryBufferFactoryDXGI::SupportsFormatRGB() { return true; } } // namespace gpu
28.862903
79
0.727578
[ "render", "vector" ]
d54bd89b2215116de947d92e924719354e468ab7
24,368
cc
C++
tensorflow/lite/kernels/pooling.cc
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
190,993
2015-11-09T13:17:30.000Z
2022-03-31T23:05:27.000Z
tensorflow/lite/kernels/pooling.cc
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
48,461
2015-11-09T14:21:11.000Z
2022-03-31T23:17:33.000Z
tensorflow/lite/kernels/pooling.cc
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
104,981
2015-11-09T13:40:17.000Z
2022-03-31T19:51:54.000Z
/* Copyright 2017 The TensorFlow Authors. 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 "tensorflow/lite/kernels/internal/optimized/integer_ops/pooling.h" #include <stddef.h> #include <stdint.h> #include <cstdlib> #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/compatibility.h" #include "tensorflow/lite/kernels/internal/optimized/optimized_ops.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/pooling.h" #include "tensorflow/lite/kernels/internal/reference/pooling.h" #include "tensorflow/lite/kernels/internal/reference/reference_ops.h" #include "tensorflow/lite/kernels/internal/tensor.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/internal/types.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/padding.h" namespace tflite { namespace ops { namespace builtin { namespace pooling { // This file has two implementation of each pooling op. enum KernelType { kReference, kGenericOptimized, }; enum PoolType { kAverage, kMax, kL2, }; struct OpData { TfLitePaddingValues padding; }; void* Init(TfLiteContext* context, const char* buffer, size_t length) { // This is a builtin op, so we don't use the contents in 'buffer', if any. // Instead, we allocate a new object to carry information from Prepare() to // Eval(). return new OpData; } void Free(TfLiteContext* context, void* buffer) { delete reinterpret_cast<OpData*>(buffer); } template <PoolType pool_type> TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); int batches = input->dims->data[0]; int height = input->dims->data[1]; int width = input->dims->data[2]; int channels_out = input->dims->data[3]; // Matching GetWindowedOutputSize in TensorFlow. auto padding = params->padding; int out_width, out_height; // Prevent division by 0 in optimized pooling implementations TF_LITE_ENSURE(context, params->stride_height > 0); TF_LITE_ENSURE(context, params->stride_width > 0); data->padding = ComputePaddingHeightWidth( params->stride_height, params->stride_width, 1, 1, height, width, params->filter_height, params->filter_width, padding, &out_height, &out_width); if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) { if (pool_type == kAverage || pool_type == kMax) { TFLITE_DCHECK_LE(std::abs(input->params.scale - output->params.scale), 1.0e-6); TFLITE_DCHECK_EQ(input->params.zero_point, output->params.zero_point); } if (pool_type == kL2) { // We currently don't have a quantized implementation of L2Pool TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32); } } TfLiteIntArray* output_size = TfLiteIntArrayCreate(4); output_size->data[0] = batches; output_size->data[1] = out_height; output_size->data[2] = out_width; output_size->data[3] = channels_out; return context->ResizeTensor(context, output, output_size); } template <KernelType kernel_type> TfLiteStatus AverageEvalFloat(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { float activation_min, activation_max; CalculateActivationRange(params->activation, &activation_min, &activation_max); #define TF_LITE_AVERAGE_POOL(type) \ tflite::PoolParams op_params; \ op_params.stride_height = params->stride_height; \ op_params.stride_width = params->stride_width; \ op_params.filter_height = params->filter_height; \ op_params.filter_width = params->filter_width; \ op_params.padding_values.height = data->padding.height; \ op_params.padding_values.width = data->padding.width; \ op_params.float_activation_min = activation_min; \ op_params.float_activation_max = activation_max; \ TF_LITE_ENSURE(context, type::AveragePool(op_params, GetTensorShape(input), \ GetTensorData<float>(input), \ GetTensorShape(output), \ GetTensorData<float>(output))) if (kernel_type == kReference) { TF_LITE_AVERAGE_POOL(reference_ops); } else { TF_LITE_AVERAGE_POOL(optimized_ops); } #undef TF_LITE_AVERAGE_POOL return kTfLiteOk; } template <KernelType kernel_type> TfLiteStatus AverageEvalQuantizedUint8(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min; int32_t activation_max; (void)CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); #define TF_LITE_AVERAGE_POOL(type) \ tflite::PoolParams op_params; \ op_params.stride_height = params->stride_height; \ op_params.stride_width = params->stride_width; \ op_params.filter_height = params->filter_height; \ op_params.filter_width = params->filter_width; \ op_params.padding_values.height = data->padding.height; \ op_params.padding_values.width = data->padding.width; \ op_params.quantized_activation_min = activation_min; \ op_params.quantized_activation_max = activation_max; \ TF_LITE_ENSURE(context, type::AveragePool(op_params, GetTensorShape(input), \ GetTensorData<uint8_t>(input), \ GetTensorShape(output), \ GetTensorData<uint8_t>(output))) if (kernel_type == kReference) { TF_LITE_AVERAGE_POOL(reference_ops); } else { TF_LITE_AVERAGE_POOL(optimized_ops); } #undef TF_LITE_AVERAGE_POOL return kTfLiteOk; } template <KernelType kernel_type> TfLiteStatus AverageEvalQuantizedInt8(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min; int32_t activation_max; (void)CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); #define TF_LITE_AVERAGE_POOL(type) \ tflite::PoolParams op_params; \ op_params.stride_height = params->stride_height; \ op_params.stride_width = params->stride_width; \ op_params.filter_height = params->filter_height; \ op_params.filter_width = params->filter_width; \ op_params.padding_values.height = data->padding.height; \ op_params.padding_values.width = data->padding.width; \ op_params.quantized_activation_min = activation_min; \ op_params.quantized_activation_max = activation_max; \ TF_LITE_ENSURE(context, type::AveragePool(op_params, GetTensorShape(input), \ GetTensorData<int8_t>(input), \ GetTensorShape(output), \ GetTensorData<int8_t>(output))) if (kernel_type == kReference) { TF_LITE_AVERAGE_POOL(reference_integer_ops); } else { TF_LITE_AVERAGE_POOL(optimized_integer_ops); } #undef TF_LITE_AVERAGE_POOL return kTfLiteOk; } template <KernelType kernel_type> TfLiteStatus AverageEvalQuantizedInt16(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min; int32_t activation_max; CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); #define TF_LITE_AVERAGE_POOL(type) \ tflite::PoolParams op_params; \ op_params.stride_height = params->stride_height; \ op_params.stride_width = params->stride_width; \ op_params.filter_height = params->filter_height; \ op_params.filter_width = params->filter_width; \ op_params.padding_values.height = data->padding.height; \ op_params.padding_values.width = data->padding.width; \ op_params.quantized_activation_min = activation_min; \ op_params.quantized_activation_max = activation_max; \ TF_LITE_ENSURE(context, type::AveragePool(op_params, GetTensorShape(input), \ GetTensorData<int16_t>(input), \ GetTensorShape(output), \ GetTensorData<int16_t>(output))) TF_LITE_AVERAGE_POOL(reference_integer_ops); #undef TF_LITE_AVERAGE_POOL return kTfLiteOk; } template <KernelType kernel_type> void MaxEvalFloat(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { float activation_min, activation_max; CalculateActivationRange(params->activation, &activation_min, &activation_max); #define TF_LITE_MAX_POOL(type) \ tflite::PoolParams op_params; \ op_params.stride_height = params->stride_height; \ op_params.stride_width = params->stride_width; \ op_params.filter_height = params->filter_height; \ op_params.filter_width = params->filter_width; \ op_params.padding_values.height = data->padding.height; \ op_params.padding_values.width = data->padding.width; \ op_params.float_activation_min = activation_min; \ op_params.float_activation_max = activation_max; \ type::MaxPool(op_params, GetTensorShape(input), GetTensorData<float>(input), \ GetTensorShape(output), GetTensorData<float>(output)) if (kernel_type == kReference) { TF_LITE_MAX_POOL(reference_ops); } else { TF_LITE_MAX_POOL(optimized_ops); } #undef TF_LITE_MAX_POOL } template <KernelType kernel_type> void MaxEvalQuantizedUInt8(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min; int32_t activation_max; (void)CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); #define TF_LITE_MAX_POOL(type) \ tflite::PoolParams op_params; \ op_params.stride_height = params->stride_height; \ op_params.stride_width = params->stride_width; \ op_params.filter_height = params->filter_height; \ op_params.filter_width = params->filter_width; \ op_params.padding_values.height = data->padding.height; \ op_params.padding_values.width = data->padding.width; \ op_params.quantized_activation_min = activation_min; \ op_params.quantized_activation_max = activation_max; \ type::MaxPool(op_params, GetTensorShape(input), \ GetTensorData<uint8_t>(input), GetTensorShape(output), \ GetTensorData<uint8_t>(output)) if (kernel_type == kReference) { TF_LITE_MAX_POOL(reference_ops); } else { TF_LITE_MAX_POOL(optimized_ops); } #undef TF_LITE_MAX_POOL } template <KernelType kernel_type> void MaxEvalQuantizedInt8(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min; int32_t activation_max; (void)CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); #define TF_LITE_MAX_POOL(type) \ tflite::PoolParams op_params; \ op_params.stride_height = params->stride_height; \ op_params.stride_width = params->stride_width; \ op_params.filter_height = params->filter_height; \ op_params.filter_width = params->filter_width; \ op_params.padding_values.height = data->padding.height; \ op_params.padding_values.width = data->padding.width; \ op_params.quantized_activation_min = activation_min; \ op_params.quantized_activation_max = activation_max; \ type::MaxPool(op_params, GetTensorShape(input), \ GetTensorData<int8_t>(input), GetTensorShape(output), \ GetTensorData<int8_t>(output)) if (kernel_type == kReference) { TF_LITE_MAX_POOL(reference_integer_ops); } else { TF_LITE_MAX_POOL(optimized_integer_ops); } #undef TF_LITE_MAX_POOL } template <KernelType kernel_type> void MaxEvalQuantizedInt16(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min; int32_t activation_max; CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); #define TF_LITE_MAX_POOL(type) \ tflite::PoolParams op_params; \ op_params.stride_height = params->stride_height; \ op_params.stride_width = params->stride_width; \ op_params.filter_height = params->filter_height; \ op_params.filter_width = params->filter_width; \ op_params.padding_values.height = data->padding.height; \ op_params.padding_values.width = data->padding.width; \ op_params.quantized_activation_min = activation_min; \ op_params.quantized_activation_max = activation_max; \ type::MaxPool(op_params, GetTensorShape(input), \ GetTensorData<int16_t>(input), GetTensorShape(output), \ GetTensorData<int16_t>(output)) TF_LITE_MAX_POOL(reference_integer_ops); #undef TF_LITE_MAX_POOL } template <KernelType kernel_type> void L2EvalFloat(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { float activation_min, activation_max; CalculateActivationRange(params->activation, &activation_min, &activation_max); #define TF_LITE_L2_POOL(type) \ tflite::PoolParams op_params; \ op_params.stride_height = params->stride_height; \ op_params.stride_width = params->stride_width; \ op_params.filter_height = params->filter_height; \ op_params.filter_width = params->filter_width; \ op_params.padding_values.height = data->padding.height; \ op_params.padding_values.width = data->padding.width; \ op_params.float_activation_min = activation_min; \ op_params.float_activation_max = activation_max; \ type::L2Pool(op_params, GetTensorShape(input), GetTensorData<float>(input), \ GetTensorShape(output), GetTensorData<float>(output)) if (kernel_type == kReference) { TF_LITE_L2_POOL(reference_ops); } else { TF_LITE_L2_POOL(optimized_ops); } #undef TF_LITE_L2_POOL } #undef TF_LITE_KERNEL_TYPE_DISPATCH template <KernelType kernel_type> TfLiteStatus AverageEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: return AverageEvalFloat<kernel_type>(context, node, params, data, input, output); case kTfLiteUInt8: return AverageEvalQuantizedUint8<kernel_type>(context, node, params, data, input, output); case kTfLiteInt8: return AverageEvalQuantizedInt8<kernel_type>(context, node, params, data, input, output); case kTfLiteInt16: return AverageEvalQuantizedInt16<kernel_type>(context, node, params, data, input, output); default: TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } template <KernelType kernel_type> TfLiteStatus MaxEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: MaxEvalFloat<kernel_type>(context, node, params, data, input, output); break; case kTfLiteUInt8: MaxEvalQuantizedUInt8<kernel_type>(context, node, params, data, input, output); break; case kTfLiteInt8: MaxEvalQuantizedInt8<kernel_type>(context, node, params, data, input, output); break; case kTfLiteInt16: MaxEvalQuantizedInt16<kernel_type>(context, node, params, data, input, output); break; default: TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } template <KernelType kernel_type> TfLiteStatus L2Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: L2EvalFloat<kernel_type>(context, node, params, data, input, output); break; case kTfLiteUInt8: // We don't have a quantized implementation, so just fall through to the // 'default' case. default: context->ReportError(context, "Type %d not currently supported.", input->type); return kTfLiteError; } return kTfLiteOk; } } // namespace pooling TfLiteRegistration* Register_AVERAGE_POOL_REF() { static TfLiteRegistration r = {pooling::Init, pooling::Free, pooling::GenericPrepare<pooling::kAverage>, pooling::AverageEval<pooling::kReference>}; return &r; } TfLiteRegistration* Register_MAX_POOL_REF() { static TfLiteRegistration r = {pooling::Init, pooling::Free, pooling::GenericPrepare<pooling::kMax>, pooling::MaxEval<pooling::kReference>}; return &r; } TfLiteRegistration* Register_L2_POOL_REF() { static TfLiteRegistration r = {pooling::Init, pooling::Free, pooling::GenericPrepare<pooling::kL2>, pooling::L2Eval<pooling::kReference>}; return &r; } TfLiteRegistration* Register_AVERAGE_POOL_GENERIC_OPT() { static TfLiteRegistration r = { pooling::Init, pooling::Free, pooling::GenericPrepare<pooling::kAverage>, pooling::AverageEval<pooling::kGenericOptimized>}; return &r; } TfLiteRegistration* Register_MAX_POOL_GENERIC_OPT() { static TfLiteRegistration r = {pooling::Init, pooling::Free, pooling::GenericPrepare<pooling::kMax>, pooling::MaxEval<pooling::kGenericOptimized>}; return &r; } TfLiteRegistration* Register_L2_POOL_GENERIC_OPT() { static TfLiteRegistration r = {pooling::Init, pooling::Free, pooling::GenericPrepare<pooling::kL2>, pooling::L2Eval<pooling::kGenericOptimized>}; return &r; } TfLiteRegistration* Register_AVERAGE_POOL_2D() { return Register_AVERAGE_POOL_GENERIC_OPT(); } TfLiteRegistration* Register_MAX_POOL_2D() { return Register_MAX_POOL_GENERIC_OPT(); } TfLiteRegistration* Register_L2_POOL_2D() { return Register_L2_POOL_GENERIC_OPT(); } } // namespace builtin } // namespace ops } // namespace tflite
46.239089
80
0.610596
[ "object" ]
d550060eb90f2131e986c24c0b1cf821c68045a7
47,594
cpp
C++
libredex/IRTypeChecker.cpp
APKLab/redex
6530161a333f7edff7b77e5562c654111daae227
[ "MIT" ]
null
null
null
libredex/IRTypeChecker.cpp
APKLab/redex
6530161a333f7edff7b77e5562c654111daae227
[ "MIT" ]
null
null
null
libredex/IRTypeChecker.cpp
APKLab/redex
6530161a333f7edff7b77e5562c654111daae227
[ "MIT" ]
1
2021-04-15T22:18:57.000Z
2021-04-15T22:18:57.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "IRTypeChecker.h" #include <boost/optional/optional.hpp> #include "Debug.h" #include "DexPosition.h" #include "DexUtil.h" #include "Match.h" #include "MonitorCount.h" #include "Resolver.h" #include "Show.h" #include "StlUtil.h" #include "Trace.h" using namespace sparta; using namespace type_inference; namespace { using namespace ir_analyzer; // We abort the type checking process at the first error encountered. class TypeCheckingException final : public std::runtime_error { public: explicit TypeCheckingException(const std::string& what_arg) : std::runtime_error(what_arg) {} }; std::ostringstream& print_register(std::ostringstream& out, reg_t reg) { if (reg == RESULT_REGISTER) { out << "result"; } else { out << "register v" << reg; } return out; } void check_type_match(reg_t reg, IRType actual, IRType expected) { if (actual == BOTTOM) { // There's nothing to do for unreachable code. return; } if (actual == SCALAR && expected != REFERENCE) { // If the type is SCALAR and we're checking compatibility with an integer // or float type, we just bail out. return; } if (!TypeDomain(actual).leq(TypeDomain(expected))) { std::ostringstream out; print_register(out, reg) << ": expected type " << expected << ", but found " << actual << " instead"; throw TypeCheckingException(out.str()); } } /* * There are cases where we cannot precisely infer the exception type for * MOVE_EXCEPTION. In these cases, we use Ljava/lang/Throwable; as a fallback * type. */ bool is_inference_fallback_type(const DexType* type) { return type == type::java_lang_Throwable(); } /* * We might not have the external DexClass to fully determine the hierarchy. * Therefore, be more lenient when assigning from or to external DexType. */ bool check_cast_helper(const DexType* from, const DexType* to) { // We can always cast to Object if (to == type::java_lang_Object()) { return true; } // We can never cast from Object to anything besides Object if (from == type::java_lang_Object() && from != to) { // TODO(T66567547) sanity check that type::check_cast would have agreed always_assert(!type::check_cast(from, to)); return false; } // If we have any external types (aside from Object and the other well known // types), allow them. auto from_cls = type_class(from); auto to_cls = type_class(to); if (!from_cls || !to_cls) { return true; } // Assume the type hierarchies of the well known external types are stable // across Android versions. When their class definitions present, perform the // regular type inheritance check. if ((from_cls->is_external() && !g_redex->pointers_cache().m_well_known_types.count(from)) || (to_cls->is_external() && !g_redex->pointers_cache().m_well_known_types.count(to))) { return true; } return type::check_cast(from, to); } // Type assignment check between two reference types. We assume that both `from` // and `to` are reference types. // Took reference from: // http://androidxref.com/6.0.1_r10/xref/art/runtime/verifier/reg_type-inl.h#88 // // Note: the expectation is that `from` and `to` are reference types, otherwise // the check fails. bool check_is_assignable_from(const DexType* from, const DexType* to, bool strict) { always_assert(from && to); always_assert_log(!type::is_primitive(from), "%s", SHOW(from)); if (type::is_primitive(from) || type::is_primitive(to)) { return false; // Expect types be a reference type. } if (from == to) { return true; // Fast path if the two are equal. } if (to == type::java_lang_Object()) { return true; // All reference types can be assigned to Object. } if (type::is_java_lang_object_array(to)) { // All reference arrays may be assigned to Object[] return type::is_reference_array(from); } if (type::is_array(from) && type::is_array(to)) { if (type::get_array_level(from) != type::get_array_level(to)) { return false; } auto efrom = type::get_array_element_type(from); auto eto = type::get_array_element_type(to); return check_cast_helper(efrom, eto); } if (!strict) { // If `to` is an interface, allow any assignment when non-strict. // This behavior is copied from AOSP. auto to_cls = type_class(to); if (to_cls != nullptr && is_interface(to_cls)) { return true; } } return check_cast_helper(from, to); } void check_wide_type_match(reg_t reg, IRType actual1, IRType actual2, IRType expected1, IRType expected2) { if (actual1 == BOTTOM) { // There's nothing to do for unreachable code. return; } if (actual1 == SCALAR1 && actual2 == SCALAR2) { // If type of the pair of registers is (SCALAR1, SCALAR2), we just bail // out. return; } if (!(TypeDomain(actual1).leq(TypeDomain(expected1)) && TypeDomain(actual2).leq(TypeDomain(expected2)))) { std::ostringstream out; print_register(out, reg) << ": expected type (" << expected1 << ", " << expected2 << "), but found (" << actual1 << ", " << actual2 << ") instead"; throw TypeCheckingException(out.str()); } } void assume_type(TypeEnvironment* state, reg_t reg, IRType expected, bool ignore_top = false) { if (state->is_bottom()) { // There's nothing to do for unreachable code. return; } IRType actual = state->get_type(reg).element(); if (ignore_top && actual == TOP) { return; } check_type_match(reg, actual, /* expected */ expected); } void assume_wide_type(TypeEnvironment* state, reg_t reg, IRType expected1, IRType expected2) { if (state->is_bottom()) { // There's nothing to do for unreachable code. return; } IRType actual1 = state->get_type(reg).element(); IRType actual2 = state->get_type(reg + 1).element(); check_wide_type_match(reg, actual1, actual2, /* expected1 */ expected1, /* expected2 */ expected2); } // This is used for the operand of a comparison operation with zero. The // complexity here is that this operation may be performed on either an // integer or a reference. void assume_comparable_with_zero(TypeEnvironment* state, reg_t reg) { if (state->is_bottom()) { // There's nothing to do for unreachable code. return; } IRType t = state->get_type(reg).element(); if (t == SCALAR) { // We can't say anything conclusive about a register that has SCALAR type, // so we just bail out. return; } if (!(TypeDomain(t).leq(TypeDomain(REFERENCE)) || TypeDomain(t).leq(TypeDomain(INT)))) { std::ostringstream out; print_register(out, reg) << ": expected integer or reference type, but found " << t << " instead"; throw TypeCheckingException(out.str()); } } // This is used for the operands of a comparison operation between two // registers. The complexity here is that this operation may be performed on // either two integers or two references. void assume_comparable(TypeEnvironment* state, reg_t reg1, reg_t reg2) { if (state->is_bottom()) { // There's nothing to do for unreachable code. return; } IRType t1 = state->get_type(reg1).element(); IRType t2 = state->get_type(reg2).element(); if (!((TypeDomain(t1).leq(TypeDomain(REFERENCE)) && TypeDomain(t2).leq(TypeDomain(REFERENCE))) || (TypeDomain(t1).leq(TypeDomain(SCALAR)) && TypeDomain(t2).leq(TypeDomain(SCALAR)) && (t1 != FLOAT) && (t2 != FLOAT)))) { // Two values can be used in a comparison operation if they either both // have the REFERENCE type or have non-float scalar types. Note that in // the case where one or both types have the SCALAR type, we can't // definitely rule out the absence of a type error. std::ostringstream out; print_register(out, reg1) << " and "; print_register(out, reg2) << ": incompatible types in comparison " << t1 << " and " << t2; throw TypeCheckingException(out.str()); } } void assume_integer(TypeEnvironment* state, reg_t reg) { assume_type(state, reg, /* expected */ INT); } void assume_float(TypeEnvironment* state, reg_t reg) { assume_type(state, reg, /* expected */ FLOAT); } void assume_long(TypeEnvironment* state, reg_t reg) { assume_wide_type(state, reg, /* expected1 */ LONG1, /* expected2 */ LONG2); } void assume_double(TypeEnvironment* state, reg_t reg) { assume_wide_type( state, reg, /* expected1 */ DOUBLE1, /* expected2 */ DOUBLE2); } void assume_wide_scalar(TypeEnvironment* state, reg_t reg) { assume_wide_type( state, reg, /* expected1 */ SCALAR1, /* expected2 */ SCALAR2); } class Result final { public: static Result Ok() { return Result(); } static Result make_error(const std::string& s) { return Result(s); } const std::string& error_message() const { always_assert(!is_ok); return m_error_message; } bool operator==(const Result& that) const { return is_ok == that.is_ok && m_error_message == that.m_error_message; } bool operator!=(const Result& that) const { return !(*this == that); } private: bool is_ok{true}; std::string m_error_message; explicit Result(const std::string& s) : is_ok(false), m_error_message(s) {} Result() = default; }; static bool has_move_result_pseudo(const MethodItemEntry& mie) { return mie.type == MFLOW_OPCODE && mie.insn->has_move_result_pseudo(); } static bool is_move_result_pseudo(const MethodItemEntry& mie) { return mie.type == MFLOW_OPCODE && opcode::is_a_move_result_pseudo(mie.insn->opcode()); } Result check_load_params(const DexMethod* method) { bool is_static_method = is_static(method); const auto* signature = method->get_proto()->get_args(); auto sig_it = signature->begin(); size_t load_insns_cnt = 0; auto handle_instance = [&](IRInstruction* insn) -> boost::optional<std::string> { // Must be a param-object. if (insn->opcode() != IOPCODE_LOAD_PARAM_OBJECT) { return std::string( "First parameter must be loaded with load-param-object: ") + show(insn); } return boost::none; }; auto handle_other = [&](IRInstruction* insn) -> boost::optional<std::string> { if (sig_it == signature->end()) { return std::string("Not enough argument types for ") + show(insn); } bool ok = false; switch (insn->opcode()) { case IOPCODE_LOAD_PARAM_OBJECT: ok = type::is_object(*sig_it); break; case IOPCODE_LOAD_PARAM: ok = type::is_primitive(*sig_it) && !type::is_wide_type(*sig_it); break; case IOPCODE_LOAD_PARAM_WIDE: ok = type::is_primitive(*sig_it) && type::is_wide_type(*sig_it); break; default: not_reached(); } if (!ok) { return std::string("Incompatible load-param ") + show(insn) + " for " + type::type_shorty(*sig_it); } ++sig_it; return boost::none; }; bool non_load_param_seen = false; using handler_t = std::function<boost::optional<std::string>(IRInstruction*)>; handler_t handler = is_static_method ? handler_t(handle_other) : handler_t(handle_instance); for (const auto& mie : InstructionIterable(method->get_code()->cfg().entry_block())) { IRInstruction* insn = mie.insn; if (!opcode::is_a_load_param(insn->opcode())) { non_load_param_seen = true; continue; } ++load_insns_cnt; if (non_load_param_seen) { return Result::make_error("Saw non-load-param instruction before " + show(insn)); } auto res = handler(insn); if (res) { return Result::make_error(res.get()); } // Instance methods have an extra 'load-param' at the beginning for the // instance object. // Once we've checked that, though, the rest is the same so move on to // using 'handle_other' in all cases. handler = handler_t(handle_other); } size_t expected_load_params_cnt = method->get_proto()->get_args()->size() + !is_static_method; if (load_insns_cnt != expected_load_params_cnt) { return Result::make_error( "Number of existing load-param instructions (" + show(load_insns_cnt) + ") is lower than expected (" + show(expected_load_params_cnt) + ")"); } return Result::Ok(); } // Every variable created by a new-instance call should be initialized by a // proper invoke-direct <init>. Here, we perform simple check to find some // missing calls resulting in use of uninitialized variables. We correctly track // variables in a basic block, the most common form of allocation+init. Result check_uninitialized(const DexMethod* method) { auto* code = method->get_code(); std::map<uint16_t, IRInstruction*> uninitialized_regs; std::map<IRInstruction*, std::set<uint16_t>> uninitialized_regs_rev; auto remove_from_uninitialized_list = [&](uint16_t reg) { auto it = uninitialized_regs.find(reg); if (it != uninitialized_regs.end()) { uninitialized_regs_rev[it->second].erase(reg); uninitialized_regs.erase(reg); } }; for (auto it = code->begin(); it != code->end(); ++it) { if (it->type != MFLOW_OPCODE) { continue; } auto* insn = it->insn; auto op = insn->opcode(); if (op == OPCODE_NEW_INSTANCE) { ++it; while (it != code->end() && it->type != MFLOW_OPCODE) ++it; if (it == code->end() || it->insn->opcode() != IOPCODE_MOVE_RESULT_PSEUDO_OBJECT) { auto prev = it; prev--; return Result::make_error("No opcode-move-result after new-instance " + show(*prev) + " in \n" + show(code->cfg())); } auto reg_dest = it->insn->dest(); remove_from_uninitialized_list(reg_dest); uninitialized_regs[reg_dest] = insn; uninitialized_regs_rev[insn].insert(reg_dest); continue; } if (opcode::is_a_move(op) && !opcode::is_move_result_any(op)) { assert(insn->srcs().size() > 0); auto src = insn->srcs()[0]; auto dest = insn->dest(); if (src == dest) continue; auto it_src = uninitialized_regs.find(src); // We no longer care about the old dest remove_from_uninitialized_list(dest); // But if src was uninitialized, dest is now too if (it_src != uninitialized_regs.end()) { uninitialized_regs[dest] = it_src->second; uninitialized_regs_rev[it_src->second].insert(dest); } continue; } auto create_error = [&](const IRInstruction* instruction, const IRCode* code) { return Result::make_error("Use of uninitialized variable " + show(instruction) + " detected at " + show(*it) + " in \n" + show(code->cfg())); }; if (op == OPCODE_INVOKE_DIRECT) { auto const& sources = insn->srcs(); auto object = sources[0]; auto object_it = uninitialized_regs.find(object); if (object_it != uninitialized_regs.end()) { auto* object_ir = object_it->second; if (insn->get_method()->get_name()->str() != "<init>") { return create_error(object_ir, code); } if (insn->get_method()->get_class()->str() != object_ir->get_type()->str()) { return Result::make_error("Variable " + show(object_ir) + "initialized with the wrong type at " + show(*it) + " in \n" + show(code->cfg())); } for (auto reg : uninitialized_regs_rev[object_ir]) { uninitialized_regs.erase(reg); } uninitialized_regs_rev.erase(object_ir); } for (unsigned int i = 1; i < sources.size(); i++) { auto u_it = uninitialized_regs.find(sources[i]); if (u_it != uninitialized_regs.end()) return create_error(u_it->second, code); } continue; } auto const& sources = insn->srcs(); for (auto reg : sources) { auto u_it = uninitialized_regs.find(reg); if (u_it != uninitialized_regs.end()) return create_error(u_it->second, code); } if (insn->has_dest()) remove_from_uninitialized_list(insn->dest()); // We clear the structures after any branch, this doesn't cover all the // possible issues, but is simple auto branchingness = opcode::branchingness(op); if (op == OPCODE_THROW || (branchingness != opcode::Branchingness::BRANCH_NONE && branchingness != opcode::Branchingness::BRANCH_THROW)) { uninitialized_regs.clear(); uninitialized_regs_rev.clear(); } } return Result::Ok(); } /* * Do a linear pass to sanity-check the structure of the bytecode. */ Result check_structure(const DexMethod* method, bool check_no_overwrite_this) { check_no_overwrite_this &= !is_static(method); auto* code = method->get_code(); IRInstruction* this_insn = nullptr; bool has_seen_non_load_param_opcode{false}; for (auto it = code->begin(); it != code->end(); ++it) { // XXX we are using IRList::iterator instead of InstructionIterator here // because the latter does not support reverse iteration if (it->type != MFLOW_OPCODE) { continue; } auto* insn = it->insn; auto op = insn->opcode(); if (has_seen_non_load_param_opcode && opcode::is_a_load_param(op)) { return Result::make_error("Encountered " + show(*it) + " not at the start of the method"); } has_seen_non_load_param_opcode = !opcode::is_a_load_param(op); if (check_no_overwrite_this) { if (op == IOPCODE_LOAD_PARAM_OBJECT && this_insn == nullptr) { this_insn = insn; } else if (insn->has_dest() && insn->dest() == this_insn->dest()) { return Result::make_error( "Encountered overwrite of `this` register by " + show(insn)); } } // The instruction immediately before a move-result instruction must be // either an invoke-* or a filled-new-array instruction. if (opcode::is_a_move_result(op)) { auto prev = it; while (prev != code->begin()) { --prev; if (prev->type == MFLOW_OPCODE) { break; } } if (it == code->begin() || prev->type != MFLOW_OPCODE) { return Result::make_error("Encountered " + show(*it) + " at start of the method"); } auto prev_op = prev->insn->opcode(); if (!(opcode::is_an_invoke(prev_op) || opcode::is_filled_new_array(prev_op))) { return Result::make_error( "Encountered " + show(*it) + " without appropriate prefix " "instruction. Expected invoke or filled-new-array, got " + show(prev->insn)); } } else if (opcode::is_a_move_result_pseudo(insn->opcode()) && (it == code->begin() || !has_move_result_pseudo(*std::prev(it)))) { return Result::make_error("Encountered " + show(*it) + " without appropriate prefix " "instruction"); } else if (insn->has_move_result_pseudo() && (it == code->end() || std::next(it) == code->end() || !is_move_result_pseudo(*std::next(it)))) { return Result::make_error("Did not find move-result-pseudo after " + show(*it) + " in \n" + show(code)); } } return check_uninitialized(method); } /* * Do a linear pass to sanity-check the structure of the positions. */ Result check_positions(const DexMethod* method) { auto code = method->get_code(); std::unordered_set<DexPosition*> positions; for (auto it = code->begin(); it != code->end(); ++it) { if (it->type != MFLOW_POSITION) { continue; } auto pos = it->pos.get(); if (!positions.insert(pos).second) { return Result::make_error("Duplicate position " + show(pos)); } } std::unordered_set<DexPosition*> visited_parents; for (auto pos : positions) { if (!pos->parent) { continue; } if (!positions.count(pos->parent)) { return Result::make_error("Missing parent " + show(pos)); } for (auto p = pos; p; p = p->parent) { if (!visited_parents.insert(p).second) { return Result::make_error("Cyclic parents around " + show(pos)); } } visited_parents.clear(); } return Result::Ok(); } /* * For now, we only check if there are... * - mismatches in the monitor stack depth * - instructions that may throw in a synchronized region in a try-block without * a catch-all. */ Result check_monitors(const DexMethod* method) { auto code = method->get_code(); monitor_count::Analyzer monitor_analyzer(code->cfg()); auto blocks = monitor_analyzer.get_monitor_mismatches(); if (!blocks.empty()) { std::ostringstream out; out << "Monitor-stack mismatch (unverifiable code) in " << method->get_deobfuscated_name_or_empty() << " at blocks "; for (auto b : blocks) { out << "("; for (auto e : b->preds()) { auto count = monitor_analyzer.get_exit_state_at(e->src()); out << "B" << e->src()->id() << ":" << show(count) << " | "; } auto count = monitor_analyzer.get_exit_state_at(b); out << ") ==> B" << b->id() << ":" << show(count) << ", "; } out << " in\n" + show(code->cfg()); return Result::make_error(out.str()); } auto sketchy_insns = monitor_analyzer.get_sketchy_instructions(); std::unordered_set<cfg::Block*> sketchy_blocks; for (auto& it : sketchy_insns) { sketchy_blocks.insert(it.block()); } std20::erase_if(sketchy_blocks, [&](auto* b) { return !code->cfg().get_succ_edge_of_type(b, cfg::EDGE_THROW); }); if (!sketchy_blocks.empty()) { std::ostringstream out; out << "Throwing instructions in a synchronized region in a try-block " "without a catch-all in " << method->get_deobfuscated_name_or_empty(); bool first = true; for (auto& it : sketchy_insns) { if (!sketchy_blocks.count(it.block())) { continue; } if (first) { first = false; } else { out << " and "; } out << " at instruction B" << it.block()->id() << " '" << SHOW(it->insn) << "' @ " << std::hex << static_cast<const void*>(&*it.unwrap()); } out << " in\n" + show(code->cfg()); return Result::make_error(out.str()); } return Result::Ok(); } /** * Validate if the caller has the permit to call a method or access a field. * * +-------------------------+--------+----------+-----------+-------+ * | Access Levels Modifier | Class | Package | Subclass | World | * +-------------------------+--------+----------+-----------+-------+ * | public | Y | Y | Y | Y | * | protected | Y | Y | Y | N | * | no modifier | Y | Y | N | N | * | private | Y | N | N | N | * +-------------------------+--------+----------+-----------+-------+ */ template <typename DexMember> void validate_access(const DexMethod* accessor, const DexMember* accessee) { auto accessor_class = accessor->get_class(); if (accessee == nullptr || is_public(accessee) || accessor_class == accessee->get_class()) { return; } if (!is_private(accessee)) { auto accessee_class = accessee->get_class(); auto from_same_package = type::same_package(accessor_class, accessee_class); if (is_package_private(accessee) && from_same_package) { return; } else if (is_protected(accessee) && (from_same_package || type::check_cast(accessor_class, accessee_class))) { return; } } std::ostringstream out; out << "\nillegal access to " << (is_private(accessee) ? "private " : (is_package_private(accessee) ? "package-private " : "protected ")) << show_deobfuscated(accessee) << "\n from " << show_deobfuscated(accessor); // If the accessee is external, we don't report the error, just log it. // TODO(fengliu): We should enforce the correctness when visiting external dex // members. if (accessee->is_external()) { TRACE(TYPE, 2, "%s", out.str().c_str()); return; } throw TypeCheckingException(out.str()); } void validate_invoke_super(const DexMethodRef* callee) { auto callee_cls = type_class(callee->get_class()); if (!callee_cls || !is_interface(callee_cls)) { return; } std::ostringstream out; out << "\nillegal invoke-super to interface method defined in class " << show_deobfuscated(callee_cls) << "(note that this can happen when external framework SDKs are not " "passed to D8 as a classpath dependency; in such cases D8 may " "silently generate illegal invoke-supers to interface methods)"; throw TypeCheckingException(out.str()); } } // namespace IRTypeChecker::~IRTypeChecker() {} IRTypeChecker::IRTypeChecker(DexMethod* dex_method, bool validate_access, bool validate_invoke_super) : m_dex_method(dex_method), m_validate_access(validate_access), m_validate_invoke_super(validate_invoke_super), m_complete(false), m_verify_moves(false), m_check_no_overwrite_this(false), m_good(true), m_what("OK") {} void IRTypeChecker::run() { IRCode* code = m_dex_method->get_code(); if (m_complete) { // The type checker can only be run once on any given method. return; } if (code == nullptr) { // If the method has no associated code, the type checking trivially // succeeds. m_complete = true; return; } code->build_cfg(/* editable */ false); auto result = check_structure(m_dex_method, m_check_no_overwrite_this); if (result != Result::Ok()) { m_complete = true; m_good = false; m_what = result.error_message(); return; } // We then infer types for all the registers used in the method. const cfg::ControlFlowGraph& cfg = code->cfg(); // Check that the load-params match the signature. auto params_result = check_load_params(m_dex_method); if (params_result != Result::Ok()) { m_complete = true; m_good = false; m_what = params_result.error_message(); return; } m_type_inference = std::make_unique<TypeInference>(cfg); m_type_inference->run(m_dex_method); // Finally, we use the inferred types to type-check each instruction in the // method. We stop at the first type error encountered. auto& type_envs = m_type_inference->get_type_environments(); for (const MethodItemEntry& mie : InstructionIterable(code)) { IRInstruction* insn = mie.insn; try { auto it = type_envs.find(insn); always_assert_log( it != type_envs.end(), "%s in:\n%s", SHOW(mie), SHOW(code)); check_instruction(insn, &it->second); } catch (const TypeCheckingException& e) { m_good = false; std::ostringstream out; out << "Type error in method " << m_dex_method->get_deobfuscated_name_or_empty() << " at instruction '" << SHOW(insn) << "' @ " << std::hex << static_cast<const void*>(&mie) << " for " << e.what(); m_what = out.str(); m_complete = true; return; } } auto positions_result = check_positions(m_dex_method); if (positions_result != Result::Ok()) { m_complete = true; m_good = false; m_what = positions_result.error_message(); return; } auto monitors_result = check_monitors(m_dex_method); if (monitors_result != Result::Ok()) { m_complete = true; m_good = false; m_what = monitors_result.error_message(); return; } m_complete = true; if (traceEnabled(TYPE, 9)) { std::ostringstream out; m_type_inference->print(out); TRACE(TYPE, 9, "%s", out.str().c_str()); } } void IRTypeChecker::assume_scalar(TypeEnvironment* state, reg_t reg, bool in_move) const { assume_type(state, reg, /* expected */ SCALAR, /* ignore_top */ in_move && !m_verify_moves); } void IRTypeChecker::assume_reference(TypeEnvironment* state, reg_t reg, bool in_move) const { assume_type(state, reg, /* expected */ REFERENCE, /* ignore_top */ in_move && !m_verify_moves); } void IRTypeChecker::assume_assignable(boost::optional<const DexType*> from, DexType* to) const { // There are some cases in type inference where we have to give up // and claim we don't know anything about a dex type. See // IRTypeCheckerTest.joinCommonBaseWithConflictingInterface, for // example - the last invoke of 'base.foo()' after the blocks join - // we no longer know anything about the type of the reference. It's // in such a case as that that we have to bail out here when the from // optional is empty. if (from && !check_is_assignable_from(*from, to, false)) { std::ostringstream out; out << ": " << *from << " is not assignable to " << to << std::endl; throw TypeCheckingException(out.str()); } } // This method performs type checking only: the type environment is not updated // and the source registers of the instruction are checked against their // expected types. // // Similarly, the various assume_* functions used throughout the code to check // that the inferred type of a register matches with its expected type, as // derived from the context. void IRTypeChecker::check_instruction(IRInstruction* insn, TypeEnvironment* current_state) const { switch (insn->opcode()) { case IOPCODE_LOAD_PARAM: case IOPCODE_LOAD_PARAM_OBJECT: case IOPCODE_LOAD_PARAM_WIDE: { // IOPCODE_LOAD_PARAM_* instructions have been processed before the // analysis. break; } case OPCODE_NOP: { break; } case OPCODE_MOVE: { assume_scalar(current_state, insn->src(0), /* in_move */ true); break; } case OPCODE_MOVE_OBJECT: { assume_reference(current_state, insn->src(0), /* in_move */ true); break; } case OPCODE_MOVE_WIDE: { assume_wide_scalar(current_state, insn->src(0)); break; } case IOPCODE_MOVE_RESULT_PSEUDO: case OPCODE_MOVE_RESULT: { assume_scalar(current_state, RESULT_REGISTER); break; } case IOPCODE_MOVE_RESULT_PSEUDO_OBJECT: case OPCODE_MOVE_RESULT_OBJECT: { assume_reference(current_state, RESULT_REGISTER); break; } case IOPCODE_MOVE_RESULT_PSEUDO_WIDE: case OPCODE_MOVE_RESULT_WIDE: { assume_wide_scalar(current_state, RESULT_REGISTER); break; } case OPCODE_MOVE_EXCEPTION: { // We don't know where to grab the type of the just-caught exception. // Simply set to j.l.Throwable here. break; } case OPCODE_RETURN_VOID: { break; } case OPCODE_RETURN: { assume_scalar(current_state, insn->src(0)); break; } case OPCODE_RETURN_WIDE: { assume_wide_scalar(current_state, insn->src(0)); break; } case OPCODE_RETURN_OBJECT: { assume_reference(current_state, insn->src(0)); auto dtype = current_state->get_dex_type(insn->src(0)); auto rtype = m_dex_method->get_proto()->get_rtype(); // If the inferred type is a fallback, there's no point performing the // accurate type assignment checking. if (dtype && !is_inference_fallback_type(*dtype)) { // Return type checking is non-strict: it is allowed to return any // reference type when `rtype` is an interface. if (!check_is_assignable_from(*dtype, rtype, /*strict=*/false)) { std::ostringstream out; out << "Returning " << dtype << ", but expected from declaration " << rtype << std::endl; throw TypeCheckingException(out.str()); } } break; } case OPCODE_CONST: { break; } case OPCODE_CONST_WIDE: { break; } case OPCODE_CONST_STRING: { break; } case OPCODE_CONST_CLASS: { break; } case OPCODE_MONITOR_ENTER: case OPCODE_MONITOR_EXIT: { assume_reference(current_state, insn->src(0)); break; } case OPCODE_CHECK_CAST: { assume_reference(current_state, insn->src(0)); break; } case OPCODE_INSTANCE_OF: case OPCODE_ARRAY_LENGTH: { assume_reference(current_state, insn->src(0)); break; } case OPCODE_NEW_INSTANCE: { break; } case OPCODE_NEW_ARRAY: { assume_integer(current_state, insn->src(0)); break; } case OPCODE_FILLED_NEW_ARRAY: { const DexType* element_type = type::get_array_component_type(insn->get_type()); // We assume that structural constraints on the bytecode are satisfied, // i.e., the type is indeed an array type. always_assert(element_type != nullptr); bool is_array_of_references = type::is_object(element_type); for (size_t i = 0; i < insn->srcs_size(); ++i) { if (is_array_of_references) { assume_reference(current_state, insn->src(i)); } else { assume_scalar(current_state, insn->src(i)); } } break; } case OPCODE_FILL_ARRAY_DATA: { break; } case OPCODE_THROW: { assume_reference(current_state, insn->src(0)); break; } case OPCODE_GOTO: { break; } case OPCODE_SWITCH: { assume_integer(current_state, insn->src(0)); break; } case OPCODE_CMPL_FLOAT: case OPCODE_CMPG_FLOAT: { assume_float(current_state, insn->src(0)); assume_float(current_state, insn->src(1)); break; } case OPCODE_CMPL_DOUBLE: case OPCODE_CMPG_DOUBLE: { assume_double(current_state, insn->src(0)); assume_double(current_state, insn->src(1)); break; } case OPCODE_CMP_LONG: { assume_long(current_state, insn->src(0)); assume_long(current_state, insn->src(1)); break; } case OPCODE_IF_EQ: case OPCODE_IF_NE: { assume_comparable(current_state, insn->src(0), insn->src(1)); break; } case OPCODE_IF_LT: case OPCODE_IF_GE: case OPCODE_IF_GT: case OPCODE_IF_LE: { assume_integer(current_state, insn->src(0)); assume_integer(current_state, insn->src(1)); break; } case OPCODE_IF_EQZ: case OPCODE_IF_NEZ: { assume_comparable_with_zero(current_state, insn->src(0)); break; } case OPCODE_IF_LTZ: case OPCODE_IF_GEZ: case OPCODE_IF_GTZ: case OPCODE_IF_LEZ: { assume_integer(current_state, insn->src(0)); break; } case OPCODE_AGET: { assume_reference(current_state, insn->src(0)); assume_integer(current_state, insn->src(1)); break; } case OPCODE_AGET_BOOLEAN: case OPCODE_AGET_BYTE: case OPCODE_AGET_CHAR: case OPCODE_AGET_SHORT: { assume_reference(current_state, insn->src(0)); assume_integer(current_state, insn->src(1)); break; } case OPCODE_AGET_WIDE: { assume_reference(current_state, insn->src(0)); assume_integer(current_state, insn->src(1)); break; } case OPCODE_AGET_OBJECT: { assume_reference(current_state, insn->src(0)); assume_integer(current_state, insn->src(1)); break; } case OPCODE_APUT: { assume_scalar(current_state, insn->src(0)); assume_reference(current_state, insn->src(1)); assume_integer(current_state, insn->src(2)); break; } case OPCODE_APUT_BOOLEAN: case OPCODE_APUT_BYTE: case OPCODE_APUT_CHAR: case OPCODE_APUT_SHORT: { assume_integer(current_state, insn->src(0)); assume_reference(current_state, insn->src(1)); assume_integer(current_state, insn->src(2)); break; } case OPCODE_APUT_WIDE: { assume_wide_scalar(current_state, insn->src(0)); assume_reference(current_state, insn->src(1)); assume_integer(current_state, insn->src(2)); break; } case OPCODE_APUT_OBJECT: { assume_reference(current_state, insn->src(0)); assume_reference(current_state, insn->src(1)); assume_integer(current_state, insn->src(2)); break; } case OPCODE_IGET: { assume_reference(current_state, insn->src(0)); const auto f_cls = insn->get_field()->get_class(); assume_assignable(current_state->get_dex_type(insn->src(0)), f_cls); break; } case OPCODE_IGET_BOOLEAN: case OPCODE_IGET_BYTE: case OPCODE_IGET_CHAR: case OPCODE_IGET_SHORT: case OPCODE_IGET_WIDE: { assume_reference(current_state, insn->src(0)); const auto f_cls = insn->get_field()->get_class(); assume_assignable(current_state->get_dex_type(insn->src(0)), f_cls); break; } case OPCODE_IGET_OBJECT: { assume_reference(current_state, insn->src(0)); always_assert(insn->has_field()); const auto f_cls = insn->get_field()->get_class(); assume_assignable(current_state->get_dex_type(insn->src(0)), f_cls); break; } case OPCODE_IPUT: { const DexType* type = insn->get_field()->get_type(); if (type::is_float(type)) { assume_float(current_state, insn->src(0)); } else { assume_integer(current_state, insn->src(0)); } assume_reference(current_state, insn->src(1)); const auto f_cls = insn->get_field()->get_class(); assume_assignable(current_state->get_dex_type(insn->src(1)), f_cls); break; } case OPCODE_IPUT_BOOLEAN: case OPCODE_IPUT_BYTE: case OPCODE_IPUT_CHAR: case OPCODE_IPUT_SHORT: { assume_integer(current_state, insn->src(0)); assume_reference(current_state, insn->src(1)); const auto f_cls = insn->get_field()->get_class(); assume_assignable(current_state->get_dex_type(insn->src(1)), f_cls); break; } case OPCODE_IPUT_WIDE: { assume_wide_scalar(current_state, insn->src(0)); assume_reference(current_state, insn->src(1)); const auto f_cls = insn->get_field()->get_class(); assume_assignable(current_state->get_dex_type(insn->src(1)), f_cls); break; } case OPCODE_IPUT_OBJECT: { assume_reference(current_state, insn->src(0)); assume_reference(current_state, insn->src(1)); always_assert(insn->has_field()); const auto f_type = insn->get_field()->get_type(); assume_assignable(current_state->get_dex_type(insn->src(0)), f_type); const auto f_cls = insn->get_field()->get_class(); assume_assignable(current_state->get_dex_type(insn->src(1)), f_cls); break; } case OPCODE_SGET: { break; } case OPCODE_SGET_BOOLEAN: case OPCODE_SGET_BYTE: case OPCODE_SGET_CHAR: case OPCODE_SGET_SHORT: { break; } case OPCODE_SGET_WIDE: { break; } case OPCODE_SGET_OBJECT: { break; } case OPCODE_SPUT: { const DexType* type = insn->get_field()->get_type(); if (type::is_float(type)) { assume_float(current_state, insn->src(0)); } else { assume_integer(current_state, insn->src(0)); } break; } case OPCODE_SPUT_BOOLEAN: case OPCODE_SPUT_BYTE: case OPCODE_SPUT_CHAR: case OPCODE_SPUT_SHORT: { assume_integer(current_state, insn->src(0)); break; } case OPCODE_SPUT_WIDE: { assume_wide_scalar(current_state, insn->src(0)); break; } case OPCODE_SPUT_OBJECT: { assume_reference(current_state, insn->src(0)); break; } case OPCODE_INVOKE_CUSTOM: case OPCODE_INVOKE_POLYMORPHIC: case OPCODE_INVOKE_VIRTUAL: case OPCODE_INVOKE_SUPER: case OPCODE_INVOKE_DIRECT: case OPCODE_INVOKE_STATIC: case OPCODE_INVOKE_INTERFACE: { DexMethodRef* dex_method = insn->get_method(); const auto* arg_types = dex_method->get_proto()->get_args(); size_t expected_args = (insn->opcode() != OPCODE_INVOKE_STATIC ? 1 : 0) + arg_types->size(); if (insn->srcs_size() != expected_args) { std::ostringstream out; out << SHOW(insn) << ": argument count mismatch; " << "expected " << expected_args << ", " << "but found " << insn->srcs_size() << " instead"; throw TypeCheckingException(out.str()); } size_t src_idx{0}; if (insn->opcode() != OPCODE_INVOKE_STATIC) { // The first argument is a reference to the object instance on which the // method is invoked. auto src = insn->src(src_idx++); assume_reference(current_state, src); assume_assignable(current_state->get_dex_type(src), dex_method->get_class()); } for (DexType* arg_type : *arg_types) { if (type::is_object(arg_type)) { auto src = insn->src(src_idx++); assume_reference(current_state, src); assume_assignable(current_state->get_dex_type(src), arg_type); continue; } if (type::is_integer(arg_type)) { assume_integer(current_state, insn->src(src_idx++)); continue; } if (type::is_long(arg_type)) { assume_long(current_state, insn->src(src_idx++)); continue; } if (type::is_float(arg_type)) { assume_float(current_state, insn->src(src_idx++)); continue; } always_assert(type::is_double(arg_type)); assume_double(current_state, insn->src(src_idx++)); } if (m_validate_access) { auto resolved = resolve_method(dex_method, opcode_to_search(insn), m_dex_method); ::validate_access(m_dex_method, resolved); } if (m_validate_invoke_super && insn->opcode() == OPCODE_INVOKE_SUPER) { validate_invoke_super(dex_method); } break; } case OPCODE_NEG_INT: case OPCODE_NOT_INT: { assume_integer(current_state, insn->src(0)); break; } case OPCODE_NEG_LONG: case OPCODE_NOT_LONG: { assume_long(current_state, insn->src(0)); break; } case OPCODE_NEG_FLOAT: { assume_float(current_state, insn->src(0)); break; } case OPCODE_NEG_DOUBLE: { assume_double(current_state, insn->src(0)); break; } case OPCODE_INT_TO_BYTE: case OPCODE_INT_TO_CHAR: case OPCODE_INT_TO_SHORT: { assume_integer(current_state, insn->src(0)); break; } case OPCODE_LONG_TO_INT: { assume_long(current_state, insn->src(0)); break; } case OPCODE_FLOAT_TO_INT: { assume_float(current_state, insn->src(0)); break; } case OPCODE_DOUBLE_TO_INT: { assume_double(current_state, insn->src(0)); break; } case OPCODE_INT_TO_LONG: { assume_integer(current_state, insn->src(0)); break; } case OPCODE_FLOAT_TO_LONG: { assume_float(current_state, insn->src(0)); break; } case OPCODE_DOUBLE_TO_LONG: { assume_double(current_state, insn->src(0)); break; } case OPCODE_INT_TO_FLOAT: { assume_integer(current_state, insn->src(0)); break; } case OPCODE_LONG_TO_FLOAT: { assume_long(current_state, insn->src(0)); break; } case OPCODE_DOUBLE_TO_FLOAT: { assume_double(current_state, insn->src(0)); break; } case OPCODE_INT_TO_DOUBLE: { assume_integer(current_state, insn->src(0)); break; } case OPCODE_LONG_TO_DOUBLE: { assume_long(current_state, insn->src(0)); break; } case OPCODE_FLOAT_TO_DOUBLE: { assume_float(current_state, insn->src(0)); break; } case OPCODE_ADD_INT: case OPCODE_SUB_INT: case OPCODE_MUL_INT: case OPCODE_AND_INT: case OPCODE_OR_INT: case OPCODE_XOR_INT: case OPCODE_SHL_INT: case OPCODE_SHR_INT: case OPCODE_USHR_INT: { assume_integer(current_state, insn->src(0)); assume_integer(current_state, insn->src(1)); break; } case OPCODE_DIV_INT: case OPCODE_REM_INT: { assume_integer(current_state, insn->src(0)); assume_integer(current_state, insn->src(1)); break; } case OPCODE_ADD_LONG: case OPCODE_SUB_LONG: case OPCODE_MUL_LONG: case OPCODE_AND_LONG: case OPCODE_OR_LONG: case OPCODE_XOR_LONG: { assume_long(current_state, insn->src(0)); assume_long(current_state, insn->src(1)); break; } case OPCODE_DIV_LONG: case OPCODE_REM_LONG: { assume_long(current_state, insn->src(0)); assume_long(current_state, insn->src(1)); break; } case OPCODE_SHL_LONG: case OPCODE_SHR_LONG: case OPCODE_USHR_LONG: { assume_long(current_state, insn->src(0)); assume_integer(current_state, insn->src(1)); break; } case OPCODE_ADD_FLOAT: case OPCODE_SUB_FLOAT: case OPCODE_MUL_FLOAT: case OPCODE_DIV_FLOAT: case OPCODE_REM_FLOAT: { assume_float(current_state, insn->src(0)); assume_float(current_state, insn->src(1)); break; } case OPCODE_ADD_DOUBLE: case OPCODE_SUB_DOUBLE: case OPCODE_MUL_DOUBLE: case OPCODE_DIV_DOUBLE: case OPCODE_REM_DOUBLE: { assume_double(current_state, insn->src(0)); assume_double(current_state, insn->src(1)); break; } case OPCODE_ADD_INT_LIT16: case OPCODE_RSUB_INT: case OPCODE_MUL_INT_LIT16: case OPCODE_AND_INT_LIT16: case OPCODE_OR_INT_LIT16: case OPCODE_XOR_INT_LIT16: case OPCODE_ADD_INT_LIT8: case OPCODE_RSUB_INT_LIT8: case OPCODE_MUL_INT_LIT8: case OPCODE_AND_INT_LIT8: case OPCODE_OR_INT_LIT8: case OPCODE_XOR_INT_LIT8: case OPCODE_SHL_INT_LIT8: case OPCODE_SHR_INT_LIT8: case OPCODE_USHR_INT_LIT8: { assume_integer(current_state, insn->src(0)); break; } case OPCODE_DIV_INT_LIT16: case OPCODE_REM_INT_LIT16: case OPCODE_DIV_INT_LIT8: case OPCODE_REM_INT_LIT8: { assume_integer(current_state, insn->src(0)); break; } case IOPCODE_INIT_CLASS: { break; } } if (insn->has_field() && m_validate_access) { auto search = opcode::is_an_sfield_op(insn->opcode()) ? FieldSearch::Static : FieldSearch::Instance; auto resolved = resolve_field(insn->get_field(), search); ::validate_access(m_dex_method, resolved); } } IRType IRTypeChecker::get_type(IRInstruction* insn, reg_t reg) const { check_completion(); auto& type_envs = m_type_inference->get_type_environments(); auto it = type_envs.find(insn); if (it == type_envs.end()) { // The instruction doesn't belong to this method. We treat this as // unreachable code and return BOTTOM. return BOTTOM; } return it->second.get_type(reg).element(); } boost::optional<const DexType*> IRTypeChecker::get_dex_type(IRInstruction* insn, reg_t reg) const { check_completion(); auto& type_envs = m_type_inference->get_type_environments(); auto it = type_envs.find(insn); if (it == type_envs.end()) { // The instruction doesn't belong to this method. We treat this as // unreachable code and return BOTTOM. return nullptr; } return it->second.get_dex_type(reg); } std::ostream& operator<<(std::ostream& output, const IRTypeChecker& checker) { checker.m_type_inference->print(output); return output; } void IRTypeChecker::check_completion() const { always_assert_log(m_complete, "The type checker did not run on method %s.\n", m_dex_method->get_deobfuscated_name_or_empty().c_str()); }
32.093055
80
0.638358
[ "object" ]
d5511a7543ebd6d595b9fde25fd6c5ff521352ea
53,882
cpp
C++
src/ringct/rctSigs.cpp
netmebtc/XtendCash_1.01
9f416959f70d728a65ae514e29a91f60b835b1a7
[ "BSD-3-Clause" ]
null
null
null
src/ringct/rctSigs.cpp
netmebtc/XtendCash_1.01
9f416959f70d728a65ae514e29a91f60b835b1a7
[ "BSD-3-Clause" ]
null
null
null
src/ringct/rctSigs.cpp
netmebtc/XtendCash_1.01
9f416959f70d728a65ae514e29a91f60b835b1a7
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2016, Monero Research Labs // // Author: Shen Noether <shen.noether@gmx.com> // // 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. #include "misc_log_ex.h" #include "common/perf_timer.h" #include "common/threadpool.h" #include "common/util.h" #include "rctSigs.h" #include "bulletproofs.h" #include "cryptonote_basic/cryptonote_format_utils.h" using namespace crypto; using namespace std; #undef XTEND_DEFAULT_LOG_CATEGORY #define XTEND_DEFAULT_LOG_CATEGORY "ringct" #define CHECK_AND_ASSERT_MES_L1(expr, ret, message) {if(!(expr)) {MCERROR("verify", message); return ret;}} namespace { rct::Bulletproof make_dummy_bulletproof(const std::vector<uint64_t> &outamounts, rct::keyV &C, rct::keyV &masks) { const size_t n_outs = outamounts.size(); const rct::key I = rct::identity(); size_t nrl = 0; while ((1u << nrl) < n_outs) ++nrl; nrl += 6; C.resize(n_outs); masks.resize(n_outs); for (size_t i = 0; i < n_outs; ++i) { masks[i] = I; rct::key sv8, sv; sv = rct::zero(); sv.bytes[0] = outamounts[i] & 255; sv.bytes[1] = (outamounts[i] >> 8) & 255; sv.bytes[2] = (outamounts[i] >> 16) & 255; sv.bytes[3] = (outamounts[i] >> 24) & 255; sv.bytes[4] = (outamounts[i] >> 32) & 255; sv.bytes[5] = (outamounts[i] >> 40) & 255; sv.bytes[6] = (outamounts[i] >> 48) & 255; sv.bytes[7] = (outamounts[i] >> 56) & 255; sc_mul(sv8.bytes, sv.bytes, rct::INV_EIGHT.bytes); rct::addKeys2(C[i], rct::INV_EIGHT, sv8, rct::H); } return rct::Bulletproof{rct::keyV(n_outs, I), I, I, I, I, I, I, rct::keyV(nrl, I), rct::keyV(nrl, I), I, I, I}; } } namespace rct { Bulletproof proveRangeBulletproof(keyV &C, keyV &masks, const std::vector<uint64_t> &amounts, epee::span<const key> sk) { CHECK_AND_ASSERT_THROW_MES(amounts.size() == sk.size(), "Invalid amounts/sk sizes"); masks.resize(amounts.size()); for (size_t i = 0; i < masks.size(); ++i) masks[i] = genCommitmentMask(sk[i]); Bulletproof proof = bulletproof_PROVE(amounts, masks); CHECK_AND_ASSERT_THROW_MES(proof.V.size() == amounts.size(), "V does not have the expected size"); C = proof.V; return proof; } bool verBulletproof(const Bulletproof &proof) { try { return bulletproof_VERIFY(proof); } // we can get deep throws from ge_frombytes_vartime if input isn't valid catch (...) { return false; } } bool verBulletproof(const std::vector<const Bulletproof*> &proofs) { try { return bulletproof_VERIFY(proofs); } // we can get deep throws from ge_frombytes_vartime if input isn't valid catch (...) { return false; } } //Borromean (c.f. gmax/andytoshi's paper) boroSig genBorromean(const key64 x, const key64 P1, const key64 P2, const bits indices) { key64 L[2], alpha; key c; int naught = 0, prime = 0, ii = 0, jj=0; boroSig bb; for (ii = 0 ; ii < 64 ; ii++) { naught = indices[ii]; prime = (indices[ii] + 1) % 2; skGen(alpha[ii]); scalarmultBase(L[naught][ii], alpha[ii]); if (naught == 0) { skGen(bb.s1[ii]); c = hash_to_scalar(L[naught][ii]); addKeys2(L[prime][ii], bb.s1[ii], c, P2[ii]); } } bb.ee = hash_to_scalar(L[1]); //or L[1].. key LL, cc; for (jj = 0 ; jj < 64 ; jj++) { if (!indices[jj]) { sc_mulsub(bb.s0[jj].bytes, x[jj].bytes, bb.ee.bytes, alpha[jj].bytes); } else { skGen(bb.s0[jj]); addKeys2(LL, bb.s0[jj], bb.ee, P1[jj]); //different L0 cc = hash_to_scalar(LL); sc_mulsub(bb.s1[jj].bytes, x[jj].bytes, cc.bytes, alpha[jj].bytes); } } return bb; } //see above. bool verifyBorromean(const boroSig &bb, const ge_p3 P1[64], const ge_p3 P2[64]) { key64 Lv1; key chash, LL; int ii = 0; ge_p2 p2; for (ii = 0 ; ii < 64 ; ii++) { // equivalent of: addKeys2(LL, bb.s0[ii], bb.ee, P1[ii]); ge_double_scalarmult_base_vartime(&p2, bb.ee.bytes, &P1[ii], bb.s0[ii].bytes); ge_tobytes(LL.bytes, &p2); chash = hash_to_scalar(LL); // equivalent of: addKeys2(Lv1[ii], bb.s1[ii], chash, P2[ii]); ge_double_scalarmult_base_vartime(&p2, chash.bytes, &P2[ii], bb.s1[ii].bytes); ge_tobytes(Lv1[ii].bytes, &p2); } key eeComputed = hash_to_scalar(Lv1); //hash function fine return equalKeys(eeComputed, bb.ee); } bool verifyBorromean(const boroSig &bb, const key64 P1, const key64 P2) { ge_p3 P1_p3[64], P2_p3[64]; for (size_t i = 0 ; i < 64 ; ++i) { CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&P1_p3[i], P1[i].bytes) == 0, false, "point conv failed"); CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&P2_p3[i], P2[i].bytes) == 0, false, "point conv failed"); } return verifyBorromean(bb, P1_p3, P2_p3); } //Multilayered Spontaneous Anonymous Group Signatures (MLSAG signatures) //This is a just slghtly more efficient version than the ones described below //(will be explained in more detail in Ring Multisig paper //These are aka MG signatutes in earlier drafts of the ring ct paper // c.f. https://eprint.iacr.org/2015/1098 section 2. // Gen creates a signature which proves that for some column in the keymatrix "pk" // the signer knows a secret key for each row in that column // Ver verifies that the MG sig was created correctly mgSig MLSAG_Gen(const key &message, const keyM & pk, const keyV & xx, const multisig_kLRki *kLRki, key *mscout, const unsigned int index, size_t dsRows, hw::device &hwdev) { mgSig rv; size_t cols = pk.size(); CHECK_AND_ASSERT_THROW_MES(cols >= 2, "Error! What is c if cols = 1!"); CHECK_AND_ASSERT_THROW_MES(index < cols, "Index out of range"); size_t rows = pk[0].size(); CHECK_AND_ASSERT_THROW_MES(rows >= 1, "Empty pk"); for (size_t i = 1; i < cols; ++i) { CHECK_AND_ASSERT_THROW_MES(pk[i].size() == rows, "pk is not rectangular"); } CHECK_AND_ASSERT_THROW_MES(xx.size() == rows, "Bad xx size"); CHECK_AND_ASSERT_THROW_MES(dsRows <= rows, "Bad dsRows size"); CHECK_AND_ASSERT_THROW_MES((kLRki && mscout) || (!kLRki && !mscout), "Only one of kLRki/mscout is present"); CHECK_AND_ASSERT_THROW_MES(!kLRki || dsRows == 1, "Multisig requires exactly 1 dsRows"); size_t i = 0, j = 0, ii = 0; key c, c_old, L, R, Hi; sc_0(c_old.bytes); vector<geDsmp> Ip(dsRows); rv.II = keyV(dsRows); keyV alpha(rows); keyV aG(rows); rv.ss = keyM(cols, aG); keyV aHP(dsRows); keyV toHash(1 + 3 * dsRows + 2 * (rows - dsRows)); toHash[0] = message; DP("here1"); for (i = 0; i < dsRows; i++) { toHash[3 * i + 1] = pk[index][i]; if (kLRki) { // multisig alpha[i] = kLRki->k; toHash[3 * i + 2] = kLRki->L; toHash[3 * i + 3] = kLRki->R; rv.II[i] = kLRki->ki; } else { Hi = hashToPoint(pk[index][i]); hwdev.mlsag_prepare(Hi, xx[i], alpha[i] , aG[i] , aHP[i] , rv.II[i]); toHash[3 * i + 2] = aG[i]; toHash[3 * i + 3] = aHP[i]; } precomp(Ip[i].k, rv.II[i]); } size_t ndsRows = 3 * dsRows; //non Double Spendable Rows (see identity chains paper) for (i = dsRows, ii = 0 ; i < rows ; i++, ii++) { skpkGen(alpha[i], aG[i]); //need to save alphas for later.. toHash[ndsRows + 2 * ii + 1] = pk[index][i]; toHash[ndsRows + 2 * ii + 2] = aG[i]; } hwdev.mlsag_hash(toHash, c_old); i = (index + 1) % cols; if (i == 0) { copy(rv.cc, c_old); } while (i != index) { rv.ss[i] = skvGen(rows); sc_0(c.bytes); for (j = 0; j < dsRows; j++) { addKeys2(L, rv.ss[i][j], c_old, pk[i][j]); hashToPoint(Hi, pk[i][j]); addKeys3(R, rv.ss[i][j], Hi, c_old, Ip[j].k); toHash[3 * j + 1] = pk[i][j]; toHash[3 * j + 2] = L; toHash[3 * j + 3] = R; } for (j = dsRows, ii = 0; j < rows; j++, ii++) { addKeys2(L, rv.ss[i][j], c_old, pk[i][j]); toHash[ndsRows + 2 * ii + 1] = pk[i][j]; toHash[ndsRows + 2 * ii + 2] = L; } hwdev.mlsag_hash(toHash, c); copy(c_old, c); i = (i + 1) % cols; if (i == 0) { copy(rv.cc, c_old); } } hwdev.mlsag_sign(c, xx, alpha, rows, dsRows, rv.ss[index]); if (mscout) *mscout = c; return rv; } //Multilayered Spontaneous Anonymous Group Signatures (MLSAG signatures) //This is a just slghtly more efficient version than the ones described below //(will be explained in more detail in Ring Multisig paper //These are aka MG signatutes in earlier drafts of the ring ct paper // c.f. https://eprint.iacr.org/2015/1098 section 2. // Gen creates a signature which proves that for some column in the keymatrix "pk" // the signer knows a secret key for each row in that column // Ver verifies that the MG sig was created correctly bool MLSAG_Ver(const key &message, const keyM & pk, const mgSig & rv, size_t dsRows) { size_t cols = pk.size(); CHECK_AND_ASSERT_MES(cols >= 2, false, "Error! What is c if cols = 1!"); size_t rows = pk[0].size(); CHECK_AND_ASSERT_MES(rows >= 1, false, "Empty pk"); for (size_t i = 1; i < cols; ++i) { CHECK_AND_ASSERT_MES(pk[i].size() == rows, false, "pk is not rectangular"); } CHECK_AND_ASSERT_MES(rv.II.size() == dsRows, false, "Bad II size"); CHECK_AND_ASSERT_MES(rv.ss.size() == cols, false, "Bad rv.ss size"); for (size_t i = 0; i < cols; ++i) { CHECK_AND_ASSERT_MES(rv.ss[i].size() == rows, false, "rv.ss is not rectangular"); } CHECK_AND_ASSERT_MES(dsRows <= rows, false, "Bad dsRows value"); for (size_t i = 0; i < rv.ss.size(); ++i) for (size_t j = 0; j < rv.ss[i].size(); ++j) CHECK_AND_ASSERT_MES(sc_check(rv.ss[i][j].bytes) == 0, false, "Bad ss slot"); CHECK_AND_ASSERT_MES(sc_check(rv.cc.bytes) == 0, false, "Bad cc"); size_t i = 0, j = 0, ii = 0; key c, L, R, Hi; key c_old = copy(rv.cc); vector<geDsmp> Ip(dsRows); for (i = 0 ; i < dsRows ; i++) { precomp(Ip[i].k, rv.II[i]); } size_t ndsRows = 3 * dsRows; //non Double Spendable Rows (see identity chains paper keyV toHash(1 + 3 * dsRows + 2 * (rows - dsRows)); toHash[0] = message; i = 0; while (i < cols) { sc_0(c.bytes); for (j = 0; j < dsRows; j++) { addKeys2(L, rv.ss[i][j], c_old, pk[i][j]); hashToPoint(Hi, pk[i][j]); CHECK_AND_ASSERT_MES(!(Hi == rct::identity()), false, "Data hashed to point at infinity"); addKeys3(R, rv.ss[i][j], Hi, c_old, Ip[j].k); toHash[3 * j + 1] = pk[i][j]; toHash[3 * j + 2] = L; toHash[3 * j + 3] = R; } for (j = dsRows, ii = 0 ; j < rows ; j++, ii++) { addKeys2(L, rv.ss[i][j], c_old, pk[i][j]); toHash[ndsRows + 2 * ii + 1] = pk[i][j]; toHash[ndsRows + 2 * ii + 2] = L; } c = hash_to_scalar(toHash); copy(c_old, c); i = (i + 1); } sc_sub(c.bytes, c_old.bytes, rv.cc.bytes); return sc_isnonzero(c.bytes) == 0; } //proveRange and verRange //proveRange gives C, and mask such that \sumCi = C // c.f. https://eprint.iacr.org/2015/1098 section 5.1 // and Ci is a commitment to either 0 or 2^i, i=0,...,63 // thus this proves that "amount" is in [0, 2^64] // mask is a such that C = aG + bH, and b = amount //verRange verifies that \sum Ci = C and that each Ci is a commitment to 0 or 2^i rangeSig proveRange(key & C, key & mask, const xmr_amount & amount) { sc_0(mask.bytes); identity(C); bits b; d2b(b, amount); rangeSig sig; key64 ai; key64 CiH; int i = 0; for (i = 0; i < ATOMS; i++) { skGen(ai[i]); if (b[i] == 0) { scalarmultBase(sig.Ci[i], ai[i]); } if (b[i] == 1) { addKeys1(sig.Ci[i], ai[i], H2[i]); } subKeys(CiH[i], sig.Ci[i], H2[i]); sc_add(mask.bytes, mask.bytes, ai[i].bytes); addKeys(C, C, sig.Ci[i]); } sig.asig = genBorromean(ai, sig.Ci, CiH, b); return sig; } //proveRange and verRange //proveRange gives C, and mask such that \sumCi = C // c.f. https://eprint.iacr.org/2015/1098 section 5.1 // and Ci is a commitment to either 0 or 2^i, i=0,...,63 // thus this proves that "amount" is in [0, 2^64] // mask is a such that C = aG + bH, and b = amount //verRange verifies that \sum Ci = C and that each Ci is a commitment to 0 or 2^i bool verRange(const key & C, const rangeSig & as) { try { PERF_TIMER(verRange); ge_p3 CiH[64], asCi[64]; int i = 0; ge_p3 Ctmp_p3 = ge_p3_identity; for (i = 0; i < 64; i++) { // faster equivalent of: // subKeys(CiH[i], as.Ci[i], H2[i]); // addKeys(Ctmp, Ctmp, as.Ci[i]); ge_cached cached; ge_p3 p3; ge_p1p1 p1; CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&p3, H2[i].bytes) == 0, false, "point conv failed"); ge_p3_to_cached(&cached, &p3); CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&asCi[i], as.Ci[i].bytes) == 0, false, "point conv failed"); ge_sub(&p1, &asCi[i], &cached); ge_p3_to_cached(&cached, &asCi[i]); ge_p1p1_to_p3(&CiH[i], &p1); ge_add(&p1, &Ctmp_p3, &cached); ge_p1p1_to_p3(&Ctmp_p3, &p1); } key Ctmp; ge_p3_tobytes(Ctmp.bytes, &Ctmp_p3); if (!equalKeys(C, Ctmp)) return false; if (!verifyBorromean(as.asig, asCi, CiH)) return false; return true; } // we can get deep throws from ge_frombytes_vartime if input isn't valid catch (...) { return false; } } key get_pre_mlsag_hash(const rctSig &rv, hw::device &hwdev) { keyV hashes; hashes.reserve(3); hashes.push_back(rv.message); crypto::hash h; std::stringstream ss; binary_archive<true> ba(ss); CHECK_AND_ASSERT_THROW_MES(!rv.mixRing.empty(), "Empty mixRing"); const size_t inputs = is_rct_simple(rv.type) ? rv.mixRing.size() : rv.mixRing[0].size(); const size_t outputs = rv.ecdhInfo.size(); key prehash; CHECK_AND_ASSERT_THROW_MES(const_cast<rctSig&>(rv).serialize_rctsig_base(ba, inputs, outputs), "Failed to serialize rctSigBase"); cryptonote::get_blob_hash(ss.str(), h); hashes.push_back(hash2rct(h)); keyV kv; if (rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2) { kv.reserve((6*2+9) * rv.p.bulletproofs.size()); for (const auto &p: rv.p.bulletproofs) { // V are not hashed as they're expanded from outPk.mask // (and thus hashed as part of rctSigBase above) kv.push_back(p.A); kv.push_back(p.S); kv.push_back(p.T1); kv.push_back(p.T2); kv.push_back(p.taux); kv.push_back(p.mu); for (size_t n = 0; n < p.L.size(); ++n) kv.push_back(p.L[n]); for (size_t n = 0; n < p.R.size(); ++n) kv.push_back(p.R[n]); kv.push_back(p.a); kv.push_back(p.b); kv.push_back(p.t); } } else { kv.reserve((64*3+1) * rv.p.rangeSigs.size()); for (const auto &r: rv.p.rangeSigs) { for (size_t n = 0; n < 64; ++n) kv.push_back(r.asig.s0[n]); for (size_t n = 0; n < 64; ++n) kv.push_back(r.asig.s1[n]); kv.push_back(r.asig.ee); for (size_t n = 0; n < 64; ++n) kv.push_back(r.Ci[n]); } } hashes.push_back(cn_fast_hash(kv)); hwdev.mlsag_prehash(ss.str(), inputs, outputs, hashes, rv.outPk, prehash); return prehash; } //Ring-ct MG sigs //Prove: // c.f. https://eprint.iacr.org/2015/1098 section 4. definition 10. // This does the MG sig on the "dest" part of the given key matrix, and // the last row is the sum of input commitments from that column - sum output commitments // this shows that sum inputs = sum outputs //Ver: // verifies the above sig is created corretly mgSig proveRctMG(const key &message, const ctkeyM & pubs, const ctkeyV & inSk, const ctkeyV &outSk, const ctkeyV & outPk, const multisig_kLRki *kLRki, key *mscout, unsigned int index, const key &txnFeeKey, hw::device &hwdev) { mgSig mg; //setup vars size_t cols = pubs.size(); CHECK_AND_ASSERT_THROW_MES(cols >= 1, "Empty pubs"); size_t rows = pubs[0].size(); CHECK_AND_ASSERT_THROW_MES(rows >= 1, "Empty pubs"); for (size_t i = 1; i < cols; ++i) { CHECK_AND_ASSERT_THROW_MES(pubs[i].size() == rows, "pubs is not rectangular"); } CHECK_AND_ASSERT_THROW_MES(inSk.size() == rows, "Bad inSk size"); CHECK_AND_ASSERT_THROW_MES(outSk.size() == outPk.size(), "Bad outSk/outPk size"); CHECK_AND_ASSERT_THROW_MES((kLRki && mscout) || (!kLRki && !mscout), "Only one of kLRki/mscout is present"); keyV sk(rows + 1); keyV tmp(rows + 1); size_t i = 0, j = 0; for (i = 0; i < rows + 1; i++) { sc_0(sk[i].bytes); identity(tmp[i]); } keyM M(cols, tmp); //create the matrix to mg sig for (i = 0; i < cols; i++) { M[i][rows] = identity(); for (j = 0; j < rows; j++) { M[i][j] = pubs[i][j].dest; addKeys(M[i][rows], M[i][rows], pubs[i][j].mask); //add input commitments in last row } } sc_0(sk[rows].bytes); for (j = 0; j < rows; j++) { sk[j] = copy(inSk[j].dest); sc_add(sk[rows].bytes, sk[rows].bytes, inSk[j].mask.bytes); //add masks in last row } for (i = 0; i < cols; i++) { for (size_t j = 0; j < outPk.size(); j++) { subKeys(M[i][rows], M[i][rows], outPk[j].mask); //subtract output Ci's in last row } //subtract txn fee output in last row subKeys(M[i][rows], M[i][rows], txnFeeKey); } for (size_t j = 0; j < outPk.size(); j++) { sc_sub(sk[rows].bytes, sk[rows].bytes, outSk[j].mask.bytes); //subtract output masks in last row.. } mgSig result = MLSAG_Gen(message, M, sk, kLRki, mscout, index, rows, hwdev); memwipe(sk.data(), sk.size() * sizeof(key)); return result; } //Ring-ct MG sigs Simple // Simple version for when we assume only // post rct inputs // here pubs is a vector of (P, C) length mixin // inSk is x, a_in corresponding to signing index // a_out, Cout is for the output commitment // index is the signing index.. mgSig proveRctMGSimple(const key &message, const ctkeyV & pubs, const ctkey & inSk, const key &a , const key &Cout, const multisig_kLRki *kLRki, key *mscout, unsigned int index, hw::device &hwdev) { mgSig mg; //setup vars size_t rows = 1; size_t cols = pubs.size(); CHECK_AND_ASSERT_THROW_MES(cols >= 1, "Empty pubs"); CHECK_AND_ASSERT_THROW_MES((kLRki && mscout) || (!kLRki && !mscout), "Only one of kLRki/mscout is present"); keyV tmp(rows + 1); keyV sk(rows + 1); size_t i; keyM M(cols, tmp); sk[0] = copy(inSk.dest); sc_sub(sk[1].bytes, inSk.mask.bytes, a.bytes); for (i = 0; i < cols; i++) { M[i][0] = pubs[i].dest; subKeys(M[i][1], pubs[i].mask, Cout); } mgSig result = MLSAG_Gen(message, M, sk, kLRki, mscout, index, rows, hwdev); memwipe(&sk[0], sizeof(key)); return result; } //Ring-ct MG sigs //Prove: // c.f. https://eprint.iacr.org/2015/1098 section 4. definition 10. // This does the MG sig on the "dest" part of the given key matrix, and // the last row is the sum of input commitments from that column - sum output commitments // this shows that sum inputs = sum outputs //Ver: // verifies the above sig is created corretly bool verRctMG(const mgSig &mg, const ctkeyM & pubs, const ctkeyV & outPk, const key &txnFeeKey, const key &message) { PERF_TIMER(verRctMG); //setup vars size_t cols = pubs.size(); CHECK_AND_ASSERT_MES(cols >= 1, false, "Empty pubs"); size_t rows = pubs[0].size(); CHECK_AND_ASSERT_MES(rows >= 1, false, "Empty pubs"); for (size_t i = 1; i < cols; ++i) { CHECK_AND_ASSERT_MES(pubs[i].size() == rows, false, "pubs is not rectangular"); } keyV tmp(rows + 1); size_t i = 0, j = 0; for (i = 0; i < rows + 1; i++) { identity(tmp[i]); } keyM M(cols, tmp); //create the matrix to mg sig for (j = 0; j < rows; j++) { for (i = 0; i < cols; i++) { M[i][j] = pubs[i][j].dest; addKeys(M[i][rows], M[i][rows], pubs[i][j].mask); //add Ci in last row } } for (i = 0; i < cols; i++) { for (j = 0; j < outPk.size(); j++) { subKeys(M[i][rows], M[i][rows], outPk[j].mask); //subtract output Ci's in last row } //subtract txn fee output in last row subKeys(M[i][rows], M[i][rows], txnFeeKey); } return MLSAG_Ver(message, M, mg, rows); } //Ring-ct Simple MG sigs //Ver: //This does a simplified version, assuming only post Rct //inputs bool verRctMGSimple(const key &message, const mgSig &mg, const ctkeyV & pubs, const key & C) { try { PERF_TIMER(verRctMGSimple); //setup vars size_t rows = 1; size_t cols = pubs.size(); CHECK_AND_ASSERT_MES(cols >= 1, false, "Empty pubs"); keyV tmp(rows + 1); size_t i; keyM M(cols, tmp); ge_p3 Cp3; CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&Cp3, C.bytes) == 0, false, "point conv failed"); ge_cached Ccached; ge_p3_to_cached(&Ccached, &Cp3); ge_p1p1 p1; //create the matrix to mg sig for (i = 0; i < cols; i++) { M[i][0] = pubs[i].dest; ge_p3 p3; CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&p3, pubs[i].mask.bytes) == 0, false, "point conv failed"); ge_sub(&p1, &p3, &Ccached); ge_p1p1_to_p3(&p3, &p1); ge_p3_tobytes(M[i][1].bytes, &p3); } //DP(C); return MLSAG_Ver(message, M, mg, rows); } catch (...) { return false; } } //These functions get keys from blockchain //replace these when connecting blockchain //getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with //populateFromBlockchain creates a keymatrix with "mixin" columns and one of the columns is inPk // the return value are the key matrix, and the index where inPk was put (random). void getKeyFromBlockchain(ctkey & a, size_t reference_index) { a.mask = pkGen(); a.dest = pkGen(); } //These functions get keys from blockchain //replace these when connecting blockchain //getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with //populateFromBlockchain creates a keymatrix with "mixin" + 1 columns and one of the columns is inPk // the return value are the key matrix, and the index where inPk was put (random). tuple<ctkeyM, xmr_amount> populateFromBlockchain(ctkeyV inPk, int mixin) { int rows = inPk.size(); ctkeyM rv(mixin + 1, inPk); int index = randXmrAmount(mixin); int i = 0, j = 0; for (i = 0; i <= mixin; i++) { if (i != index) { for (j = 0; j < rows; j++) { getKeyFromBlockchain(rv[i][j], (size_t)randXmrAmount); } } } return make_tuple(rv, index); } //These functions get keys from blockchain //replace these when connecting blockchain //getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with //populateFromBlockchain creates a keymatrix with "mixin" columns and one of the columns is inPk // the return value are the key matrix, and the index where inPk was put (random). xmr_amount populateFromBlockchainSimple(ctkeyV & mixRing, const ctkey & inPk, int mixin) { int index = randXmrAmount(mixin); int i = 0; for (i = 0; i <= mixin; i++) { if (i != index) { getKeyFromBlockchain(mixRing[i], (size_t)randXmrAmount(1000)); } else { mixRing[i] = inPk; } } return index; } //RingCT protocol //genRct: // creates an rctSig with all data necessary to verify the rangeProofs and that the signer owns one of the // columns that are claimed as inputs, and that the sum of inputs = sum of outputs. // Also contains masked "amount" and "mask" so the receiver can see how much they received //verRct: // verifies that all signatures (rangeProogs, MG sig, sum inputs = outputs) are correct //decodeRct: (c.f. https://eprint.iacr.org/2015/1098 section 5.1.1) // uses the attached ecdh info to find the amounts represented by each output commitment // must know the destination private key to find the correct amount, else will return a random number // Note: For txn fees, the last index in the amounts vector should contain that // Thus the amounts vector will be "one" longer than the destinations vectort rctSig genRct(const key &message, const ctkeyV & inSk, const keyV & destinations, const vector<xmr_amount> & amounts, const ctkeyM &mixRing, const keyV &amount_keys, const multisig_kLRki *kLRki, multisig_out *msout, unsigned int index, ctkeyV &outSk, const RCTConfig &rct_config, hw::device &hwdev) { CHECK_AND_ASSERT_THROW_MES(amounts.size() == destinations.size() || amounts.size() == destinations.size() + 1, "Different number of amounts/destinations"); CHECK_AND_ASSERT_THROW_MES(amount_keys.size() == destinations.size(), "Different number of amount_keys/destinations"); CHECK_AND_ASSERT_THROW_MES(index < mixRing.size(), "Bad index into mixRing"); for (size_t n = 0; n < mixRing.size(); ++n) { CHECK_AND_ASSERT_THROW_MES(mixRing[n].size() == inSk.size(), "Bad mixRing size"); } CHECK_AND_ASSERT_THROW_MES((kLRki && msout) || (!kLRki && !msout), "Only one of kLRki/msout is present"); rctSig rv; rv.type = RCTTypeFull; rv.message = message; rv.outPk.resize(destinations.size()); rv.p.rangeSigs.resize(destinations.size()); rv.ecdhInfo.resize(destinations.size()); size_t i = 0; keyV masks(destinations.size()); //sk mask.. outSk.resize(destinations.size()); for (i = 0; i < destinations.size(); i++) { //add destination to sig rv.outPk[i].dest = copy(destinations[i]); //compute range proof rv.p.rangeSigs[i] = proveRange(rv.outPk[i].mask, outSk[i].mask, amounts[i]); #ifdef DBG CHECK_AND_ASSERT_THROW_MES(verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]), "verRange failed on newly created proof"); #endif //mask amount and mask rv.ecdhInfo[i].mask = copy(outSk[i].mask); rv.ecdhInfo[i].amount = d2h(amounts[i]); hwdev.ecdhEncode(rv.ecdhInfo[i], amount_keys[i], rv.type == RCTTypeBulletproof2); } //set txn fee if (amounts.size() > destinations.size()) { rv.txnFee = amounts[destinations.size()]; } else { rv.txnFee = 0; } key txnFeeKey = scalarmultH(d2h(rv.txnFee)); rv.mixRing = mixRing; if (msout) msout->c.resize(1); rv.p.MGs.push_back(proveRctMG(get_pre_mlsag_hash(rv, hwdev), rv.mixRing, inSk, outSk, rv.outPk, kLRki, msout ? &msout->c[0] : NULL, index, txnFeeKey,hwdev)); return rv; } rctSig genRct(const key &message, const ctkeyV & inSk, const ctkeyV & inPk, const keyV & destinations, const vector<xmr_amount> & amounts, const keyV &amount_keys, const multisig_kLRki *kLRki, multisig_out *msout, const int mixin, const RCTConfig &rct_config, hw::device &hwdev) { unsigned int index; ctkeyM mixRing; ctkeyV outSk; tie(mixRing, index) = populateFromBlockchain(inPk, mixin); return genRct(message, inSk, destinations, amounts, mixRing, amount_keys, kLRki, msout, index, outSk, rct_config, hwdev); } //RCT simple //for post-rct only rctSig genRctSimple(const key &message, const ctkeyV & inSk, const keyV & destinations, const vector<xmr_amount> &inamounts, const vector<xmr_amount> &outamounts, xmr_amount txnFee, const ctkeyM & mixRing, const keyV &amount_keys, const std::vector<multisig_kLRki> *kLRki, multisig_out *msout, const std::vector<unsigned int> & index, ctkeyV &outSk, const RCTConfig &rct_config, hw::device &hwdev) { const bool bulletproof = rct_config.range_proof_type != RangeProofBorromean; CHECK_AND_ASSERT_THROW_MES(inamounts.size() > 0, "Empty inamounts"); CHECK_AND_ASSERT_THROW_MES(inamounts.size() == inSk.size(), "Different number of inamounts/inSk"); CHECK_AND_ASSERT_THROW_MES(outamounts.size() == destinations.size(), "Different number of amounts/destinations"); CHECK_AND_ASSERT_THROW_MES(amount_keys.size() == destinations.size(), "Different number of amount_keys/destinations"); CHECK_AND_ASSERT_THROW_MES(index.size() == inSk.size(), "Different number of index/inSk"); CHECK_AND_ASSERT_THROW_MES(mixRing.size() == inSk.size(), "Different number of mixRing/inSk"); for (size_t n = 0; n < mixRing.size(); ++n) { CHECK_AND_ASSERT_THROW_MES(index[n] < mixRing[n].size(), "Bad index into mixRing"); } CHECK_AND_ASSERT_THROW_MES((kLRki && msout) || (!kLRki && !msout), "Only one of kLRki/msout is present"); if (kLRki && msout) { CHECK_AND_ASSERT_THROW_MES(kLRki->size() == inamounts.size(), "Mismatched kLRki/inamounts sizes"); } rctSig rv; rv.type = bulletproof ? (rct_config.bp_version == 0 || rct_config.bp_version >= 2 ? RCTTypeBulletproof2 : RCTTypeBulletproof) : RCTTypeSimple; rv.message = message; rv.outPk.resize(destinations.size()); if (!bulletproof) rv.p.rangeSigs.resize(destinations.size()); rv.ecdhInfo.resize(destinations.size()); size_t i; keyV masks(destinations.size()); //sk mask.. outSk.resize(destinations.size()); for (i = 0; i < destinations.size(); i++) { //add destination to sig rv.outPk[i].dest = copy(destinations[i]); //compute range proof if (!bulletproof) rv.p.rangeSigs[i] = proveRange(rv.outPk[i].mask, outSk[i].mask, outamounts[i]); #ifdef DBG if (!bulletproof) CHECK_AND_ASSERT_THROW_MES(verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]), "verRange failed on newly created proof"); #endif } rv.p.bulletproofs.clear(); if (bulletproof) { std::vector<uint64_t> proof_amounts; size_t n_amounts = outamounts.size(); size_t amounts_proved = 0; if (rct_config.range_proof_type == RangeProofPaddedBulletproof) { rct::keyV C, masks; if (hwdev.get_mode() == hw::device::TRANSACTION_CREATE_FAKE) { // use a fake bulletproof for speed rv.p.bulletproofs.push_back(make_dummy_bulletproof(outamounts, C, masks)); } else { const epee::span<const key> keys{&amount_keys[0], amount_keys.size()}; rv.p.bulletproofs.push_back(proveRangeBulletproof(C, masks, outamounts, keys)); #ifdef DBG CHECK_AND_ASSERT_THROW_MES(verBulletproof(rv.p.bulletproofs.back()), "verBulletproof failed on newly created proof"); #endif } for (i = 0; i < outamounts.size(); ++i) { rv.outPk[i].mask = rct::scalarmult8(C[i]); outSk[i].mask = masks[i]; } } else while (amounts_proved < n_amounts) { size_t batch_size = 1; if (rct_config.range_proof_type == RangeProofMultiOutputBulletproof) while (batch_size * 2 + amounts_proved <= n_amounts && batch_size * 2 <= BULLETPROOF_MAX_OUTPUTS) batch_size *= 2; rct::keyV C, masks; std::vector<uint64_t> batch_amounts(batch_size); for (i = 0; i < batch_size; ++i) batch_amounts[i] = outamounts[i + amounts_proved]; if (hwdev.get_mode() == hw::device::TRANSACTION_CREATE_FAKE) { // use a fake bulletproof for speed rv.p.bulletproofs.push_back(make_dummy_bulletproof(batch_amounts, C, masks)); } else { const epee::span<const key> keys{&amount_keys[amounts_proved], batch_size}; rv.p.bulletproofs.push_back(proveRangeBulletproof(C, masks, batch_amounts, keys)); #ifdef DBG CHECK_AND_ASSERT_THROW_MES(verBulletproof(rv.p.bulletproofs.back()), "verBulletproof failed on newly created proof"); #endif } for (i = 0; i < batch_size; ++i) { rv.outPk[i + amounts_proved].mask = rct::scalarmult8(C[i]); outSk[i + amounts_proved].mask = masks[i]; } amounts_proved += batch_size; } } key sumout = zero(); for (i = 0; i < outSk.size(); ++i) { sc_add(sumout.bytes, outSk[i].mask.bytes, sumout.bytes); //mask amount and mask rv.ecdhInfo[i].mask = copy(outSk[i].mask); rv.ecdhInfo[i].amount = d2h(outamounts[i]); hwdev.ecdhEncode(rv.ecdhInfo[i], amount_keys[i], rv.type == RCTTypeBulletproof2); } //set txn fee rv.txnFee = txnFee; // TODO: unused ?? // key txnFeeKey = scalarmultH(d2h(rv.txnFee)); rv.mixRing = mixRing; keyV &pseudoOuts = bulletproof ? rv.p.pseudoOuts : rv.pseudoOuts; pseudoOuts.resize(inamounts.size()); rv.p.MGs.resize(inamounts.size()); key sumpouts = zero(); //sum pseudoOut masks keyV a(inamounts.size()); for (i = 0 ; i < inamounts.size() - 1; i++) { skGen(a[i]); sc_add(sumpouts.bytes, a[i].bytes, sumpouts.bytes); genC(pseudoOuts[i], a[i], inamounts[i]); } sc_sub(a[i].bytes, sumout.bytes, sumpouts.bytes); genC(pseudoOuts[i], a[i], inamounts[i]); DP(pseudoOuts[i]); key full_message = get_pre_mlsag_hash(rv,hwdev); if (msout) msout->c.resize(inamounts.size()); for (i = 0 ; i < inamounts.size(); i++) { rv.p.MGs[i] = proveRctMGSimple(full_message, rv.mixRing[i], inSk[i], a[i], pseudoOuts[i], kLRki ? &(*kLRki)[i]: NULL, msout ? &msout->c[i] : NULL, index[i], hwdev); } return rv; } rctSig genRctSimple(const key &message, const ctkeyV & inSk, const ctkeyV & inPk, const keyV & destinations, const vector<xmr_amount> &inamounts, const vector<xmr_amount> &outamounts, const keyV &amount_keys, const std::vector<multisig_kLRki> *kLRki, multisig_out *msout, xmr_amount txnFee, unsigned int mixin, const RCTConfig &rct_config, hw::device &hwdev) { std::vector<unsigned int> index; index.resize(inPk.size()); ctkeyM mixRing; ctkeyV outSk; mixRing.resize(inPk.size()); for (size_t i = 0; i < inPk.size(); ++i) { mixRing[i].resize(mixin+1); index[i] = populateFromBlockchainSimple(mixRing[i], inPk[i], mixin); } return genRctSimple(message, inSk, destinations, inamounts, outamounts, txnFee, mixRing, amount_keys, kLRki, msout, index, outSk, rct_config, hwdev); } //RingCT protocol //genRct: // creates an rctSig with all data necessary to verify the rangeProofs and that the signer owns one of the // columns that are claimed as inputs, and that the sum of inputs = sum of outputs. // Also contains masked "amount" and "mask" so the receiver can see how much they received //verRct: // verifies that all signatures (rangeProogs, MG sig, sum inputs = outputs) are correct //decodeRct: (c.f. https://eprint.iacr.org/2015/1098 section 5.1.1) // uses the attached ecdh info to find the amounts represented by each output commitment // must know the destination private key to find the correct amount, else will return a random number bool verRct(const rctSig & rv, bool semantics) { PERF_TIMER(verRct); CHECK_AND_ASSERT_MES(rv.type == RCTTypeFull, false, "verRct called on non-full rctSig"); if (semantics) { CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.p.rangeSigs.size(), false, "Mismatched sizes of outPk and rv.p.rangeSigs"); CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.ecdhInfo.size(), false, "Mismatched sizes of outPk and rv.ecdhInfo"); CHECK_AND_ASSERT_MES(rv.p.MGs.size() == 1, false, "full rctSig has not one MG"); } else { // semantics check is early, we don't have the MGs resolved yet } // some rct ops can throw try { if (semantics) { tools::threadpool& tpool = tools::threadpool::getInstance(); tools::threadpool::waiter waiter; std::deque<bool> results(rv.outPk.size(), false); DP("range proofs verified?"); for (size_t i = 0; i < rv.outPk.size(); i++) tpool.submit(&waiter, [&, i] { results[i] = verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]); }); waiter.wait(&tpool); for (size_t i = 0; i < results.size(); ++i) { if (!results[i]) { LOG_PRINT_L1("Range proof verified failed for proof " << i); return false; } } } if (!semantics) { //compute txn fee key txnFeeKey = scalarmultH(d2h(rv.txnFee)); bool mgVerd = verRctMG(rv.p.MGs[0], rv.mixRing, rv.outPk, txnFeeKey, get_pre_mlsag_hash(rv, hw::get_device("default"))); DP("mg sig verified?"); DP(mgVerd); if (!mgVerd) { LOG_PRINT_L1("MG signature verification failed"); return false; } } return true; } catch (const std::exception &e) { LOG_PRINT_L1("Error in verRct: " << e.what()); return false; } catch (...) { LOG_PRINT_L1("Error in verRct, but not an actual exception"); return false; } } //ver RingCT simple //assumes only post-rct style inputs (at least for max anonymity) bool verRctSemanticsSimple(const std::vector<const rctSig*> & rvv) { try { PERF_TIMER(verRctSemanticsSimple); tools::threadpool& tpool = tools::threadpool::getInstance(); tools::threadpool::waiter waiter; std::deque<bool> results; std::vector<const Bulletproof*> proofs; size_t max_non_bp_proofs = 0, offset = 0; for (const rctSig *rvp: rvv) { CHECK_AND_ASSERT_MES(rvp, false, "rctSig pointer is NULL"); const rctSig &rv = *rvp; CHECK_AND_ASSERT_MES(rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2, false, "verRctSemanticsSimple called on non simple rctSig"); const bool bulletproof = is_rct_bulletproof(rv.type); if (bulletproof) { CHECK_AND_ASSERT_MES(rv.outPk.size() == n_bulletproof_amounts(rv.p.bulletproofs), false, "Mismatched sizes of outPk and bulletproofs"); CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.size() == rv.p.MGs.size(), false, "Mismatched sizes of rv.p.pseudoOuts and rv.p.MGs"); CHECK_AND_ASSERT_MES(rv.pseudoOuts.empty(), false, "rv.pseudoOuts is not empty"); } else { CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.p.rangeSigs.size(), false, "Mismatched sizes of outPk and rv.p.rangeSigs"); CHECK_AND_ASSERT_MES(rv.pseudoOuts.size() == rv.p.MGs.size(), false, "Mismatched sizes of rv.pseudoOuts and rv.p.MGs"); CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.empty(), false, "rv.p.pseudoOuts is not empty"); } CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.ecdhInfo.size(), false, "Mismatched sizes of outPk and rv.ecdhInfo"); if (!bulletproof) max_non_bp_proofs += rv.p.rangeSigs.size(); } results.resize(max_non_bp_proofs); for (const rctSig *rvp: rvv) { const rctSig &rv = *rvp; const bool bulletproof = is_rct_bulletproof(rv.type); const keyV &pseudoOuts = bulletproof ? rv.p.pseudoOuts : rv.pseudoOuts; rct::keyV masks(rv.outPk.size()); for (size_t i = 0; i < rv.outPk.size(); i++) { masks[i] = rv.outPk[i].mask; } key sumOutpks = addKeys(masks); DP(sumOutpks); const key txnFeeKey = scalarmultH(d2h(rv.txnFee)); addKeys(sumOutpks, txnFeeKey, sumOutpks); key sumPseudoOuts = addKeys(pseudoOuts); DP(sumPseudoOuts); //check pseudoOuts vs Outs.. if (!equalKeys(sumPseudoOuts, sumOutpks)) { LOG_PRINT_L1("Sum check failed"); return false; } if (bulletproof) { for (size_t i = 0; i < rv.p.bulletproofs.size(); i++) proofs.push_back(&rv.p.bulletproofs[i]); } else { for (size_t i = 0; i < rv.p.rangeSigs.size(); i++) tpool.submit(&waiter, [&, i, offset] { results[i+offset] = verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]); }); offset += rv.p.rangeSigs.size(); } } if (!proofs.empty() && !verBulletproof(proofs)) { LOG_PRINT_L1("Aggregate range proof verified failed"); return false; } waiter.wait(&tpool); for (size_t i = 0; i < results.size(); ++i) { if (!results[i]) { LOG_PRINT_L1("Range proof verified failed for proof " << i); return false; } } return true; } // we can get deep throws from ge_frombytes_vartime if input isn't valid catch (const std::exception &e) { LOG_PRINT_L1("Error in verRctSemanticsSimple: " << e.what()); return false; } catch (...) { LOG_PRINT_L1("Error in verRctSemanticsSimple, but not an actual exception"); return false; } } bool verRctSemanticsSimple(const rctSig & rv) { return verRctSemanticsSimple(std::vector<const rctSig*>(1, &rv)); } //ver RingCT simple //assumes only post-rct style inputs (at least for max anonymity) bool verRctNonSemanticsSimple(const rctSig & rv) { try { PERF_TIMER(verRctNonSemanticsSimple); CHECK_AND_ASSERT_MES(rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2, false, "verRctNonSemanticsSimple called on non simple rctSig"); const bool bulletproof = is_rct_bulletproof(rv.type); // semantics check is early, and mixRing/MGs aren't resolved yet if (bulletproof) CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.size() == rv.mixRing.size(), false, "Mismatched sizes of rv.p.pseudoOuts and mixRing"); else CHECK_AND_ASSERT_MES(rv.pseudoOuts.size() == rv.mixRing.size(), false, "Mismatched sizes of rv.pseudoOuts and mixRing"); const size_t threads = std::max(rv.outPk.size(), rv.mixRing.size()); std::deque<bool> results(threads); tools::threadpool& tpool = tools::threadpool::getInstance(); tools::threadpool::waiter waiter; const keyV &pseudoOuts = bulletproof ? rv.p.pseudoOuts : rv.pseudoOuts; const key message = get_pre_mlsag_hash(rv, hw::get_device("default")); results.clear(); results.resize(rv.mixRing.size()); for (size_t i = 0 ; i < rv.mixRing.size() ; i++) { tpool.submit(&waiter, [&, i] { results[i] = verRctMGSimple(message, rv.p.MGs[i], rv.mixRing[i], pseudoOuts[i]); }); } waiter.wait(&tpool); for (size_t i = 0; i < results.size(); ++i) { if (!results[i]) { LOG_PRINT_L1("verRctMGSimple failed for input " << i); return false; } } return true; } // we can get deep throws from ge_frombytes_vartime if input isn't valid catch (const std::exception &e) { LOG_PRINT_L1("Error in verRctNonSemanticsSimple: " << e.what()); return false; } catch (...) { LOG_PRINT_L1("Error in verRctNonSemanticsSimple, but not an actual exception"); return false; } } //RingCT protocol //genRct: // creates an rctSig with all data necessary to verify the rangeProofs and that the signer owns one of the // columns that are claimed as inputs, and that the sum of inputs = sum of outputs. // Also contains masked "amount" and "mask" so the receiver can see how much they received //verRct: // verifies that all signatures (rangeProogs, MG sig, sum inputs = outputs) are correct //decodeRct: (c.f. https://eprint.iacr.org/2015/1098 section 5.1.1) // uses the attached ecdh info to find the amounts represented by each output commitment // must know the destination private key to find the correct amount, else will return a random number xmr_amount decodeRct(const rctSig & rv, const key & sk, unsigned int i, key & mask, hw::device &hwdev) { CHECK_AND_ASSERT_MES(rv.type == RCTTypeFull, false, "decodeRct called on non-full rctSig"); CHECK_AND_ASSERT_THROW_MES(i < rv.ecdhInfo.size(), "Bad index"); CHECK_AND_ASSERT_THROW_MES(rv.outPk.size() == rv.ecdhInfo.size(), "Mismatched sizes of rv.outPk and rv.ecdhInfo"); //mask amount and mask ecdhTuple ecdh_info = rv.ecdhInfo[i]; hwdev.ecdhDecode(ecdh_info, sk, rv.type == RCTTypeBulletproof2); mask = ecdh_info.mask; key amount = ecdh_info.amount; key C = rv.outPk[i].mask; DP("C"); DP(C); key Ctmp; CHECK_AND_ASSERT_THROW_MES(sc_check(mask.bytes) == 0, "warning, bad ECDH mask"); CHECK_AND_ASSERT_THROW_MES(sc_check(amount.bytes) == 0, "warning, bad ECDH amount"); addKeys2(Ctmp, mask, amount, H); DP("Ctmp"); DP(Ctmp); if (equalKeys(C, Ctmp) == false) { CHECK_AND_ASSERT_THROW_MES(false, "warning, amount decoded incorrectly, will be unable to spend"); } return h2d(amount); } xmr_amount decodeRct(const rctSig & rv, const key & sk, unsigned int i, hw::device &hwdev) { key mask; return decodeRct(rv, sk, i, mask, hwdev); } xmr_amount decodeRctSimple(const rctSig & rv, const key & sk, unsigned int i, key &mask, hw::device &hwdev) { CHECK_AND_ASSERT_MES(rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2, false, "decodeRct called on non simple rctSig"); CHECK_AND_ASSERT_THROW_MES(i < rv.ecdhInfo.size(), "Bad index"); CHECK_AND_ASSERT_THROW_MES(rv.outPk.size() == rv.ecdhInfo.size(), "Mismatched sizes of rv.outPk and rv.ecdhInfo"); //mask amount and mask ecdhTuple ecdh_info = rv.ecdhInfo[i]; hwdev.ecdhDecode(ecdh_info, sk, rv.type == RCTTypeBulletproof2); mask = ecdh_info.mask; key amount = ecdh_info.amount; key C = rv.outPk[i].mask; DP("C"); DP(C); key Ctmp; CHECK_AND_ASSERT_THROW_MES(sc_check(mask.bytes) == 0, "warning, bad ECDH mask"); CHECK_AND_ASSERT_THROW_MES(sc_check(amount.bytes) == 0, "warning, bad ECDH amount"); addKeys2(Ctmp, mask, amount, H); DP("Ctmp"); DP(Ctmp); if (equalKeys(C, Ctmp) == false) { CHECK_AND_ASSERT_THROW_MES(false, "warning, amount decoded incorrectly, will be unable to spend"); } return h2d(amount); } xmr_amount decodeRctSimple(const rctSig & rv, const key & sk, unsigned int i, hw::device &hwdev) { key mask; return decodeRctSimple(rv, sk, i, mask, hwdev); } bool signMultisig(rctSig &rv, const std::vector<unsigned int> &indices, const keyV &k, const multisig_out &msout, const key &secret_key) { CHECK_AND_ASSERT_MES(rv.type == RCTTypeFull || rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2, false, "unsupported rct type"); CHECK_AND_ASSERT_MES(indices.size() == k.size(), false, "Mismatched k/indices sizes"); CHECK_AND_ASSERT_MES(k.size() == rv.p.MGs.size(), false, "Mismatched k/MGs size"); CHECK_AND_ASSERT_MES(k.size() == msout.c.size(), false, "Mismatched k/msout.c size"); if (rv.type == RCTTypeFull) { CHECK_AND_ASSERT_MES(rv.p.MGs.size() == 1, false, "MGs not a single element"); } for (size_t n = 0; n < indices.size(); ++n) { CHECK_AND_ASSERT_MES(indices[n] < rv.p.MGs[n].ss.size(), false, "Index out of range"); CHECK_AND_ASSERT_MES(!rv.p.MGs[n].ss[indices[n]].empty(), false, "empty ss line"); } for (size_t n = 0; n < indices.size(); ++n) { rct::key diff; sc_mulsub(diff.bytes, msout.c[n].bytes, secret_key.bytes, k[n].bytes); sc_add(rv.p.MGs[n].ss[indices[n]][0].bytes, rv.p.MGs[n].ss[indices[n]][0].bytes, diff.bytes); } return true; } }
43.62915
403
0.572288
[ "vector" ]
d5572876d1898b39dc2a02e318951599a3b02cbf
7,311
cpp
C++
source/supreme/tool.cpp
Hypexion/HamSandwich
e5adb6b45d822cbef1be1a52d0ce51513dc24bc8
[ "MIT" ]
24
2019-05-12T12:03:21.000Z
2022-03-30T01:05:46.000Z
source/supreme/tool.cpp
Hypexion/HamSandwich
e5adb6b45d822cbef1be1a52d0ce51513dc24bc8
[ "MIT" ]
6
2019-05-12T11:54:54.000Z
2022-02-26T11:47:20.000Z
source/supreme/tool.cpp
Hypexion/HamSandwich
e5adb6b45d822cbef1be1a52d0ce51513dc24bc8
[ "MIT" ]
12
2019-05-12T13:48:57.000Z
2022-02-25T15:25:24.000Z
#include "winpch.h" #include "tool.h" #include "tool_floor.h" #include "tool_wall.h" #include "tool_item.h" #include "tool_monster.h" #include "tool_light.h" #include "tool_eraser.h" #include "tool_special.h" #include "tool_select.h" #include "dialogbits.h" #include "terrainedit.h" #include "soundedit.h" #include "monsteredit.h" #include "itemedit.h" #include "edithelp.h" #include "yesnodialog.h" #include "mapdialog.h" #include "leveldialog.h" #include "viewdialog.h" static Tool *tool[NUM_TOOLS],*curTool; static byte whichTool; static byte doing; static char toolName[NUM_TOOLS][16]={"Floor","Wall","Item","Badguy","Light","Special","Select", "Eraser"}; static char menuName[NUM_MENUS][16]={"File","World","TEST!","Level","View","Tiles","Items","Sound", "Exit"}; char worldFilename[64]; void ToolInit(void) { int i; worldFilename[0]='\0'; doing=TD_USING; whichTool=TOOL_FLOOR; for(i=0;i<NUM_TOOLS;i++) tool[i]=NULL; tool[TOOL_FLOOR]=new FloorTool(); tool[TOOL_WALL]=new WallTool(); tool[TOOL_ITEM]=new ItemTool(); tool[TOOL_BADGUY]=new MonsterTool(); tool[TOOL_LIGHT]=new LightTool(); tool[TOOL_SELECT]=new SelectTool(); tool[TOOL_ERASER]=new EraserTool(); tool[TOOL_SPECIAL]=new SpecialTool(); curTool=tool[0]; } void ToolExit(void) { int i; for(i=0;i<NUM_TOOLS;i++) if(tool[i]) { delete tool[i]; tool[i]=NULL; } } byte ToolDoing(void) { return doing; } TASK(void) ToolUpdate(int msx,int msy,byte editMenu,MGLDraw *mgl) { switch(doing) { case TD_USING: if(editMenu) { if(PointInRect(msx,msy,380,386,435,400)) // tool name { if(mgl->MouseTap()) doing=TD_PICKTOOL; } else if(PointInRect(msx,msy,584,386,639,400)) // menu list { if(mgl->MouseTap()) doing=TD_PICKMENU; } else if(!PointInRect(msx,msy,380,400,639,479)) { // not anywhere in the menu if(mgl->MouseTap()) { doing=TD_PLOPPING; curTool->StartPlop(); } if(mgl->RMouseTap()) { doing=TD_ERASING; curTool->StartErase(); } } } else { // not anywhere in the menu, no matter what, since the menu is missing! if(mgl->MouseTap()) { doing=TD_PLOPPING; curTool->StartPlop(); } if(mgl->RMouseTap()) { doing=TD_ERASING; curTool->StartErase(); } } curTool->Update(msx,msy); break; case TD_PICKTOOL: if(mgl->MouseDown()) { // do nothing, continue picking the tool } else { // you released the mouse, so select the tool if on it if(PointInRect(msx,msy,380,400-16*NUM_TOOLS,435,399)) { whichTool=(msy-(400-16*NUM_TOOLS))/16; curTool=tool[whichTool]; } doing=TD_USING; } break; case TD_PICKMENU: if(mgl->MouseDown()) { // do nothing, continue picking the menu } else { // you released the mouse, so select the menu if on it if(PointInRect(msx,msy,584,400-16*NUM_MENUS,639,399)) { switch((msy-(400-16*NUM_MENUS))/16) { case MENU_FILE: InitFileDialog("worlds",".dlw",FM_SAVE|FM_LOAD|FM_NEW|FM_EXIT|FM_ASKLOAD,worldFilename); SetEditMode(EDITMODE_FILE); break; case MENU_WORLD: SetEditMode(EDITMODE_MAPMENU); InitMapDialog(EditorGetWorld(),EditorGetMapNum()); break; case MENU_TEST: int cx,cy; GetCamera(&cx,&cy); AWAIT TestLevel(EditorGetWorld(),EditorGetMapNum()); StopSong(); SetPlayerStart(-1,-1); AddMapGuys(EditorGetMap()); PutCamera(cx<<FIXSHIFT,cy<<FIXSHIFT); break; case MENU_LEVEL: SetEditMode(EDITMODE_LEVELMENU); InitLevelDialog(EditorGetWorld(),EditorGetMapNum()); break; case MENU_TILES: TerrainEdit_Init(EditorGetWorld()); SetEditMode(EDITMODE_TERRAIN); break; case MENU_ITEMS: ItemEdit_Init(EDITMODE_EDIT,EditorGetWorld(),0); SetEditMode(EDITMODE_ITEM); break; case MENU_SOUND: SoundEdit_Init(EditorGetWorld()); SetEditMode(EDITMODE_SOUND); break; case MENU_DISPLAY: ViewMenuOn(); break; case MENU_EXIT: InitYesNoDialog("Exit the editor?","Yes","No"); SetEditMode(EDITMODE_EXIT); break; } } doing=TD_USING; } break; case TD_PICKINK: curTool->SetInk(); doing=TD_USING; break; case TD_PLOPPING: if(mgl->MouseDown()) { curTool->Plop(); } else doing=TD_USING; break; case TD_ERASING: if(mgl->RMouseDown()) { curTool->Erase(); } else doing=TD_USING; break; } } void RenderToolList(int msx,int msy,MGLDraw *mgl) { int i; mgl->FillBox(380,400-16*NUM_TOOLS,435,400,6); mgl->Box(380,400-16*NUM_TOOLS,435,400,31); for(i=0;i<NUM_TOOLS;i++) { if(PointInRect(msx,msy,380,400-16*NUM_TOOLS+i*16,435,400-16*NUM_TOOLS+i*16+15)) mgl->FillBox(381,401-16*NUM_TOOLS+i*16,434,400-16*NUM_TOOLS+i*16+15,8+32*1); CenterPrint((435-380)/2+380,400-16*NUM_TOOLS+2+i*16,toolName[i],0,1); } } void RenderMenuList(int msx,int msy,MGLDraw *mgl) { int i; mgl->FillBox(584,400-16*NUM_MENUS,639,400,6); mgl->Box(584,400-16*NUM_MENUS,639,400,31); for(i=0;i<NUM_MENUS;i++) { if(PointInRect(msx,msy,584,400-16*NUM_MENUS+i*16,639,400-16*NUM_MENUS+i*16+15)) mgl->FillBox(585,401-16*NUM_MENUS+i*16,638,400-16*NUM_MENUS+i*16+15,8+32*1); CenterPrint((639-584)/2+584,400-16*NUM_MENUS+2+i*16,menuName[i],0,1); } } void ToolRender(int msx,int msy,MGLDraw *mgl) { // the base portion of the tool menu mgl->FillBox(380,400,639,479,6); mgl->Box(380,400,639,479,31); if(doing!=TD_PICKTOOL) { // make the tab for the tool name if(PointInRect(msx,msy,380,386,435,400)) mgl->FillBox(380,386,435,400,8+32*1); else mgl->FillBox(380,386,435,400,6); mgl->Box(380,386,435,400,31); CenterPrint((435-380)/2+380,389,toolName[whichTool],0,1); } else { RenderToolList(msx,msy,mgl); } if(doing==TD_PICKMENU) RenderMenuList(msx,msy,mgl); else { if(PointInRect(msx,msy,584,386,639,400)) mgl->FillBox(584,386,639,400,8+32*1); else mgl->FillBox(584,386,639,400,6); mgl->Box(584,386,639,400,31); CenterPrint((639-584)/2+584,389,"Menus",0,1); } curTool->Render(msx,msy); } void ToolPickInk(void) { doing=TD_PICKINK; } void ToolShowTarget(void) { curTool->ShowTarget(); } void ToolSetFilename(void) { strcpy(worldFilename,GetFilename("")); } char *ToolGetFilename(void) { return worldFilename; } void ToolSuckUp(int x,int y) { curTool->SuckUp(x,y); } void ToolBrushUp(void) { curTool->BrushUp(); } void ToolGetHelp(void) { SetEditMode(EDITMODE_HELP); InitEditHelp(HELP_FLOORTOOL+whichTool); } byte WhichTool(void) { return whichTool; } void PickTool(byte w) { whichTool=w; curTool=tool[w]; doing=TD_USING; } void ToolItemWasDeleted(int i) { ((MonsterTool *)tool[TOOL_BADGUY])->ItemWasDeleted(i); ((ItemTool *)tool[TOOL_ITEM])->ItemWasDeleted(i); } //------------------------------------ Tool::~Tool() { } void Tool::Update(int msx,int msy) { } void Tool::Render(int msx,int msy) { } void Tool::StartPlop(void) { } void Tool::Plop(void) { } void Tool::StartErase(void) { } void Tool::Erase(void) { } void Tool::SetInk(void) { } void Tool::ShowTarget(void) { } void Tool::SuckUp(int x,int y) { } void Tool::BrushUp(void) { }
19.706199
99
0.644919
[ "render" ]
d5580ba141fc4136888690835ddb18f93a7922bd
26,791
cpp
C++
dev/Gems/ScriptCanvas/Code/Editor/View/Widgets/PropertyGrid.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
2
2020-12-22T01:02:01.000Z
2020-12-22T01:02:05.000Z
dev/Gems/ScriptCanvas/Code/Editor/View/Widgets/PropertyGrid.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
dev/Gems/ScriptCanvas/Code/Editor/View/Widgets/PropertyGrid.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <precompiled.h> #include "PropertyGrid.h" #include <QLabel> #include <QVBoxLayout> #include <QScrollArea> #include <AzCore/Component/ComponentApplicationBus.h> #include <AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.hxx> #include <AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.hxx> #include <AzToolsFramework/UI/PropertyEditor/ComponentEditor.hxx> #include <AzToolsFramework/UI/PropertyEditor/ComponentEditorHeader.hxx> #include <AzToolsFramework/Entity/EditorEntityHelpers.h> #include <AzToolsFramework/ToolsComponents/EditorInspectorComponentBus.h> #include <AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI.h> #include <Editor/View/Widgets/PropertyGridContextMenu.h> #include <ScriptCanvas/Bus/RequestBus.h> #include <GraphCanvas/Components/Nodes/NodeBus.h> #include <GraphCanvas/Components/Nodes/NodeTitleBus.h> #include <GraphCanvas/Components/GraphCanvasPropertyBus.h> #include <GraphCanvas/Components/SceneBus.h> #include <GraphCanvas/Editor/GraphCanvasProfiler.h> #include <ScriptCanvas/Core/Endpoint.h> #include <GraphCanvas/Components/Slots/SlotBus.h> #include <ScriptCanvas/Libraries/Core/EBusEventHandler.h> #include <ScriptCanvas/Libraries/Core/Method.h> #include <ScriptCanvas/GraphCanvas/NodeDescriptorBus.h> namespace { using StringToInstanceMap = AZStd::unordered_map<AZStd::string, ScriptCanvasEditor::Widget::PropertyGrid::InstancesToDisplay>; AZStd::string GetTitle(const AZ::EntityId& entityId, AZ::Component* instance) { AZStd::string result; AZStd::string title; GraphCanvas::NodeTitleRequestBus::EventResult(title, entityId, &GraphCanvas::NodeTitleRequests::GetTitle); AZStd::string subtitle; GraphCanvas::NodeTitleRequestBus::EventResult(subtitle, entityId, &GraphCanvas::NodeTitleRequests::GetSubTitle); // NOT a variable. result = title; if (!subtitle.empty()) { result += (result.empty() ? "" : " - " ) + subtitle; } if (result.empty()) { result = AzToolsFramework::GetFriendlyComponentName(instance).c_str(); } return result; } void AddInstancesToComponentEditor( AzToolsFramework::ComponentEditor* componentEditor, const AZStd::list<AZ::Component*>& instanceList, AZStd::unordered_map<AZ::TypeId, AZ::Component*>& firstOfTypeMap, AZStd::unordered_set<AZ::EntityId>& entitySet) { GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION(); for (auto& instance : instanceList) { GRAPH_CANVAS_DETAILED_PROFILE_SCOPE("AddInstanceToComponentEditor::InnerLoop"); // non-first instances are aggregated under the first instance AZ::Component* aggregateInstance = nullptr; if (firstOfTypeMap.count(instance->RTTI_GetType()) > 0) { aggregateInstance = firstOfTypeMap[instance->RTTI_GetType()]; } else { firstOfTypeMap[instance->RTTI_GetType()] = instance; } componentEditor->AddInstance(instance, aggregateInstance, nullptr); // Try and get the underlying SC entity AZStd::any* userData{}; GraphCanvas::NodeRequestBus::EventResult(userData, instance->GetEntityId(), &GraphCanvas::NodeRequests::GetUserData); AZ::EntityId scriptCanvasId = userData && userData->is<AZ::EntityId>() ? *AZStd::any_cast<AZ::EntityId>(userData) : AZ::EntityId(); if (scriptCanvasId.IsValid()) { entitySet.insert(scriptCanvasId); } else { entitySet.insert(instance->GetEntityId()); } } } const AZStd::string GetMethod(AZ::Component* component) { auto classData = AzToolsFramework::GetComponentClassData(component); if (!classData) { return ""; } if (!classData->m_azRtti->IsTypeOf<ScriptCanvas::Nodes::Core::Method>()) { return ""; } ScriptCanvas::Nodes::Core::Method* method = azrtti_cast<ScriptCanvas::Nodes::Core::Method*>(component); return method->GetMethodClassName() + method->GetName(); } AZStd::string GetEBusEventHandlerString(const AZ::EntityId& entityId, AZ::Component* component) { auto classData = AzToolsFramework::GetComponentClassData(component); if (!classData) { return ""; } if (!classData->m_azRtti->IsTypeOf<ScriptCanvas::Nodes::Core::EBusEventHandler>()) { return ""; } ScriptCanvas::Nodes::Core::EBusEventHandler* eventHandler = azrtti_cast<ScriptCanvas::Nodes::Core::EBusEventHandler*>(component); // IMPORTANT: A wrapped node will have an event name. NOT a wrapper node. AZStd::string eventName; ScriptCanvasEditor::EBusHandlerEventNodeDescriptorRequestBus::EventResult(eventName, entityId, &ScriptCanvasEditor::EBusHandlerEventNodeDescriptorRequests::GetEventName); AZStd::string result = eventHandler->GetEBusName() + eventName; return result; } // Returns a set of unique display component instances AZStd::list<AZ::Component*> GetVisibleGcInstances(const AZ::EntityId& entityId) { GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION(); AZStd::list<AZ::Component*> result; GraphCanvas::GraphCanvasPropertyBus::EnumerateHandlersId(entityId, [&result](GraphCanvas::GraphCanvasPropertyInterface* propertyInterface) -> bool { AZ::Component* component = propertyInterface->GetPropertyComponent(); if (AzToolsFramework::ShouldInspectorShowComponent(component)) { result.push_back(component); } // Continue enumeration. return true; }); return result; } // Returns a set of unique display component instances AZStd::list<AZ::Component*> GetVisibleScInstances(const AZ::EntityId& entityId) { GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION(); // GraphCanvas entityId -> scriptCanvasEntity AZStd::any* userData {}; GraphCanvas::NodeRequestBus::EventResult(userData, entityId, &GraphCanvas::NodeRequests::GetUserData); AZ::EntityId scriptCanvasId = userData && userData->is<AZ::EntityId>() ? *AZStd::any_cast<AZ::EntityId>(userData) : AZ::EntityId(); if (!scriptCanvasId.IsValid()) { return AZStd::list<AZ::Component*>(); } AZ::Entity* scriptCanvasEntity = AzToolsFramework::GetEntityById(scriptCanvasId); if (!scriptCanvasEntity) { return AZStd::list<AZ::Component*>(); } // scriptCanvasEntity -> ScriptCanvas::Node AZStd::list<AZ::Component*> result; auto components = AZ::EntityUtils::FindDerivedComponents<ScriptCanvas::Node>(scriptCanvasEntity); for (auto component : components) { if (AzToolsFramework::ShouldInspectorShowComponent(component)) { result.push_back(component); } } return result; } void MoveInstances(const AZStd::string& position, const AZ::EntityId& entityId, AZStd::list<AZ::Component*>& gcInstances, AZStd::list<AZ::Component*>& scInstances, StringToInstanceMap& instancesToDisplay) { GRAPH_CANVAS_PROFILE_FUNCTION(); if (position.empty() || (gcInstances.empty() && scInstances.empty())) { return; } auto& entry = instancesToDisplay[position]; if (!entry.m_gcEntityId.IsValid()) { entry.m_gcEntityId = entityId; } if (!gcInstances.empty()) { entry.m_gcInstances.splice(entry.m_gcInstances.end(), gcInstances); } if (!scInstances.empty()) { entry.m_scInstances.splice(entry.m_scInstances.end(), scInstances); } } AZStd::string GetKeyForInstancesToDisplay(const AZ::EntityId& entityId, const AZStd::list<AZ::Component*>& gcInstances, const AZStd::list<AZ::Component*>& scInstances) { GRAPH_CANVAS_PROFILE_FUNCTION(); AZStd::string result; if (!scInstances.empty()) { auto component = scInstances.front(); result = GetMethod(component); if (!result.empty()) { return result; } result = GetEBusEventHandlerString(entityId, component); if (!result.empty()) { return result; } return component->RTTI_GetType().ToString<AZStd::string>(); } if (!gcInstances.empty()) { return gcInstances.front()->RTTI_GetType().ToString<AZStd::string>(); } return result; } void GetInstancesToDisplay(const AZStd::vector<AZ::EntityId>& selectedEntityIds, StringToInstanceMap& instancesToDisplay) { GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION(); for (auto& entityId : selectedEntityIds) { GRAPH_CANVAS_DETAILED_PROFILE_SCOPE("GetInstancesToDisplay::InnerLoop"); AZStd::list<AZ::Component*> gcInstances = GetVisibleGcInstances(entityId); AZStd::list<AZ::Component*> scInstances = GetVisibleScInstances(entityId); AZStd::string position = GetKeyForInstancesToDisplay(entityId, gcInstances, scInstances); MoveInstances(position, entityId, gcInstances, scInstances, instancesToDisplay); } } } namespace ScriptCanvasEditor { namespace Widget { PropertyGrid::PropertyGrid(QWidget* parent /*= nullptr*/, const char* name /*= "Properties"*/) : AzQtComponents::StyledDockWidget(parent) { // This is used for styling. setObjectName("PropertyGrid"); m_spacer = new QSpacerItem(1, 1, QSizePolicy::Fixed, QSizePolicy::Expanding); setWindowTitle(name); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_scrollArea = new QScrollArea(this); m_scrollArea->setWidgetResizable(true); m_scrollArea->setSizePolicy(QSizePolicy::Policy::Ignored, QSizePolicy::Policy::Ignored); m_host = new QWidget; m_host->setLayout(new QVBoxLayout()); m_scrollArea->setWidget(m_host); setWidget(m_scrollArea); AZ::SerializeContext* serializeContext = nullptr; AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationRequests::GetSerializeContext); AZ_Assert(serializeContext, "Failed to acquire application serialize context."); UpdateContents(AZStd::vector<AZ::EntityId>()); PropertyGridRequestBus::Handler::BusConnect(); } PropertyGrid::~PropertyGrid() { } void PropertyGrid::ClearSelection() { GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION(); for (auto& componentEditor : m_componentEditors) { // Component editor deletion needs to be deferred until the next frame // as ClearSelection can be called when a slot is removed via the Reflected // therefore causing the reflected property editor to be deleted while it is still // in the callstack // Deleting a node will cause the selection change event to be fired from the GraphCanvas Scene which leads to the selection being cleared // Furthermore that change queues a property editor refresh for next frame, which if the node contained an EntityId slot it attempts to access // the node address which has been deleted. // Therefore the property editor property modification refresh level is set to none to prevent a refresh before it gets deleted componentEditor->GetPropertyEditor()->CancelQueuedRefresh(); componentEditor->setVisible(false); componentEditor.release()->deleteLater(); } m_componentEditors.clear(); ScriptCanvas::EndpointNotificationBus::MultiHandler::BusDisconnect(); } void PropertyGrid::DisplayInstances(const InstancesToDisplay& instances) { GRAPH_CANVAS_PROFILE_FUNCTION(); if (instances.m_gcInstances.empty() && instances.m_scInstances.empty()) { return; } AzToolsFramework::ComponentEditor* componentEditor = CreateComponentEditor(); AZ::Component* firstGcInstance = !instances.m_gcInstances.empty() ? instances.m_gcInstances.front() : nullptr; AZ::Component* firstScInstance = !instances.m_scInstances.empty() ? instances.m_scInstances.front() : nullptr; AZStd::unordered_map<AZ::TypeId, AZ::Component*> firstOfTypeMap; AZStd::unordered_set<AZ::EntityId> entitySet; // This adds all the component instances to the component editor widget and aggregates them based on the component types AddInstancesToComponentEditor(componentEditor, instances.m_gcInstances, firstOfTypeMap, entitySet); AddInstancesToComponentEditor(componentEditor, instances.m_scInstances, firstOfTypeMap, entitySet); // Set the title. // This MUST be done AFTER AddInstance() to override the default title. AZStd::string title = GetTitle(instances.m_gcEntityId, firstScInstance ? firstScInstance : firstGcInstance); // Use the number of unique entities to determine the number of selected entities for this component editor if (entitySet.size() > 1) { title += AZStd::string::format(" (%zu Selected)", entitySet.size()); } componentEditor->GetHeader()->SetTitle(title.c_str()); { GRAPH_CANVAS_DETAILED_PROFILE_SCOPE("PropertyGrid::DisplayInstance::RefreshEditor"); // Refresh editor componentEditor->AddNotifications(); componentEditor->SetExpanded(true); componentEditor->InvalidateAll(); } // hiding the icon on the header for Preview componentEditor->GetHeader()->SetIcon(QIcon()); componentEditor->show(); } AzToolsFramework::ComponentEditor* PropertyGrid::CreateComponentEditor() { GRAPH_CANVAS_PROFILE_FUNCTION(); AZ::SerializeContext* serializeContext = nullptr; AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationRequests::GetSerializeContext); AZ_Assert(serializeContext, "Failed to acquire application serialize context."); { GRAPH_CANVAS_DETAILED_PROFILE_SCOPE("CreateComponentEditor::ComponentConstruction"); m_componentEditors.push_back(AZStd::make_unique<AzToolsFramework::ComponentEditor>(serializeContext, this, this)); } AzToolsFramework::ComponentEditor* componentEditor = m_componentEditors.back().get(); { GRAPH_CANVAS_DETAILED_PROFILE_SCOPE("CreateComponentEditor::ComponentConfiguration"); componentEditor->GetHeader()->SetHasContextMenu(false); componentEditor->GetPropertyEditor()->SetHideRootProperties(false); componentEditor->GetPropertyEditor()->SetAutoResizeLabels(true); connect(componentEditor, &AzToolsFramework::ComponentEditor::OnExpansionContractionDone, this, [this]() { m_host->layout()->update(); m_host->layout()->activate(); }); } { GRAPH_CANVAS_DETAILED_PROFILE_SCOPE("CreateComponentEditor::SpacerUpdates"); //move spacer to bottom of editors m_host->layout()->removeItem(m_spacer); m_host->layout()->addWidget(componentEditor); m_host->layout()->addItem(m_spacer); m_host->layout()->update(); } return componentEditor; } void PropertyGrid::SetSelection(const AZStd::vector<AZ::EntityId>& selectedEntityIds) { GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION(); ClearSelection(); UpdateContents(selectedEntityIds); RefreshPropertyGrid(); } void PropertyGrid::OnNodeUpdate(const AZ::EntityId&) { RefreshPropertyGrid(); } void PropertyGrid::BeforePropertyModified(AzToolsFramework::InstanceDataNode* pNode) { } void PropertyGrid::AfterPropertyModified(AzToolsFramework::InstanceDataNode* pNode) { AzToolsFramework::InstanceDataNode* componentNode = pNode; do { auto* componentClassData = componentNode->GetClassMetadata(); if (componentClassData && componentClassData->m_azRtti && componentClassData->m_azRtti->IsTypeOf(azrtti_typeid<AZ::Component>())) { break; } } while (componentNode = componentNode->GetParent()); if (!componentNode) { AZ_Warning("Script Canvas", false, "Failed to locate component data associated with the script canvas property. Unable to mark parent Entity as dirty."); return; } // Only need one instance to lookup the SceneId in-order to record the undo state const size_t firstInstanceIdx = 0; if (componentNode->GetNumInstances()) { AZ::SerializeContext* context = componentNode->GetSerializeContext(); AZ::Component* componentInstance = context->Cast<AZ::Component*>(componentNode->GetInstance(firstInstanceIdx), componentNode->GetClassMetadata()->m_typeId); if (componentInstance && componentInstance->GetEntity()) { AZ::EntityId scriptCanvasGraphId; if (AZ::EntityUtils::FindFirstDerivedComponent<ScriptCanvas::Node>(componentInstance->GetEntity())) { // ScriptCanvas Node ScriptCanvas::EditorNodeRequestBus::EventResult(scriptCanvasGraphId, componentInstance->GetEntityId(), &ScriptCanvas::EditorNodeRequests::GetGraphEntityId); } else { AZ::EntityId graphCanvasGraphId; GeneralRequestBus::BroadcastResult(scriptCanvasGraphId, &GeneralRequests::GetActiveScriptCanvasGraphId); if (!scriptCanvasGraphId.IsValid()) { // GraphCanvas Node GraphCanvas::SceneMemberRequestBus::EventResult(graphCanvasGraphId, componentInstance->GetEntityId(), &GraphCanvas::SceneMemberRequests::GetScene); GeneralRequestBus::BroadcastResult(scriptCanvasGraphId, &GeneralRequests::GetScriptCanvasGraphId, graphCanvasGraphId); } } GeneralRequestBus::Broadcast(&GeneralRequests::PostUndoPoint, scriptCanvasGraphId); } } } void PropertyGrid::SetPropertyEditingActive(AzToolsFramework::InstanceDataNode* pNode) { } void PropertyGrid::SetPropertyEditingComplete(AzToolsFramework::InstanceDataNode* pNode) { } void PropertyGrid::RequestPropertyContextMenu(AzToolsFramework::InstanceDataNode* node, const QPoint& point) { PropertyGridContextMenu contextMenu(node); if (!contextMenu.actions().empty()) { contextMenu.exec(point); } } void PropertyGrid::RefreshPropertyGrid() { GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION(); for (auto& componentEditor : m_componentEditors) { if (componentEditor->isVisible()) { componentEditor->QueuePropertyEditorInvalidation(AzToolsFramework::PropertyModificationRefreshLevel::Refresh_Values); } else { break; } } } void PropertyGrid::RebuildPropertyGrid() { for (auto& componentEditor : m_componentEditors) { if (componentEditor->isVisible()) { componentEditor->QueuePropertyEditorInvalidation(AzToolsFramework::PropertyModificationRefreshLevel::Refresh_EntireTree); } else { break; } } } void PropertyGrid::SetVisibility(const AZStd::vector<AZ::EntityId>& selectedEntityIds) { GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION(); // Set the visibility and connect for changes. for (auto& gcNodeEntityId : selectedEntityIds) { // GC node -> SC node. AZStd::any* nodeUserData = nullptr; GraphCanvas::NodeRequestBus::EventResult(nodeUserData, gcNodeEntityId, &GraphCanvas::NodeRequests::GetUserData); AZ::EntityId scNodeEntityId = nodeUserData && nodeUserData->is<AZ::EntityId>() ? *AZStd::any_cast<AZ::EntityId>(nodeUserData) : AZ::EntityId(); AZ::Entity* nodeEntity{}; AZ::ComponentApplicationBus::BroadcastResult(nodeEntity, &AZ::ComponentApplicationRequests::FindEntity, scNodeEntityId); auto node = nodeEntity ? AZ::EntityUtils::FindFirstDerivedComponent<ScriptCanvas::Node>(nodeEntity) : nullptr; if (!node) { continue; } AZStd::vector<AZ::EntityId> gcSlotEntityIds; GraphCanvas::NodeRequestBus::EventResult(gcSlotEntityIds, gcNodeEntityId, &GraphCanvas::NodeRequests::GetSlotIds); for (auto& gcSlotEntityId : gcSlotEntityIds) { // GC slot -> SC slot. AZStd::any* slotUserData = nullptr; GraphCanvas::SlotRequestBus::EventResult(slotUserData, gcSlotEntityId, &GraphCanvas::SlotRequests::GetUserData); ScriptCanvas::SlotId scSlotId = slotUserData && slotUserData->is<ScriptCanvas::SlotId>() ? *AZStd::any_cast<ScriptCanvas::SlotId>(slotUserData) : ScriptCanvas::SlotId(); const ScriptCanvas::Slot* slot = node->GetSlot(scSlotId); if (!slot || slot->GetDescriptor() != ScriptCanvas::SlotDescriptors::DataIn()) { continue; } // Set the visibility based on the connection status. { bool isConnected = false; GraphCanvas::SlotRequestBus::EventResult(isConnected, gcSlotEntityId, &GraphCanvas::SlotRequests::HasConnections); ScriptCanvas::Datum* datum = nullptr; ScriptCanvas::EditorNodeRequestBus::EventResult(datum, scNodeEntityId, &ScriptCanvas::EditorNodeRequests::ModInput, scSlotId); if (datum) { datum->SetVisibility(isConnected ? AZ::Edit::PropertyVisibility::Hide : AZ::Edit::PropertyVisibility::ShowChildrenOnly); } } // Connect to get notified of changes. ScriptCanvas::EndpointNotificationBus::MultiHandler::BusConnect(ScriptCanvas::Endpoint(scNodeEntityId, scSlotId)); } } } void PropertyGrid::UpdateContents(const AZStd::vector<AZ::EntityId>& selectedEntityIds) { GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION(); if (!selectedEntityIds.empty()) { // Build up components to display StringToInstanceMap instanceMap; GetInstancesToDisplay(selectedEntityIds, instanceMap); SetVisibility(selectedEntityIds); for (auto& pair : instanceMap) { GRAPH_CANVAS_DETAILED_PROFILE_SCOPE("PropertyGrid::UpdateContents::InstanceMapLoop"); DisplayInstances(pair.second); } } } void PropertyGrid::OnEndpointConnected(const ScriptCanvas::Endpoint& targetEndpoint) { const ScriptCanvas::Endpoint* sourceEndpoint = ScriptCanvas::EndpointNotificationBus::GetCurrentBusId(); ScriptCanvas::Datum* datum = nullptr; ScriptCanvas::EditorNodeRequestBus::EventResult(datum, sourceEndpoint->GetNodeId(), &ScriptCanvas::EditorNodeRequests::ModInput, sourceEndpoint->GetSlotId()); if (datum) { datum->SetVisibility(AZ::Edit::PropertyVisibility::Hide); } } void PropertyGrid::OnEndpointDisconnected(const ScriptCanvas::Endpoint& targetEndpoint) { const ScriptCanvas::Endpoint* sourceEndpoint = ScriptCanvas::EndpointNotificationBus::GetCurrentBusId(); ScriptCanvas::Datum* datum = nullptr; ScriptCanvas::EditorNodeRequestBus::EventResult(datum, sourceEndpoint->GetNodeId(), &ScriptCanvas::EditorNodeRequests::ModInput, sourceEndpoint->GetSlotId()); if (datum) { datum->SetVisibility(AZ::Edit::PropertyVisibility::ShowChildrenOnly); } } #include <Editor/View/Widgets/PropertyGrid.moc> } }
40.408748
189
0.615319
[ "vector" ]
d5587c22f953a5f2307698f5772a9729fdd280ae
11,423
cpp
C++
StackADT_JS_PS/StackADT_JS_PS/CurrencyTypes.cpp
jaydeep/stack-adt
92f90241b3eb2defa05d1aae02c0ad24bf44eb63
[ "MIT" ]
null
null
null
StackADT_JS_PS/StackADT_JS_PS/CurrencyTypes.cpp
jaydeep/stack-adt
92f90241b3eb2defa05d1aae02c0ad24bf44eb63
[ "MIT" ]
null
null
null
StackADT_JS_PS/StackADT_JS_PS/CurrencyTypes.cpp
jaydeep/stack-adt
92f90241b3eb2defa05d1aae02c0ad24bf44eb63
[ "MIT" ]
1
2018-10-16T20:02:01.000Z
2018-10-16T20:02:01.000Z
/* @class Implementation for CurrencyTypes class */ #include "CurrencyTypes.h" //United States dollar //Constructors USD::USD() { sCurrencyName = "USD"; sFractionalName = "Cent(s)"; } USD::USD(const string& sLocalCurrencyName, const string& sLocalFractionalName) { sCurrencyName = sLocalCurrencyName; sFractionalName = sLocalFractionalName; } USD::USD(const int& iLocalWholeValue, const int& iLocalFractionalValue) { sCurrencyName = "USD"; sFractionalName = "Cent(s)"; iWholeValue = iLocalWholeValue; iFractionalValue = iLocalFractionalValue; } USD::USD(const string& sLocalCurrencyName, const string& sLocalFractionalName, const int& iLocalWholeValue, const int& iLocalFractionalValue) { sCurrencyName = sLocalCurrencyName; sFractionalName = sLocalFractionalName; iWholeValue = iLocalWholeValue; iFractionalValue = iLocalFractionalValue; } //Mutators void USD::setiWholeValue(const int& iLocalWholeValue) { iWholeValue = iLocalWholeValue; } void USD::setiFractionalValue(const int& iLocalFractionalValue) { iFractionalValue = iLocalFractionalValue; } //Accessors const string& USD::getsCurrencyName() { return sCurrencyName; } const string& USD::getsFractionalName() { return sFractionalName; } //Overloaded Operators ostream &operator << (ostream& strm, const USD &obj) { if (obj.iFractionalValue < 10) { strm << obj.iWholeValue << " " << obj.sCurrencyName << " " << "0" << obj.iFractionalValue << " " << obj.sFractionalName; } else strm << obj.iWholeValue << " " << obj.sCurrencyName << " " << obj.iFractionalValue << " " << obj.sFractionalName; return strm; } USD USD::operator + (const USD& right) { USD temp = right; temp.iWholeValue = iWholeValue + right.iWholeValue; temp.iFractionalValue = iFractionalValue + right.iFractionalValue; temp.simplify(); return temp; } USD USD::operator - (const USD &right) { USD temp = right; temp.iWholeValue = iWholeValue - right.iWholeValue; temp.iFractionalValue = iFractionalValue - right.iFractionalValue; temp.simplify(); if (temp.iWholeValue < 0) { temp.setiWholeValue(0); temp.setiFractionalValue(0); string s_SubtractionError = "\nError: Subtraction results in negative value. Operation cancelled.\n"; throw (s_SubtractionError); return temp; } else return temp; } /********************************************************************************/ //Euro //Constructors EUR::EUR() { sCurrencyName = "EUR"; sFractionalName = "Cent"; } EUR::EUR(const string& sLocalCurrencyName, const string& sLocalFractionalName) { sCurrencyName = sLocalCurrencyName; sFractionalName = sLocalFractionalName; } EUR::EUR(const int& iLocalWholeValue, const int& iLocalFractionalValue) { sCurrencyName = "EUR"; sFractionalName = "Cent"; iWholeValue = iLocalWholeValue; iFractionalValue = iLocalFractionalValue; } EUR::EUR(const string& sLocalCurrencyName, const string& sLocalFractionalName, const int& iLocalWholeValue, const int& iLocalFractionalValue) { sCurrencyName = sLocalCurrencyName; sFractionalName = sLocalFractionalName; iWholeValue = iLocalWholeValue; iFractionalValue = iLocalFractionalValue; } //Mutators void EUR::setsCurrencyName(const string& sLocalCurrencyName) { sCurrencyName = sLocalCurrencyName; } void EUR::setsFractionalName(const string& sLocalFractionalName) { sFractionalName = sLocalFractionalName; } //Accessors const string& EUR::getsCurrencyName() { return sCurrencyName; } const string& EUR::getsFractionalName() { return sFractionalName; } //Overloaded Operators ostream &operator << (ostream& strm, const EUR &obj) { if (obj.iFractionalValue < 10) { strm << obj.iWholeValue << " " << obj.sCurrencyName << " " << "0" << obj.iFractionalValue << " " << obj.sFractionalName; } else strm << obj.iWholeValue << " " << obj.sCurrencyName << " " << obj.iFractionalValue << " " << obj.sFractionalName; return strm; } EUR EUR::operator + (const EUR& right) { EUR temp = right; temp.iWholeValue = iWholeValue + right.iWholeValue; temp.iFractionalValue = iFractionalValue + right.iFractionalValue; temp.simplify(); return temp; } EUR EUR::operator - (const EUR &right) { EUR temp = right; temp.iWholeValue = iWholeValue - right.iWholeValue; temp.iFractionalValue = iFractionalValue - right.iFractionalValue; temp.simplify(); if (temp.iWholeValue < 0) { temp.setiWholeValue(0); temp.setiFractionalValue(0); string s_SubtractionError = "\nError: Subtraction results in negative value. Operation cancelled.\n"; throw (s_SubtractionError); return temp; } else return temp; } /********************************************************************************/ //Pound sterling //Constructors GBP::GBP() { sCurrencyName = "GBP"; sFractionalName = "Penny / Pence"; } GBP::GBP(const string& sLocalCurrencyName, const string& sLocalFractionalName) { sCurrencyName = sLocalCurrencyName; sFractionalName = sLocalFractionalName; } GBP::GBP(const int& iLocalWholeValue, const int& iLocalFractionalValue) { sCurrencyName = "GBP"; sFractionalName = "Penny / Pence"; iWholeValue = iLocalWholeValue; iFractionalValue = iLocalFractionalValue; } GBP::GBP(const string& sLocalCurrencyName, const string& sLocalFractionalName, const int& iLocalWholeValue, const int& iLocalFractionalValue) { sCurrencyName = sLocalCurrencyName; sFractionalName = sLocalFractionalName; iWholeValue = iLocalWholeValue; iFractionalValue = iLocalFractionalValue; } //Mutators void GBP::setsCurrencyName(const string& sLocalCurrencyName) { sCurrencyName = sLocalCurrencyName; } void GBP::setsFractionalName(const string& sLocalFractionalName) { sFractionalName = sLocalFractionalName; } //Accessors const string& GBP::getsCurrencyName() { return sCurrencyName; } const string& GBP::getsFractionalName() { return sFractionalName; } //Overloaded Operators ostream &operator << (ostream& strm, const GBP &obj) { if (obj.iFractionalValue < 10) { strm << obj.iWholeValue << " " << obj.sCurrencyName << " " << "0" << obj.iFractionalValue << " " << obj.sFractionalName; } else strm << obj.iWholeValue << " " << obj.sCurrencyName << " " << obj.iFractionalValue << " " << obj.sFractionalName; return strm; } GBP GBP::operator + (const GBP& right) { GBP temp = right; temp.iWholeValue = iWholeValue + right.iWholeValue; temp.iFractionalValue = iFractionalValue + right.iFractionalValue; temp.simplify(); return temp; } GBP GBP::operator - (const GBP &right) { GBP temp = right; temp.iWholeValue = iWholeValue - right.iWholeValue; temp.iFractionalValue = iFractionalValue - right.iFractionalValue; temp.simplify(); if (temp.iWholeValue < 0) { temp.setiWholeValue(0); temp.setiFractionalValue(0); string s_SubtractionError = "\nError: Subtraction results in negative value. Operation cancelled.\n"; throw (s_SubtractionError); return temp; } else return temp; } /********************************************************************************/ //Australian dollar //Constructors AUD::AUD() { sCurrencyName = "AUD"; sFractionalName = "Cent(s)"; } AUD::AUD(const string& sLocalCurrencyName, const string& sLocalFractionalName) { sCurrencyName = sLocalCurrencyName; sFractionalName = sLocalFractionalName; } AUD::AUD(const int& iLocalWholeValue, const int& iLocalFractionalValue) { sCurrencyName = "AUD"; sFractionalName = "Cent(s)"; iWholeValue = iLocalWholeValue; iFractionalValue = iLocalFractionalValue; } AUD::AUD(const string& sLocalCurrencyName, const string& sLocalFractionalName, const int& iLocalWholeValue, const int& iLocalFractionalValue) { sCurrencyName = sLocalCurrencyName; sFractionalName = sLocalFractionalName; iWholeValue = iLocalWholeValue; iFractionalValue = iLocalFractionalValue; } //Mutators void AUD::setsCurrencyName(const string& sLocalCurrencyName) { sCurrencyName = sLocalCurrencyName; } void AUD::setsFractionalName(const string& sLocalFractionalName) { sFractionalName = sLocalFractionalName; } //Accessors const string& AUD::getsCurrencyName() { return sCurrencyName; } const string& AUD::getsFractionalName() { return sFractionalName; } //Overloaded Operators ostream &operator << (ostream& strm, const AUD &obj) { if (obj.iFractionalValue < 10) { strm << obj.iWholeValue << " " << obj.sCurrencyName << " " << "0" << obj.iFractionalValue << " " << obj.sFractionalName; } else strm << obj.iWholeValue << " " << obj.sCurrencyName << " " << obj.iFractionalValue << " " << obj.sFractionalName; return strm; } AUD AUD::operator + (const AUD& right) { AUD temp = right; temp.iWholeValue = iWholeValue + right.iWholeValue; temp.iFractionalValue = iFractionalValue + right.iFractionalValue; temp.simplify(); return temp; } AUD AUD::operator - (const AUD &right) { AUD temp = right; temp.iWholeValue = iWholeValue - right.iWholeValue; temp.iFractionalValue = iFractionalValue - right.iFractionalValue; temp.simplify(); if (temp.iWholeValue < 0) { temp.setiWholeValue(0); temp.setiFractionalValue(0); string s_SubtractionError = "\nError: Subtraction results in negative value. Operation cancelled.\n"; throw (s_SubtractionError); return temp; } else return temp; } /********************************************************************************/ //Canadian dollar //Constructors CAD::CAD() { sCurrencyName = "CAD"; sFractionalName = "Cent(s)"; } CAD::CAD(const string& sLocalCurrencyName, const string& sLocalFractionalName) { sCurrencyName = sLocalCurrencyName; sFractionalName = sLocalFractionalName; } CAD::CAD(const int& iLocalWholeValue, const int& iLocalFractionalValue) { sCurrencyName = "CAD"; sFractionalName = "Cent(s)"; iWholeValue = iLocalWholeValue; iFractionalValue = iLocalFractionalValue; } CAD::CAD(const string& sLocalCurrencyName, const string& sLocalFractionalName, const int& iLocalWholeValue, const int& iLocalFractionalValue) { sCurrencyName = sLocalCurrencyName; sFractionalName = sLocalFractionalName; iWholeValue = iLocalWholeValue; iFractionalValue = iLocalFractionalValue; } //Mutators void CAD::setsCurrencyName(const string& sLocalCurrencyName) { sCurrencyName = sLocalCurrencyName; } void CAD::setsFractionalName(const string& sLocalFractionalName) { sFractionalName = sLocalFractionalName; } //Accessors const string& CAD::getsCurrencyName() { return sCurrencyName; } const string& CAD::getsFractionalName() { return sFractionalName; } //Overloaded Operators ostream &operator << (ostream& strm, const CAD &obj) { if (obj.iFractionalValue < 10) { strm << obj.iWholeValue << " " << obj.sCurrencyName << " " << "0" << obj.iFractionalValue << " " << obj.sFractionalName; } else strm << obj.iWholeValue << " " << obj.sCurrencyName << " " << obj.iFractionalValue << " " << obj.sFractionalName; return strm; } CAD CAD::operator + (const CAD& right) { CAD temp = right; temp.iWholeValue = iWholeValue + right.iWholeValue; temp.iFractionalValue = iFractionalValue + right.iFractionalValue; temp.simplify(); return temp; } CAD CAD::operator - (const CAD &right) { CAD temp = right; temp.iWholeValue = iWholeValue - right.iWholeValue; temp.iFractionalValue = iFractionalValue - right.iFractionalValue; temp.simplify(); if (temp.iWholeValue < 0) { temp.setiWholeValue(0); temp.setiFractionalValue(0); string s_SubtractionError = "\nError: Subtraction results in negative value. Operation cancelled.\n"; throw (s_SubtractionError); return temp; } else return temp; }
24.304255
141
0.721264
[ "cad" ]
d55bf3e08de99206b4c16f12d58994ec3993c04f
9,852
cc
C++
ggadget/extension_manager.cc
meego-netbook-ux/google-gadgets-meego
89af89796bca073e95f44d43c9d81407caabedf0
[ "Apache-2.0" ]
null
null
null
ggadget/extension_manager.cc
meego-netbook-ux/google-gadgets-meego
89af89796bca073e95f44d43c9d81407caabedf0
[ "Apache-2.0" ]
null
null
null
ggadget/extension_manager.cc
meego-netbook-ux/google-gadgets-meego
89af89796bca073e95f44d43c9d81407caabedf0
[ "Apache-2.0" ]
null
null
null
/* Copyright 2008 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 <algorithm> #include <utility> #include <vector> #include <cstdlib> #include "logger.h" #include "module.h" #include "common.h" #include "extension_manager.h" #include "small_object.h" namespace ggadget { ElementExtensionRegister::ElementExtensionRegister(ElementFactory *factory) : factory_(factory) { } bool ElementExtensionRegister::RegisterExtension(const Module *extension) { ASSERT(extension); // reinterpret_cast<> doesn't work on gcc 3.x RegisterElementExtensionFunc func = (RegisterElementExtensionFunc)( extension->GetSymbol(kElementExtensionSymbolName)); return func ? func(factory_) : false; } ScriptExtensionRegister::ScriptExtensionRegister( ScriptContextInterface *context, Gadget *gadget) : context_(context), gadget_(gadget) { } bool ScriptExtensionRegister::RegisterExtension(const Module *extension) { ASSERT(extension); // reinterpret_cast<> doesn't work on gcc 3.x RegisterScriptExtensionFunc func = (RegisterScriptExtensionFunc)( extension->GetSymbol(kScriptExtensionSymbolName)); return func ? func(context_, gadget_) : false; } FrameworkExtensionRegister::FrameworkExtensionRegister( ScriptableInterface *framework, Gadget *gadget) : framework_(framework), gadget_(gadget) { } bool FrameworkExtensionRegister::RegisterExtension(const Module *extension) { ASSERT(extension); // reinterpret_cast<> doesn't work on gcc 3.x RegisterFrameworkExtensionFunc func = (RegisterFrameworkExtensionFunc)( extension->GetSymbol(kFrameworkExtensionSymbolName)); return func ? func(framework_, gadget_) : false; } ScriptRuntimeExtensionRegister::ScriptRuntimeExtensionRegister( ScriptRuntimeManager *manager) : manager_(manager) { } bool ScriptRuntimeExtensionRegister::RegisterExtension(const Module *extension) { ASSERT(extension); // reinterpret_cast<> doesn't work on gcc 3.x RegisterScriptRuntimeExtensionFunc func = (RegisterScriptRuntimeExtensionFunc)( extension->GetSymbol(kScriptRuntimeExtensionSymbolName)); return func ? func(manager_) : false; } FileManagerExtensionRegister::FileManagerExtensionRegister( FileManagerWrapper *fm_wrapper) : fm_wrapper_(fm_wrapper) { } bool FileManagerExtensionRegister::RegisterExtension(const Module *extension) { ASSERT(extension); // reinterpret_cast<> doesn't work on gcc 3.x RegisterFileManagerExtensionFunc func = (RegisterFileManagerExtensionFunc)( extension->GetSymbol(kFileManagerExtensionSymbolName)); return func ? func(fm_wrapper_) : false; } class MultipleExtensionRegisterWrapper::Impl : public SmallObject<> { public: typedef std::vector<ExtensionRegisterInterface *> ExtRegisterVector; ExtRegisterVector ext_registers_; }; MultipleExtensionRegisterWrapper::MultipleExtensionRegisterWrapper() : impl_(new Impl()) { } MultipleExtensionRegisterWrapper::~MultipleExtensionRegisterWrapper() { delete impl_; } bool MultipleExtensionRegisterWrapper::RegisterExtension( const Module *extension) { ASSERT(extension); bool result = false; Impl::ExtRegisterVector::iterator it = impl_->ext_registers_.begin(); for (;it != impl_->ext_registers_.end(); ++it) { if ((*it)->RegisterExtension(extension)) result = true; } return result; } void MultipleExtensionRegisterWrapper::AddExtensionRegister( ExtensionRegisterInterface *ext_register) { ASSERT(ext_register); impl_->ext_registers_.push_back(ext_register); } class ExtensionManager::Impl : public SmallObject<> { typedef std::vector<std::pair<std::string, Module*> > ExtensionVector; public: Impl() : readonly_(false) { } ~Impl() { // Destroy extensions in reverse order. for (ExtensionVector::reverse_iterator it = extensions_.rbegin(); it != extensions_.rend(); ++it) { delete it->second; } } ExtensionVector::iterator FindExtension(const std::string &name) { ExtensionVector::iterator it = extensions_.begin(); for (; it != extensions_.end(); ++it) { if (it->first == name) break; } return it; } Module *LoadExtension(const char *name, bool resident) { ASSERT(name && *name); if (readonly_) { LOG("Can't load extension %s, into a readonly ExtensionManager.", name); return NULL; } if (name && *name) { std::string name_str(name); // If the module has already been loaded, then just return it. ExtensionVector::iterator it = FindExtension(name_str); if (it != extensions_.end()) { if (!it->second->IsResident() && resident) it->second->MakeResident(); return it->second; } Module *extension = new Module(name); if (!extension->IsValid()) { delete extension; return NULL; } if (resident) extension->MakeResident(); extensions_.push_back(std::make_pair(name_str, extension)); DLOG("Extension %s was loaded successfully.", name); return extension; } return NULL; } bool UnloadExtension(const char *name) { ASSERT(name && *name); if (readonly_) { LOG("Can't unload extension %s, from a readonly ExtensionManager.", name); return false; } if (name && *name) { std::string name_str(name); ExtensionVector::iterator it = FindExtension(name_str); if (it != extensions_.end()) { if (it->second->IsResident()) { LOG("Can't unload extension %s, it's resident.", name); return false; } delete it->second; extensions_.erase(it); return true; } } return false; } bool EnumerateLoadedExtensions( Slot2<bool, const char *, const char *> *callback) { ASSERT(callback); bool result = false; for (ExtensionVector::const_iterator it = extensions_.begin(); it != extensions_.end(); ++it) { result = (*callback)(it->first.c_str(), it->second->GetName().c_str()); if (!result) break; } delete callback; return result; } bool RegisterExtension(const char *name, ExtensionRegisterInterface *reg) { ASSERT(name && *name && reg); Module *extension = LoadExtension(name, false); if (extension && extension->IsValid()) { return reg->RegisterExtension(extension); } return false; } bool RegisterLoadedExtensions(ExtensionRegisterInterface *reg) { ASSERT(reg); if (extensions_.size()) { bool ret = true; for (ExtensionVector::const_iterator it = extensions_.begin(); it != extensions_.end(); ++it) { if (!reg->RegisterExtension(it->second)) ret = false; } return ret; } return false; } void SetReadonly() { // Don't make extensions resident, so that they can be unloaded when exit. readonly_ = true; } public: static void ExitHandler() { // Inform the logger not to use contexts any more, because the destruction // of the global manager will unload the module that log contexts might // depend on. FinalizeLogger(); if (global_manager_) { DLOG("Destroy global extension manager."); delete global_manager_; global_manager_ = NULL; } } static bool SetGlobalExtensionManager(ExtensionManager *manager) { if (!global_manager_ && manager) { global_manager_ = manager; atexit(ExitHandler); return true; } return false; } static ExtensionManager *GetGlobalExtensionManager() { return global_manager_; } static ExtensionManager *global_manager_; private: ExtensionVector extensions_; bool readonly_; }; ExtensionManager* ExtensionManager::Impl::global_manager_ = NULL; ExtensionManager::ExtensionManager() : impl_(new Impl()) { } ExtensionManager::~ExtensionManager() { delete impl_; } bool ExtensionManager::Destroy() { if (this && this != Impl::global_manager_) { delete this; return true; } DLOG("Try to destroy %s ExtensionManager object.", (this == NULL ? "an invalid" : "the global")); return false; } bool ExtensionManager::LoadExtension(const char *name, bool resident) { return impl_->LoadExtension(name, resident) != NULL; } bool ExtensionManager::UnloadExtension(const char *name) { return impl_->UnloadExtension(name); } bool ExtensionManager::EnumerateLoadedExtensions( Slot2<bool, const char *, const char *> *callback) const { return impl_->EnumerateLoadedExtensions(callback); } bool ExtensionManager::RegisterExtension(const char *name, ExtensionRegisterInterface *reg) const { return impl_->RegisterExtension(name, reg); } bool ExtensionManager::RegisterLoadedExtensions( ExtensionRegisterInterface *reg) const { return impl_->RegisterLoadedExtensions(reg); } void ExtensionManager::SetReadonly() { impl_->SetReadonly(); } const ExtensionManager *ExtensionManager::GetGlobalExtensionManager() { return Impl::GetGlobalExtensionManager(); } bool ExtensionManager::SetGlobalExtensionManager(ExtensionManager *manager) { return Impl::SetGlobalExtensionManager(manager); } ExtensionManager * ExtensionManager::CreateExtensionManager() { ExtensionManager *manager = new ExtensionManager(); return manager; } } // namespace ggadget
27.830508
81
0.699249
[ "object", "vector" ]
f65a33f0a6c769a2d3e089ec05f6c6f41fc6ce89
25,038
cpp
C++
PlatformIO_Files/NodeOven/src/main.cpp
Hans-Beerman/NodeOven
582493a7740506022321a3cc4d3aead28b9aba74
[ "Apache-2.0" ]
null
null
null
PlatformIO_Files/NodeOven/src/main.cpp
Hans-Beerman/NodeOven
582493a7740506022321a3cc4d3aead28b9aba74
[ "Apache-2.0" ]
null
null
null
PlatformIO_Files/NodeOven/src/main.cpp
Hans-Beerman/NodeOven
582493a7740506022321a3cc4d3aead28b9aba74
[ "Apache-2.0" ]
null
null
null
/* Copyright 2015-2018 Dirk-Willem van Gulik <dirkx@webweaving.org> Copyright 2020 Hans Beerman <hans.beerman@xs4all.nl> Stichting Makerspace Leiden, the Netherlands. 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. */ #ifndef ESP32 #error "The MetalNode uses an ESP32 based board (Olimex ESP32-PoE)!" #endif // An Olimex ESP32-PoE is used (default is POESP board (Aart board)) #define ESP32_PoE // for debugging // see DEBUGIT flag in platformio.ini // i2C params #define RFID_SDA_PIN (13) #define RFID_SCL_PIN (16) #include <Arduino.h> #include <PowerNodeV11.h> #include <ACNode.h> #include <RFID.h> // NFC version #include <SIG2.h> #include <Cache.h> #include <EEPROM.h> #include ".passwd.h" /* If using WiFi instead of a fixed ethernet connection, and/or OTA: Add Passwd.h to the NodeOven/src directoy containing the following information #pragma once #define WIFI_NETWORK "YOUR_SSID" #define WIFI_PASSWD "YOUR_PASSWD" #define OTA_PASSWD "YOUR_OTA_PASSWD" */ #include "pid.h" #define MACHINE "nodeoven" #define SOLID_STATE_RELAIS_PIN (33) #define SIGNAL_LAMP_PIN (32) #define FAN_PIN (0) #define KWH_METER_PIN (35) #define SERIAL_RX_PIN 36 #define SERIAL_TX_PIN 4 #define SERIAL_MAXLINELENGTH 128 #define SERIAL2_BAUDRATE 19200 #define DISPLAY_UPDATE_INTERVAL 1000 // in ms // See https://mailman.makerspaceleiden.nl/mailman/private/deelnemers/2019-February/019837.html // Introduced by alex - 2020-01-8 // Clear EEProm + Cache button // Press BUT1 on Olimex ESP32 PoE module before (re)boot of node // keep BUT1 pressed for at least 5 s // After the release of BUT1 node will restart with empty EEProm and empty cache #define CLEAR_EEPROM_AND_CACHE_BUTTON (34) #define CLEAR_EEPROM_AND_CACHE_BUTTON_PRESSED (LOW) #define MAX_WAIT_TIME_BUTTON_PRESSED (4000) // in ms #ifdef WIFI_NETWORK ACNode node = ACNode(MACHINE, WIFI_NETWORK, WIFI_PASSWD); #else ACNode node = ACNode(MACHINE); #endif RFID reader = RFID(false); // don't use tags already stored in cache, to see in the server who has used the oven MqttLogStream mqttlogStream = MqttLogStream(); TelnetSerialStream telnetSerialStream = TelnetSerialStream(); // Use software SPI: CS, DI, DO, CLK Adafruit_MAX31856 thermo = Adafruit_MAX31856(15, 5, 2, 14); #ifdef OTA_PASSWD OTA ota = OTA(OTA_PASSWD); #endif // LED aartLed = LED(SYSTEM_LED); // defaults to the aartLed - otherwise specify a GPIO. typedef enum { BOOTING, OUTOFORDER, // device not functional. REBOOT, // forcefull reboot TRANSIENTERROR, // hopefully goes away level error NOCONN, // sort of fairly hopless (though we can cache RFIDs!) WAITINGFORCARD, // waiting for card. CHECKINGCARD, CLEARSTATUS, APPROVED, REJECTED, OVENON, OVENOFF, } machinestates_t; #define NEVER (0) struct { const char * label; // name of this state LED::led_state_t ledState; // flashing pattern for the aartLED. Zie ook https://wiki.makerspaceleiden.nl/mediawiki/index.php/Powernode_1.1. time_t maxTimeInMilliSeconds; // how long we can stay in this state before we timeout. machinestates_t failStateOnTimeout; // what state we transition to on timeout. unsigned long timeInState; unsigned long timeoutTransitions; unsigned long autoReportCycle; } state[OVENOFF + 1] = { { "Booting", LED::LED_ERROR, 120 * 1000, REBOOT, 0 }, { "Out of order", LED::LED_ERROR, 120 * 1000, REBOOT, 5 * 60 * 1000 }, { "Rebooting", LED::LED_ERROR, 120 * 1000, REBOOT, 0 }, { "Transient Error", LED::LED_ERROR, 5 * 1000, WAITINGFORCARD, 5 * 60 * 1000 }, { "No network", LED::LED_FLASH, NEVER, NOCONN, 0 }, { "Waiting for card", LED::LED_IDLE, NEVER, WAITINGFORCARD, 0 }, { "Checking card", LED::LED_PENDING, 5 * 1000, WAITINGFORCARD, 0 }, { "Clear status", LED::LED_PENDING, NEVER, WAITINGFORCARD, 0 }, { "Approved card", LED::LED_PENDING, 60 * 1000, CLEARSTATUS, 0 }, { "Rejected", LED::LED_ERROR, 5 * 1000, CLEARSTATUS, 0 }, { "Device(s) switched on", LED::LED_ON, MAX_OVEN_ON_TIME * 3600 * 1000, OVENOFF, 0 }, { "Switch oven off", LED::LED_ON, NEVER, WAITINGFORCARD, 0 }, }; enum messID { e_Beat = 1, e_Prev, e_Next, e_On, e_Off }; enum displayMessageID { e_BeatAnswer = 1, e_CurrentSchedule, e_ScheduleName, e_CurrentSegment, e_Mode, e_Goal, e_TimeLeft, e_Empty, e_IsOn, e_IsOff, e_Fault, e_Solved, e_OvenTemp, e_Authenticate, e_ClearMessage, e_Status }; unsigned long laststatechange = 0, lastReport = 0; static machinestates_t laststate = OUTOFORDER; machinestates_t machinestate = BOOTING; // to handle onconnect only once (only after reboot) static bool firstOnConnectTime = true; PIDController * _OvenController; char reportStr[128]; ESP32WebServer myWebServer(80); unsigned long wattPulses = 0; bool kWhPinIsHigh = false; unsigned long startPinChange = 0; char messageReceived[SERIAL_MAXLINELENGTH]; bool firstTimeSerialBeatReceived = true; char tmpStr[255]; unsigned long displayUpdateStartTime = 0; int prevSchedule = -1; int prevSegment = -1; bool clearMessageSent = false; bool thermoCoupleFault = false; void updateDisplayTop() { String tmpStr; char resultStr[SERIAL_MAXLINELENGTH]; if (prevSchedule != _OvenController->getSelectedSchedule()) { prevSchedule = _OvenController->getSelectedSchedule(); prevSegment = -1; sprintf(resultStr, "%d:%d", e_CurrentSchedule, _OvenController->getSelectedSchedule()); Serial2.println(resultStr); tmpStr = _OvenController->getScheduleName(); sprintf(resultStr, "%d:%s", e_ScheduleName, tmpStr.c_str()); Serial2.println(resultStr); if (_OvenController->getScheduleIsEmpty()) { sprintf(resultStr, "%d", e_Empty); Serial2.println(resultStr); } else { sprintf(resultStr, "%d", e_ClearMessage); Serial2.println(resultStr); } } } void updateDisplayBottom() { String tmpStr; char resultStr[SERIAL_MAXLINELENGTH]; if ((machinestate == OVENON) || _OvenController->ovenIsSwitchedOn()) { if (prevSegment != _OvenController->getCurrentSegment()) { prevSegment = _OvenController->getCurrentSegment(); sprintf(resultStr, "%d:%d", e_CurrentSegment, _OvenController->getCurrentSegment()); Serial2.println(resultStr); sprintf(resultStr, "%d:%s", e_Mode, _OvenController->getCurrentMode().c_str()); Serial2.println(resultStr); sprintf(resultStr, "%d:%d", e_Goal, (int)_OvenController->getCurrentGoal()); Serial2.println(resultStr); clearMessageSent = false; } sprintf(resultStr, "%d:%lu", e_TimeLeft, _OvenController->getTimeLeft()); Serial2.println(resultStr); } else { if (!clearMessageSent) { sprintf(resultStr, "%d", e_ClearMessage); Serial2.println(resultStr); clearMessageSent = true; } } } void decodeMessageReceived(int messageID) { //String tmpStr; char resultStr[SERIAL_MAXLINELENGTH]; switch (messageID) { case e_Beat: // BEAT received, answer with BEAT sprintf(resultStr, "%d", e_BeatAnswer); Serial2.println(resultStr); if (firstTimeSerialBeatReceived) { firstTimeSerialBeatReceived = false; updateDisplayTop(); } break; case e_Prev: // Select previous schedule // Check if oven is switched off if ((machinestate == OVENON) || _OvenController->ovenIsSwitchedOn()) { // skip message } else { _OvenController->selectSchedule(false); updateDisplayTop(); } break; case e_Next: // Select next schedule //Check if oven is switched off if ((machinestate == OVENON) || _OvenController->ovenIsSwitchedOn()) { // skip message } else { _OvenController->selectSchedule(true); updateDisplayTop(); } break; case e_On: // Switch oven on (if needed/possible) // Check if oven is already on if ((machinestate == OVENON) || _OvenController->ovenIsSwitchedOn()) { // skip request, oven is already on return; } // Check if schedule is empty if (_OvenController->getScheduleIsEmpty()) { sprintf(resultStr, "%d", e_Empty); Serial2.println(resultStr); return; } // Check if user is approved if (machinestate != APPROVED) { sprintf(resultStr, "%d", e_Authenticate); Serial2.println(resultStr); return; } // Switch oven on _OvenController->switchOvenOn(); sprintf(resultStr, "%d", e_IsOn); Serial2.println(resultStr); sprintf(resultStr, "%d:0", e_Status); // clear status Serial2.println(resultStr); machinestate = OVENON; prevSegment = -1; updateDisplayBottom(); break; case e_Off: // switch oven off _OvenController->switchOvenOff(); sprintf(resultStr, "%d", e_IsOff); Serial2.println(resultStr); machinestate = WAITINGFORCARD; sprintf(resultStr, "%d:0", e_Status); // clear status Serial2.println(resultStr); clearMessageSent = false; updateDisplayBottom(); break; } } void readSerial2() { if (Serial2.available()) { //memset(messageReceived, 0, sizeof(messageReceived)); while (Serial2.available()) { int len = Serial2.readBytesUntil('\n', messageReceived, SERIAL_MAXLINELENGTH - 1); messageReceived[len] = 0; #ifdef DEBUGIT // Serial.printf("Message received: %s\n\r", messageReceived); #endif int messageId = atoi(messageReceived); decodeMessageReceived(messageId); } } } void displayLoop() { if ((millis() - displayUpdateStartTime) > DISPLAY_UPDATE_INTERVAL) { displayUpdateStartTime = millis(); if ((machinestate == OVENON) || _OvenController->ovenIsSwitchedOn()) { updateDisplayBottom(); } else { updateDisplayTop(); } double currentOvenTemp = _OvenController->getThermoCoupleTemp(); if ((currentOvenTemp > -300) && !_OvenController->getTempFault()) { sprintf(tmpStr, "%d:%d", e_OvenTemp, (int)currentOvenTemp); Serial2.println(tmpStr); if (thermoCoupleFault) { sprintf(tmpStr, "%d", e_Solved); Serial2.println(tmpStr); thermoCoupleFault = false; } } else { if (_OvenController->getTempFault()) { if (!thermoCoupleFault) { thermoCoupleFault = true; sprintf(tmpStr, "%d", e_Fault); Serial2.println(tmpStr); } } } } } void countkWhPulses() { int currentPinValue = 0; currentPinValue = digitalRead(KWH_METER_PIN); if (( currentPinValue == HIGH) && !kWhPinIsHigh && (millis() - startPinChange) > 50) { startPinChange = millis(); wattPulses++; kWhPinIsHigh = true; } else { if ((currentPinValue == LOW) && kWhPinIsHigh && (millis() - startPinChange) > 50) { startPinChange = millis(); kWhPinIsHigh = false; } } } void checkClearEEPromAndCacheButtonPressed(void) { unsigned long ButtonPressedTime; unsigned long currentSecs; unsigned long prevSecs; bool firstTime = true; // check CLEAR_EEPROM_AND_CACHE_BUTTON pressed pinMode(CLEAR_EEPROM_AND_CACHE_BUTTON, INPUT); // check if button is pressed for at least 3 s Log.println("Checking if the button is pressed for clearing EEProm and cache"); ButtonPressedTime = millis(); prevSecs = MAX_WAIT_TIME_BUTTON_PRESSED / 1000; Log.print(prevSecs); Log.print(" s"); while (digitalRead(CLEAR_EEPROM_AND_CACHE_BUTTON) == CLEAR_EEPROM_AND_CACHE_BUTTON_PRESSED) { if ((millis() - ButtonPressedTime) >= MAX_WAIT_TIME_BUTTON_PRESSED) { if (firstTime == true) { Log.print("\rPlease release button"); firstTime = false; } } else { currentSecs = (MAX_WAIT_TIME_BUTTON_PRESSED - millis()) / 1000; if ((currentSecs != prevSecs) && (currentSecs >= 0)) { Log.print("\r"); Log.print(currentSecs); Log.print(" s"); prevSecs = currentSecs; } } } if (millis() - ButtonPressedTime >= MAX_WAIT_TIME_BUTTON_PRESSED) { Log.print("\rButton for clearing EEProm and cache was pressed for more than "); Log.print(MAX_WAIT_TIME_BUTTON_PRESSED / 1000); Log.println(" s, EEProm and Cache will be cleared!"); // Clear EEPROM EEPROM.begin(1024); wipe_eeprom(); Log.println("EEProm cleared!"); // Clear cache prepareCache(true); Log.println("Cache cleared!"); // wait until button is released, than reboot while (digitalRead(CLEAR_EEPROM_AND_CACHE_BUTTON) == CLEAR_EEPROM_AND_CACHE_BUTTON_PRESSED) { // do nothing here } Log.println("Node will be restarted"); // restart node ESP.restart(); } else { Log.println("\rButton was not (or not long enough) pressed to clear EEProm and cache"); } } int inputIsHigh = 0; void handleNotFound() { myWebServer.send(404, "text/plain", "404: Not found"); // Send HTTP status 404 (Not Found) when there's no handler for the URI in the request } void setup() { Serial.begin(115200); Serial.println("\n\n\n"); Serial.println("Booted: " __FILE__ " " __DATE__ " " __TIME__ ); Serial2.begin(SERIAL2_BAUDRATE, SERIAL_8N1, SERIAL_RX_PIN, SERIAL_TX_PIN); Serial2.setRxBufferSize(256); Serial2.flush(); sprintf(tmpStr, "%d:1", e_Status); // Please wait, controller is starting Serial2.println(tmpStr); pinMode(KWH_METER_PIN, INPUT); checkClearEEPromAndCacheButtonPressed(); _OvenController = new PIDController(); _OvenController->begin(SOLID_STATE_RELAIS_PIN, FAN_PIN, SIGNAL_LAMP_PIN); node.set_mqtt_prefix("ac"); node.set_master("master"); node.onConnect([]() { Log.println("Connected"); if (firstOnConnectTime == true) { _OvenController->setUserIsApproved(false); firstOnConnectTime = false; machinestate = WAITINGFORCARD; } }); node.onDisconnect([]() { Log.println("Disconnected"); // machinestate = NOCONN; }); node.onError([](acnode_error_t err) { Log.printf("Error %d\n", err); _OvenController->setUserIsApproved(false); machinestate = WAITINGFORCARD; }); node.onApproval([](const char * machine) { char resultStr2[SERIAL_MAXLINELENGTH]; Debug.print("Got approve for machine: "); Debug.println(machine); if (machinestate == WAITINGFORCARD) { _OvenController->setUserIsApproved(true); sprintf(resultStr2, "%d:2", e_Status); // User authenticated Serial2.println(resultStr2); sprintf(resultStr2, "%d", e_ClearMessage); Serial2.println(resultStr2); machinestate = APPROVED; Log.println("User is approved and is now allowed to switch the oven on"); } }); node.onDenied([](const char * machine) { char resultStr3[SERIAL_MAXLINELENGTH]; Debug.println("Got denied"); if (machinestate > REJECTED) { Debug.println("Denied ingnored, oven is already in use"); } else { machinestate = REJECTED; _OvenController->setUserIsApproved(false); sprintf(resultStr3, "%d:3", e_Status); // User denied Serial2.println(resultStr3); } }); node.set_report_period(20 * 1000); node.onReport([](JsonObject & report) { report["state"] = state[machinestate].label; if (_OvenController->getAllowPidControllerIsOn()) { report["ovencontroller"] = "enabled"; } else { report["ovencontroller"] = "disabled"; } if (_OvenController->getSSRIsOn()) { report["Solid State Relais"] = "switched on"; } else { report["Solid State Relais"] = "switched off"; } _OvenController->measureOvenTemps(); if (_OvenController->getTempFault()) { report["Thermocouple"] = "error detected"; } else { report["Thermocouple"] = "working OK"; if (_OvenController->getValidTemps()) { sprintf(reportStr, "Internal temperature node = %6.1f degrees Celcius", _OvenController->getInternalTemp()); report["Thermocouple"] = reportStr; sprintf(reportStr, "Oven temperature = %6.1f degrees Celcius", _OvenController->getThermoCoupleTemp()); report["Thermocouple"] = reportStr; } else { report["Thermocouple"] = "No valid temperature readings available"; } } #ifdef OTA_PASSWD report["ota"] = true; #else report["ota"] = false; #endif }); reader.onSwipe([](const char * tag) -> ACBase::cmd_result_t { // avoid swithing messing with the swipe process if (machinestate > CHECKINGCARD) { Debug.printf("Ignoring a normal swipe - as we're still in some open process."); return ACBase::CMD_CLAIMED; } // We'r declining so that the core library handle sending // an approval request, keep state, and so on. // Debug.printf("Detected a normal swipe.\n"); // buzz = CHECK; return ACBase::CMD_DECLINE; }); // This reports things such as FW version of the card; which can 'wedge' it. So we // disable it unless we absolutely positively need that information. // reader.set_debug(false); node.addHandler(&reader); #ifdef OTA_PASSWD node.addHandler(&ota); #endif Log.addPrintStream(std::make_shared<MqttLogStream>(mqttlogStream)); auto t = std::make_shared<TelnetSerialStream>(telnetSerialStream); Log.addPrintStream(t); Debug.addPrintStream(t); // node.set_debug(true); // node.set_debugAlive(true); // if Olimex ESP32-PoE board is used #ifdef ESP32_PoE node.begin(BOARD_OLIMEX); #endif // if default, board (POESP, board Aart) is used #ifndef ESP32_PoE node.begin(); #endif // if FAN_PIN uses gpio0, this port must be (re-)initialized here, because // in the ethernet settings for the ethernet port in node.begin() gpio0 is used. // This switches this port to another mode. This use is not needed, because the PHY // for the internet port used on the ESP32-PoE is not the same as the one used in // the init procedure pinMode(FAN_PIN, OUTPUT); digitalWrite(FAN_PIN, 0); _OvenController->addToWebServer(myWebServer, "/", ROOTPAGE); _OvenController->addToWebServer(myWebServer, "/prev_schedule_page", PREVPAGE); _OvenController->addToWebServer(myWebServer, "/next_schedule_page", NEXTPAGE); _OvenController->addToWebServer(myWebServer, "/prev_select_schedule_page", PREVSELECTPAGE); _OvenController->addToWebServer(myWebServer, "/next_select_schedule_page", NEXTSELECTPAGE); // _OvenController->addToWebServer(myWebServer, "/select_schedule_page", SELECTSCHEDULEPAGE); _OvenController->addToWebServer(myWebServer, "/edit_schedules_page", EDITSCHEDULESPAGE); _OvenController->addToWebServer(myWebServer, "/action_page", ACTIONPAGE); #ifdef DEBUGIT _OvenController->addToWebServer(myWebServer, "/switch_oven_on_page", SWITCHOVENONPAGE); _OvenController->addToWebServer(myWebServer, "/switch_oven_off_page", SWITCHOVENOFFPAGE); #endif myWebServer.onNotFound(handleNotFound); // When a client requests an unknown URI (i.e. something other than "/"), call function "handleNotFound" myWebServer.begin(); Log.println("Webserver started"); sprintf(tmpStr, "%d:0", e_Status); // clear status Serial2.println(tmpStr); sprintf(tmpStr, "%d", e_IsOff); double currentOvenTemp = _OvenController->measureOvenTemps(); if (currentOvenTemp > -300) { sprintf(tmpStr, "%d:%d", e_OvenTemp, (int)currentOvenTemp); Serial2.println(tmpStr); } Log.println("Booted: " __FILE__ " " __DATE__ " " __TIME__ ); } void test_Loop() { int tmp = digitalRead(KWH_METER_PIN); if (tmp != inputIsHigh) { inputIsHigh = tmp; digitalWrite(SOLID_STATE_RELAIS_PIN, inputIsHigh); digitalWrite(SIGNAL_LAMP_PIN, inputIsHigh); digitalWrite(FAN_PIN, inputIsHigh); } } unsigned long startTime = 0; int test_State = 0; int state_duration = 60000; // i minute void test_Loop_PID() { if (startTime == 0) { startTime = millis(); _OvenController->setControllerOn(); _OvenController->setGoalOvenTemp(30, false); Log.println("PID test started (state 0): goal = 30 degrees Celsius"); } if ((millis() - startTime) > state_duration) { test_State++; if (test_State > 3) { test_State = 0; } switch (test_State) { case 0: _OvenController->setControllerOn(); _OvenController->setGoalOvenTemp(30, false); Log.println("PID test state 0: goal = 30 degrees Celsius"); break; case 1: _OvenController->setGoalOvenTemp(200, false); Log.println("PID test state 1: goal = 30 degrees Celsius"); break; case 2: _OvenController->setGoalOvenTemp(200, false); Log.println("PID test state 2: goal = 200 degrees Celsius"); break; case 3: _OvenController->setGoalOvenTemp(1000, false); Log.println("PID test state 3: goal = 1000 degrees Celsius"); break; default: break; } startTime = millis(); } } void loop() { node.loop(); readSerial2(); displayLoop(); myWebServer.handleClient(); _OvenController->PIDloop(); // test_Loop_PID(); _OvenController->scheduleLoop(); _OvenController->checkTemps(); countkWhPulses(); // test_Loop(); if (laststate != machinestate) { Debug.printf("Changed from state <%s> to state <%s>\n", state[laststate].label, state[machinestate].label); state[laststate].timeInState += (millis() - laststatechange) / 1000; laststate = machinestate; laststatechange = millis(); return; } if (state[machinestate].maxTimeInMilliSeconds != NEVER && ((millis() - laststatechange) > state[machinestate].maxTimeInMilliSeconds)) { state[machinestate].timeoutTransitions++; laststate = machinestate; machinestate = state[machinestate].failStateOnTimeout; Log.printf("Time-out; transition from <%s> to <%s>\n", state[laststate].label, state[machinestate].label); return; }; if (state[machinestate].autoReportCycle && \ (millis() - laststatechange) > state[machinestate].autoReportCycle && \ (millis() - lastReport) > state[machinestate].autoReportCycle) { Log.printf("State: %s now for %lu seconds", state[laststate].label, (millis() - laststatechange) / 1000); lastReport = millis(); }; // aartLed.set(state[machinestate].ledState); switch (machinestate) { case REBOOT: node.delayedReboot(); break; case WAITINGFORCARD: case CHECKINGCARD: break; case CLEARSTATUS: sprintf(tmpStr, "%d:0", e_Status); // Clear status Serial2.println(tmpStr); sprintf(tmpStr, "%d", e_ClearMessage); Serial2.println(tmpStr); machinestate = WAITINGFORCARD; break; case REJECTED: break; case APPROVED: if (_OvenController->ovenIsSwitchedOn()) { _OvenController->setUserIsApproved(false); sprintf(tmpStr, "%d:0", e_Status); // Clear status Serial2.println(tmpStr); machinestate = OVENON; sprintf(tmpStr, "%d", e_IsOn); Serial2.println(tmpStr); updateDisplayBottom(); wattPulses = 0; } break; case OVENON: // wait until schedule is ready if (_OvenController->ovenIsSwitchedOff()) { _OvenController->setUserIsApproved(false); machinestate = WAITINGFORCARD; sprintf(tmpStr, "%d", e_IsOff); Serial2.println(tmpStr); clearMessageSent = false; updateDisplayBottom(); Log.printf("Count watt pulses = %lu\n\r", wattPulses); Log.printf("Oven schedule ready, used energy = %7.3f kWh\n\r", (double)wattPulses / 1000); } break; case OVENOFF: _OvenController->switchOvenOff(); _OvenController->setUserIsApproved(false); Log.printf("Count watt pulses = %lu\n\r", wattPulses); Log.printf("Oven schedule ready, used energy = %7.3f kWh\n\r", (double)wattPulses / 1000); sprintf(tmpStr, "%d", e_IsOff); Serial2.println(tmpStr); clearMessageSent = false; updateDisplayBottom(); machinestate = WAITINGFORCARD; break; case BOOTING: case OUTOFORDER: case TRANSIENTERROR: case NOCONN: break; }; }
30.349091
153
0.66419
[ "solid" ]
f65a88b80394d0ee0d54f35f4e75d9a08269ec2c
2,840
hxx
C++
Modules/Core/Transform/include/itkTransformGeometryImageFilter.hxx
ferdymercury/ITK
b0a86ded2edd698a6f4a3e58a9db23523a7eb871
[ "Apache-2.0" ]
2
2021-02-01T17:24:16.000Z
2021-02-02T02:18:46.000Z
Modules/Core/Transform/include/itkTransformGeometryImageFilter.hxx
ferdymercury/ITK
b0a86ded2edd698a6f4a3e58a9db23523a7eb871
[ "Apache-2.0" ]
4
2019-02-08T21:13:11.000Z
2019-02-18T20:57:34.000Z
Modules/Core/Transform/include/itkTransformGeometryImageFilter.hxx
ferdymercury/ITK
b0a86ded2edd698a6f4a3e58a9db23523a7eb871
[ "Apache-2.0" ]
4
2015-02-07T05:09:14.000Z
2019-10-08T09:17:30.000Z
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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. * *=========================================================================*/ #ifndef itkTransformGeometryImageFilter_hxx #define itkTransformGeometryImageFilter_hxx #include "itkCastImageFilter.h" namespace itk { template <typename TInputImage, typename TOutputImage> TransformGeometryImageFilter<TInputImage, TOutputImage>::TransformGeometryImageFilter() { Self::SetPrimaryInputName("InputImage"); // "RigidTransform" required ( not numbered ) Self::AddRequiredInputName("Transform"); } template <typename TInputImage, typename TOutputImage> void TransformGeometryImageFilter<TInputImage, TOutputImage>::VerifyPreconditions() ITKv5_CONST { Superclass::VerifyPreconditions(); TransformConstPointer tx = this->GetTransform(); if (!tx->IsLinear()) { itkExceptionMacro(<< "Transform set to non-linear transform of type: " << tx->GetNameOfClass()); } } template <typename TInputImage, typename TOutputImage> void TransformGeometryImageFilter<TInputImage, TOutputImage>::GenerateOutputInformation() { Superclass::GenerateOutputInformation(); OutputImageType * outputPtr = this->GetOutput(); TransformConstPointer tx = this->GetTransform(); tx->ApplyToImageMetadata(outputPtr); } template <typename TInputImage, typename TOutputImage> void TransformGeometryImageFilter<TInputImage, TOutputImage>::GenerateData() { if (this->GetRunningInPlace()) { // No need to copy the bulk data return; } OutputImageType * output = this->GetOutput(); auto input = InputImageType::New(); input->Graft(const_cast<InputImageType *>(this->GetInput())); // SEE HEADER FILE FOR MATH DESCRIPTION /** make a cast copied version of the input image **/ using DuplicatorType = CastImageFilter<InputImageType, OutputImageType>; auto castFilter = DuplicatorType::New(); castFilter->SetInput(input); castFilter->GraftOutput(this->GetOutput()); castFilter->Update(); // Can't use graft as it will overwrite the new meta-data output->SetPixelContainer(castFilter->GetOutput()->GetPixelContainer()); output->SetBufferedRegion(castFilter->GetOutput()->GetBufferedRegion()); } } // end namespace itk #endif
28.686869
100
0.71162
[ "transform" ]
f65abf42057ad50ba5bd18eba0b69cac08aeddf3
41,727
cpp
C++
DX11Starter/DX11Starter/Renderer.cpp
mray2014/CosmicEngine
e2255251041b1466d9ba1465926369baa5a91c9a
[ "MIT" ]
null
null
null
DX11Starter/DX11Starter/Renderer.cpp
mray2014/CosmicEngine
e2255251041b1466d9ba1465926369baa5a91c9a
[ "MIT" ]
null
null
null
DX11Starter/DX11Starter/Renderer.cpp
mray2014/CosmicEngine
e2255251041b1466d9ba1465926369baa5a91c9a
[ "MIT" ]
null
null
null
#include "Renderer.h" #include "WICTextureLoader.h" #include "DDSTextureLoader.h" // https://www.gamedev.net/forums/topic/644740-dx11-multiple-render-targets/ Renderer::Renderer() { } Renderer::Renderer(Camera * c, ID3D11Device * dev, ID3D11DeviceContext * con, ID3D11RenderTargetView* backB, ID3D11DepthStencilView* depthS, IDXGISwapChain* sw) { cam = c; device = dev; context = con; backBufferRTV = backB; depthStencilView = depthS; swap = sw; assets = new AssetManager(dev, con); assets->GetMesh("BackGroundTile")->instanceThreshold = 1000; assets->GetMesh("Worlds")->instanceThreshold = 1000; Init(); InitSkyBox(); SetWireFrame(); //CreateRenderTargets(); } Renderer::~Renderer() { /*for (auto& x : meshStorage) { if (x.second) { delete x.second; x.second = nullptr; } } for (auto& x : surTextStorage) { if (x.second) { delete x.second; x.second = nullptr; } } for (auto& x : norTextStorage) { if (x.second) { delete x.second; x.second = nullptr; } } for (auto& x : skyTextStorage) { if (x.second) { delete x.second; x.second = nullptr; } }*/ if (assets != nullptr) { delete assets; assets = nullptr; } for(unsigned int i = 0; i < allLights.size(); i++) { if (allLights[i] != nullptr) { delete allLights[i]; allLights[i] = nullptr; } } allLights.clear(); directionalLights.clear(); pointLights.clear(); spotLights.clear(); delete vertexFShader; delete instanceFVShader; delete vertexDShader; delete instanceDVShader; delete skyVShader; delete quadVShader; delete canvasVShader; delete particleVShader; delete pixelFShader; delete pixelFSShader; delete pixelFSNShader; delete pixelDShader; delete pLightingShader; delete skyPShader; delete bloomShader; delete hdrShader; delete canvasPShader; delete canvasPTShader; delete particlePShader; delete[] localInstanceData; instanceWorldMatrixBuffer->Release(); addBlendState->Release(); subBlendState->Release(); cutBlendState->Release(); particleDepthState->Release(); if (wireFrame != nullptr) { wireFrame->Release(); wireFrame = nullptr; } if (fillFrame != nullptr) { fillFrame->Release(); fillFrame = nullptr; } //if (skyBoxSVR != nullptr) { skyBoxSVR->Release(); skyBoxSVR = nullptr; } if (textureSample != nullptr) { textureSample->Release(); textureSample = nullptr; } if (sample != nullptr) { sample->Release(); sample = nullptr; } if (skyRast != nullptr) { skyRast->Release(); skyRast = nullptr; } if (skyDepth != nullptr) { skyDepth->Release(); skyDepth = nullptr; } } void Renderer::Init() { instanceRenderingOn = true; defferedRenderingOn = false; HdrOn = false; BloomOn = false; wireFrameOn = false; skyBoxOn = true; prevWireStatus = wireFrameOn; skyBoxNum = 1; LoadShaders(); sunLight = CreateDirectionalLight({0.0f,-1.0f,0.0f }); //sunLight->ligComponent->lightColor = { 0.05f, 0.5f, 0.0f, 1.0f }; sunLight->ligComponent->lightAmb = {0.2f, 0.2f, 0.2f, 1.0f}; maxSize = 10; D3D11_SAMPLER_DESC tDes = {}; tDes.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; tDes.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; tDes.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; tDes.Filter = D3D11_FILTER_ANISOTROPIC; tDes.MaxAnisotropy = 16; tDes.MaxLOD = D3D11_FLOAT32_MAX; device->CreateSamplerState(&tDes, &textureSample); D3D11_RASTERIZER_DESC fillDesc; fillDesc.FillMode = D3D11_FILL_SOLID; fillDesc.CullMode = D3D11_CULL_FRONT; fillDesc.FrontCounterClockwise = true; fillDesc.DepthBias = 0; fillDesc.DepthBiasClamp = 0.0f; fillDesc.SlopeScaledDepthBias = 0.0f; fillDesc.DepthClipEnable = true; fillDesc.ScissorEnable = false; fillDesc.MultisampleEnable = false; fillDesc.AntialiasedLineEnable = false; device->CreateRasterizerState(&fillDesc, &fillFrame); D3D11_RASTERIZER_DESC wireDesc; wireDesc.FillMode = D3D11_FILL_WIREFRAME; wireDesc.CullMode = D3D11_CULL_FRONT; wireDesc.FrontCounterClockwise = true; wireDesc.DepthBias = 0; wireDesc.DepthBiasClamp = 0.0f; wireDesc.SlopeScaledDepthBias = 0.0f; wireDesc.DepthClipEnable = true; wireDesc.ScissorEnable = false; wireDesc.MultisampleEnable = false; wireDesc.AntialiasedLineEnable = false; device->CreateRasterizerState(&wireDesc, &wireFrame); // The number of instances to draw with a single draw call // Code in Update() assumes this is a perfect cube (N*N*N) numInstances = 1500; // Create the local buffer to hold our data before copying // it to the GPU localInstanceData = new InstanceData[numInstances]; // Set up a new vertex buffer that will hold our // PER-INSTANCE data. From this code, the description // looks about the same as other ones. How we use it // and how the shader interprets it differ though! // It needs to be dynamic so we can put new data in // at run time D3D11_BUFFER_DESC instDesc = {}; instDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; instDesc.ByteWidth = sizeof(InstanceData) * numInstances; instDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; instDesc.MiscFlags = 0; instDesc.StructureByteStride = 0; instDesc.Usage = D3D11_USAGE_DYNAMIC; device->CreateBuffer(&instDesc, 0, &instanceWorldMatrixBuffer); // A depth state for the particles D3D11_DEPTH_STENCIL_DESC dsDesc = {}; dsDesc.DepthEnable = true; dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; // Turns off depth writing dsDesc.DepthFunc = D3D11_COMPARISON_LESS; device->CreateDepthStencilState(&dsDesc, &particleDepthState); // Blend for particles (additive) D3D11_BLEND_DESC addblend = {}; addblend.AlphaToCoverageEnable = false; addblend.IndependentBlendEnable = false; addblend.RenderTarget[0].BlendEnable = true; addblend.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; addblend.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; addblend.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; addblend.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; addblend.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; addblend.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE; addblend.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; device->CreateBlendState(&addblend, &addBlendState); // Blend for particles (subtract) D3D11_BLEND_DESC subblend = {}; subblend.AlphaToCoverageEnable = false; subblend.IndependentBlendEnable = false; subblend.RenderTarget[0].BlendEnable = true; subblend.RenderTarget[0].BlendOp = D3D11_BLEND_OP_SUBTRACT; subblend.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; subblend.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; subblend.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; subblend.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; subblend.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE; subblend.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; device->CreateBlendState(&subblend, &subBlendState); D3D11_BLEND_DESC cutblend = {}; cutblend.AlphaToCoverageEnable = false; cutblend.IndependentBlendEnable = false; cutblend.RenderTarget[0].BlendEnable = true; cutblend.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; cutblend.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;; cutblend.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; cutblend.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; cutblend.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; cutblend.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; cutblend.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; device->CreateBlendState(&cutblend, &cutBlendState); } void Renderer::Render(float dt) { if (wireFrameOn != prevWireStatus) { SetWireFrame(); } //////////////////////////////////////// //CLEARING SCREEN //////////////////////////////////////// const float color[4] = { 0.4f, 0.6f, 0.75f, 0.0f }; context->ClearRenderTargetView(backBufferRTV, color); context->ClearDepthStencilView( depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); //////////////////////////////////////// //Compiling Lights //////////////////////////////////////// CompileLights(); //////////////////////////////////////// //DRAWING OBJECTS TO SCREEN //////////////////////////////////////// for (auto& x : assets->meshStorage) { if (!x.second->broken && x.second->inUse) { if (x.second->canInstRender && instanceRenderingOn) { unsigned int count = 0; for(unsigned int i = 0; i < x.second->rendComponents->size(); i++) { if (x.second->rendComponents->at(i)->canRender) { if (x.second->rendComponents->at(i)->mat.materialType != Material::Transulcent) { XMStoreFloat4x4(&localInstanceData[count].worldMat, XMLoadFloat4x4(&x.second->rendComponents->at(i)->worldMat)); XMStoreFloat4x4(&localInstanceData[count].invTrans, XMLoadFloat4x4(&x.second->rendComponents->at(i)->worldInvTrans)); XMStoreFloat4(&localInstanceData[count].color, XMLoadFloat4(&x.second->rendComponents->at(i)->mat.surfaceColor)); count++; } } } if(defferedRenderingOn) { DrawDInstance(x.second->meshName, localInstanceData, count); } else { DrawFInstance(x.second->meshName, localInstanceData, count); } } else { for (unsigned int i = 0; i < x.second->rendComponents->size(); i++) { if (x.second->rendComponents->at(i)->canRender) { if (x.second->rendComponents->at(i)->mat.materialType != Material::Transulcent) { if (defferedRenderingOn) { DrawDefferedPass(x.second->rendComponents->at(i)); } else { DrawForwardPass(x.second->rendComponents->at(i)); } } } } } } } //////////////////////////////////////// //DRAWING SKY BOX //////////////////////////////////////// if(skyBoxOn) { DrawSkyBox(); } DrawEmiters(); //////////////////////////////////////// //POST PROCESSING //////////////////////////////////////// // Deffered rendering lighting pass // if(defferedRenderingOn) { /*Insert code here*/ } // Drawing translucent objects with forward rendering float blend[4] = { 1,1,1,1 }; context->OMSetDepthStencilState(particleDepthState, 0); context->OMSetBlendState(cutBlendState, blend, 0xFFFFFFFF); // Additive blending for (unsigned int i = 0; i < transRendComponents.size(); i++) { if (transRendComponents[i]->canRender) { DrawForwardPass(transRendComponents[i]); } } context->OMSetBlendState(0, blend, 0xffffffff); context->OMSetDepthStencilState(0, 0); // HDR // if (HdrOn) { /*Insert code here*/ } // Bloom // if (BloomOn) { /*Insert code here*/ } DrawCanvas(); // Present the back buffer to the user // - Puts the final frame we're drawing into the window so the user can see it // - Do this exactly ONCE PER FRAME (always at the very end of the frame) } void Renderer::CreateRenderTargets() { // The above function created the back buffer render target // for us, but we need a reference to it ID3D11Texture2D* colorTexture; swap->GetBuffer( 1, __uuidof(ID3D11Texture2D), (void**)&colorTexture); // Now that we have the texture, create a render target view // for the back buffer so we can render into it. Then release // our local reference to the texture, since we have the view. device->CreateRenderTargetView( colorTexture, 0, &colorRTV); colorTexture->Release(); //================================================================================== // //================================================================================== D3D11_TEXTURE2D_DESC worldTextDesc = {}; worldTextDesc.Width = cam->width; worldTextDesc.Height = cam->height; worldTextDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; worldTextDesc.MipLevels = 1; worldTextDesc.ArraySize = 1; worldTextDesc.SampleDesc.Count = 1; worldTextDesc.Usage = D3D11_USAGE_DEFAULT; worldTextDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; worldTextDesc.CPUAccessFlags = 0; worldTextDesc.MiscFlags = 0; ID3D11Texture2D* worldTexture; /*swap->GetBuffer( 2, __uuidof(ID3D11Texture2D), (void**)&worldTexture);*/ device->CreateTexture2D(&worldTextDesc, NULL, &worldTexture); device->CreateRenderTargetView( worldTexture, 0, &worldRTV); worldTexture->Release(); //================================================================================== // //================================================================================== ID3D11Texture2D* normalTexture; swap->GetBuffer( 3, __uuidof(ID3D11Texture2D), (void**)&normalTexture); device->CreateRenderTargetView( normalTexture, 0, &normalRTV); normalTexture->Release(); } //void Renderer::LoadMesh(Mesh * newMesh)//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //{ // meshStorage[newMesh->meshName] = newMesh; //} // //Mesh * Renderer::GetMesh(std::string name) //{ // return meshStorage.find(name)->second; //} void Renderer::PushToRenderer(RenderingComponent * com) { com->rendID = (unsigned int)assets->meshStorage[com->meshName]->rendComponents->size(); if (com->mat.materialType == Material::Transulcent) { PushToTranslucent(com); } assets->meshStorage[com->meshName]->rendComponents->push_back(com); assets->meshStorage[com->meshName]->instances++; assets->meshStorage[com->meshName]->inUse = assets->meshStorage[com->meshName]->instances != 0 ? true : false; assets->meshStorage[com->meshName]->canInstRender = assets->meshStorage[com->meshName]->instances >= assets->meshStorage[com->meshName]->instanceThreshold ? true : false; } void Renderer::PushToTranslucent(RenderingComponent * com) { com->mat.translucentID = (unsigned int)transRendComponents.size(); transRendComponents.push_back(com); } void Renderer::PushToCanvas(RenderingComponent * com) { com->rendID = (unsigned int)canvasRendComponents.size(); canvasRendComponents.push_back(com); } void Renderer::PushToEmitter(Emitter * emit) { emit->emitterID = (unsigned int)particleEmitters.size(); particleEmitters.push_back(emit); } void Renderer::Flush() { for (auto& x : assets->meshStorage) { if(x.second->inUse) { x.second->rendComponents->clear(); x.second->instances = 0; x.second->canInstRender = false; } } transRendComponents.clear(); canvasRendComponents.clear(); particleEmitters.clear(); for (unsigned int i = 0; i < allLights.size(); i++) { if (allLights[i] != nullptr) { delete allLights[i]; allLights[i] = nullptr; } } allLights.clear(); directionalLights.clear(); pointLights.clear(); spotLights.clear(); sunLight = CreateDirectionalLight({ 0.0f,-1.0f,0.0f }); //sunLight->ligComponent->lightColor = { 0.05f, 0.5f, 0.0f, 1.0f }; sunLight->ligComponent->lightAmb = { 0.2f, 0.2f, 0.2f, 1.0f }; } #pragma region Light Stuff Light * Renderer::CreateLight(Light::LightType lType) { if (allLights.size() == (maxDLights + maxPLights + maxSLights)) { return nullptr; printf("ERROR: Could not create new light.\nReason: Maximum capacity"); } Light* newLight = new Light(); if (lType == Light::Directional) { newLight->lightID = (unsigned int)allLights.size(); newLight->compID = (unsigned int)directionalLights.size(); allLights.push_back(newLight); directionalLights.push_back(Light::LightComponent()); newLight->ligComponent = &directionalLights[newLight->compID]; newLight->lightType = Light::Directional; newLight->lightOn = true; newLight->ligComponent->lightDir = { 1.0f, -1.0f, 0.0f }; newLight->ligComponent->lightColor = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightAmb = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightIntensity = 4.0f; } else if(lType == Light::Point) { newLight->lightID = (unsigned int)allLights.size(); newLight->compID = (unsigned int)pointLights.size(); allLights.push_back(newLight); pointLights.push_back(Light::LightComponent()); newLight->ligComponent = &pointLights[newLight->compID]; newLight->lightType = Light::Point; newLight->lightOn = true; newLight->ligComponent->lightPos = { 0.0f, 0.0f, 0.0f }; newLight->ligComponent->lightColor = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightAmb = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightIntensity = 4.0f; } else if(lType == Light::Spot) { newLight->lightID = (unsigned int)allLights.size(); newLight->compID = (unsigned int)spotLights.size(); allLights.push_back(newLight); spotLights.push_back(Light::LightComponent()); newLight->ligComponent = &spotLights[newLight->compID]; newLight->lightType = Light::Spot; newLight->lightOn = true; newLight->ligComponent->lightPos = { 0.0f, 0.0f, 0.0f }; newLight->ligComponent->lightColor = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightAmb = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightIntensity = 4.0f; } return newLight; } Light * Renderer::CreateDirectionalLight(DirectX::XMFLOAT3 direction) { if (directionalLights.size() == maxDLights) { return nullptr; printf("ERROR: Could not create new light.\nReason: Maximum capacity"); } Light* newLight = new Light(); newLight->lightID = (unsigned int)allLights.size(); newLight->compID = (unsigned int)directionalLights.size(); allLights.push_back(newLight); directionalLights.push_back(Light::LightComponent()); newLight->ligComponent = &directionalLights[newLight->compID]; newLight->lightType = Light::Directional; newLight->lightOn = true; newLight->ligComponent->lightDir = direction; newLight->ligComponent->lightColor = {0.5f, 0.5f, 0.5f, 0.5f}; newLight->ligComponent->lightAmb = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightIntensity = 4.0f; return newLight; } Light * Renderer::CreateDirectionalLight(DirectX::XMFLOAT3 direction, DirectX::XMFLOAT4 ligColor) { if (directionalLights.size() == maxDLights) { return nullptr; printf("ERROR: Could not create new light.\nReason: Maximum capacity"); } Light* newLight = new Light(); newLight->lightID = (unsigned int)allLights.size(); newLight->compID = (unsigned int)directionalLights.size(); allLights.push_back(newLight); directionalLights.push_back(Light::LightComponent()); newLight->ligComponent = &directionalLights[newLight->compID]; newLight->lightType = Light::Directional; newLight->lightOn = true; newLight->ligComponent->lightDir = direction; newLight->ligComponent->lightColor = ligColor; newLight->ligComponent->lightAmb = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightIntensity = 4.0f; return newLight; } Light * Renderer::CreateDirectionalLight(DirectX::XMFLOAT3 direction, DirectX::XMFLOAT4 ligColor, float inten) { if (directionalLights.size() == maxDLights) { return nullptr; printf("ERROR: Could not create new light.\nReason: Maximum capacity"); } Light* newLight = new Light(); newLight->lightID = (unsigned int)allLights.size(); newLight->compID = (unsigned int)directionalLights.size(); allLights.push_back(newLight); directionalLights.push_back(Light::LightComponent()); newLight->ligComponent = &directionalLights[newLight->compID]; newLight->lightType = Light::Directional; newLight->lightOn = true; newLight->ligComponent->lightDir = direction; newLight->ligComponent->lightColor = ligColor; newLight->ligComponent->lightIntensity = inten; newLight->ligComponent->lightAmb = { 0.5f, 0.5f, 0.5f, 0.5f }; return newLight; } Light * Renderer::CreatePointLight(DirectX::XMFLOAT3 position) { if (pointLights.size() == maxPLights) { return nullptr; printf("ERROR: Could not create new light.\nReason: Maximum capacity"); } Light* newLight = new Light(); newLight->lightID = (unsigned int)allLights.size(); newLight->compID = (unsigned int)pointLights.size(); allLights.push_back(newLight); pointLights.push_back(Light::LightComponent()); newLight->ligComponent = &pointLights[newLight->compID]; newLight->lightType = Light::Point; newLight->lightOn = true; newLight->ligComponent->lightPos = position; newLight->ligComponent->lightColor = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightAmb = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightIntensity = 4.0f; return newLight; } Light * Renderer::CreatePointLight(DirectX::XMFLOAT3 position, DirectX::XMFLOAT4 ligColor) { if (pointLights.size() == maxPLights) { return nullptr; printf("ERROR: Could not create new light.\nReason: Maximum capacity"); } Light* newLight = new Light(); newLight->lightID = (unsigned int)allLights.size(); newLight->compID = (unsigned int)pointLights.size(); allLights.push_back(newLight); pointLights.push_back(Light::LightComponent()); newLight->ligComponent = &pointLights[newLight->compID]; newLight->lightType = Light::Point; newLight->lightOn = true; newLight->ligComponent->lightPos = position; newLight->ligComponent->lightColor = ligColor; newLight->ligComponent->lightPos = { 0.0f, 0.0f, 0.0f }; newLight->ligComponent->lightAmb = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightIntensity = 4.0f; return newLight; } Light * Renderer::CreatePointLight(DirectX::XMFLOAT3 position, DirectX::XMFLOAT4 ligColor, float inten) { if (pointLights.size() == maxPLights) { return nullptr; printf("ERROR: Could not create new light.\nReason: Maximum capacity"); } Light* newLight = new Light(); newLight->lightID = (unsigned int)allLights.size(); newLight->compID = (unsigned int)pointLights.size(); allLights.push_back(newLight); pointLights.push_back(Light::LightComponent()); newLight->ligComponent = &pointLights[newLight->compID]; newLight->lightType = Light::Point; newLight->lightOn = true; newLight->ligComponent->lightPos = position; newLight->ligComponent->lightColor = ligColor; newLight->ligComponent->lightIntensity = inten; newLight->ligComponent->lightAmb = { 0.5f, 0.5f, 0.5f, 0.5f }; return newLight; } Light * Renderer::CreateSpotLight(DirectX::XMFLOAT3 position) { if (spotLights.size() == maxSLights) { return nullptr; printf("ERROR: Could not create new light.\nReason: Maximum capacity"); } Light* newLight = new Light(); newLight->lightID = (unsigned int)allLights.size(); newLight->compID = (unsigned int)spotLights.size(); allLights.push_back(newLight); spotLights.push_back(Light::LightComponent()); newLight->ligComponent = &spotLights[newLight->compID]; newLight->lightType = Light::Spot; newLight->lightOn = true; newLight->ligComponent->lightPos = position; newLight->ligComponent->lightColor = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightAmb = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightIntensity = 4.0f; return newLight; } Light * Renderer::CreateSpotLight(DirectX::XMFLOAT3 position, DirectX::XMFLOAT4 ligColor) { if (spotLights.size() == maxSLights) { return nullptr; printf("ERROR: Could not create new light.\nReason: Maximum capacity"); } Light* newLight = new Light(); newLight->lightID = (unsigned int)allLights.size(); newLight->compID = (unsigned int)spotLights.size(); allLights.push_back(newLight); spotLights.push_back(Light::LightComponent()); newLight->ligComponent = &spotLights[newLight->compID]; newLight->lightType = Light::Spot; newLight->lightOn = true; newLight->ligComponent->lightPos = position; newLight->ligComponent->lightColor = ligColor; newLight->ligComponent->lightAmb = { 0.5f, 0.5f, 0.5f, 0.5f }; newLight->ligComponent->lightIntensity = 4.0f; return newLight; } Light * Renderer::CreateSpotLight(DirectX::XMFLOAT3 position, DirectX::XMFLOAT4 ligColor, float inten) { if (spotLights.size() == maxSLights) { return nullptr; printf("ERROR: Could not create new light.\nReason: Maximum capacity"); } Light* newLight = new Light(); newLight->lightID = (unsigned int)allLights.size(); newLight->compID = (unsigned int)spotLights.size(); allLights.push_back(newLight); spotLights.push_back(Light::LightComponent()); newLight->ligComponent = &spotLights[newLight->compID]; newLight->lightType = Light::Spot; newLight->lightOn = true; newLight->ligComponent->lightPos = position; newLight->ligComponent->lightColor = ligColor; newLight->ligComponent->lightIntensity = inten; newLight->ligComponent->lightAmb = { 0.5f, 0.5f, 0.5f, 0.5f }; return newLight; } void Renderer::RemoveLight(Light * light) { allLights.erase(allLights.begin() + light->lightID); if(light->lightType == Light::Directional) { directionalLights.erase(directionalLights.begin() + light->compID); } else if(light->lightType == Light::Point) { pointLights.erase(pointLights.begin() + light->compID); } else if(light->lightType == Light::Spot) { spotLights.erase(spotLights.begin() + light->compID); } if (light != nullptr) { delete light; light = nullptr; } } #pragma endregion void Renderer::RemoveFromRenderer(std::string meshName, unsigned int Id) { if (assets->meshStorage[meshName]->rendComponents->at(Id)->mat.materialType == Material::Transulcent) { RemoveFromTranslucent(assets->meshStorage[meshName]->rendComponents->at(Id)->mat.translucentID); } assets->meshStorage[meshName]->rendComponents->erase(assets->meshStorage[meshName]->rendComponents->begin()+Id); for (unsigned int i = Id; i < assets->meshStorage[meshName]->rendComponents->size(); i++) { assets->meshStorage[meshName]->rendComponents->at(i)->rendID = i; } assets->meshStorage[meshName]->inUse = assets->meshStorage[meshName]->instances != 0 ? true : false; assets->meshStorage[meshName]->canInstRender = assets->meshStorage[meshName]->instances >= assets->meshStorage[meshName]->instanceThreshold ? true : false; } void Renderer::RemoveFromTranslucent(unsigned int Id) { transRendComponents.erase(transRendComponents.begin() + Id); for (unsigned int i = 0; i < transRendComponents.size(); i++) { transRendComponents[i]->mat.translucentID = i; } } void Renderer::RemoveFromCanvas(unsigned int Id) { canvasRendComponents.erase(canvasRendComponents.begin() + Id); for (unsigned int i = 0; i < canvasRendComponents.size(); i++) { canvasRendComponents[i]->rendID= i; } } void Renderer::RemoveFromEmitter(unsigned int Id) { particleEmitters.erase(particleEmitters.begin() + Id); for (unsigned int i = 0; i < particleEmitters.size(); i++) { particleEmitters[i]->emitterID = i; } } void Renderer::LoadShaders() { //================================================= // Init Vertex Shaders //================================================= vertexFShader = new SimpleVertexShader(device, context); vertexFShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/ForwardShaders/VertexFShader.cso"); instanceFVShader = new SimpleVertexShader(device, context); instanceFVShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/ForwardShaders/InstanceFVShader.cso"); vertexDShader = new SimpleVertexShader(device, context); vertexDShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/DeferredShaders/VertexDShader.cso"); instanceDVShader = new SimpleVertexShader(device, context); instanceDVShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/DeferredShaders/InstanceDVShader.cso"); skyVShader = new SimpleVertexShader(device, context); skyVShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/SkyBoxShaders/SkyVShader.cso"); quadVShader = new SimpleVertexShader(device, context); quadVShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/PostProcessShaders/QuadVShader.cso"); canvasVShader = new SimpleVertexShader(device, context); canvasVShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/CanvasShaders/CanvasVShader.cso"); particleVShader = new SimpleVertexShader(device, context); particleVShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/ParticleShaders/ParticleVShader.cso"); //================================================= // Init Pixel Shaders //================================================= pixelFShader = new SimplePixelShader(device, context); pixelFShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/ForwardShaders/PixelFShader.cso"); pixelFSShader = new SimplePixelShader(device, context); pixelFSShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/ForwardShaders/PixelFSShader.cso"); pixelFSNShader = new SimplePixelShader(device, context); pixelFSNShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/ForwardShaders/PixelFSNShader.cso"); pixelDShader = new SimplePixelShader(device, context); pixelDShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/DeferredShaders/PixelDShader.cso"); pLightingShader = new SimplePixelShader(device, context); pLightingShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/DeferredShaders/PLightingShader.cso"); skyPShader = new SimplePixelShader(device, context); skyPShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/SkyBoxShaders/SkyPShader.cso"); bloomShader = new SimplePixelShader(device, context); bloomShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/PostProcessShaders/BloomPShader.cso"); hdrShader = new SimplePixelShader(device, context); hdrShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/PostProcessShaders/HdrPShader.cso"); canvasPShader = new SimplePixelShader(device, context); canvasPShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/CanvasShaders/CanvasPShader.cso"); canvasPTShader = new SimplePixelShader(device, context); canvasPTShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/CanvasShaders/CanvasPTShader.cso"); particlePShader = new SimplePixelShader(device, context); particlePShader->LoadShaderFile(L"../DX11Starter/Debug/Shaders/ParticleShaders/ParticlePShader.cso"); } void Renderer::SetWireFrame() { if (wireFrameOn) { context->RSSetState(wireFrame); } else { context->RSSetState(fillFrame); } prevWireStatus = wireFrameOn; } void Renderer::ToggleWireFrame() { wireFrameOn = wireFrameOn ? false : true; SetWireFrame(); } void Renderer::CompileLights() { for (unsigned int i = 0; i < allLights.size(); i++) { if (allLights[i]->lightOn) { //dArr[ligDcount] = directionalLights[i]->dLComponent; /*if (ligDcount == maxSize) { break; } ligDcount++;*/ } } } void Renderer::SetLights(SimplePixelShader* pixel) { int dCount = (int)directionalLights.size(); pixel->SetInt("dCount", dCount); if (dCount != 0) { pixel->SetData("dirLights", &directionalLights[0], sizeof(Light::LightComponent) * maxDLights); } int pCount = (int)pointLights.size(); pixel->SetInt("pCount", pCount); if (pCount != 0) { pixel->SetData("pointLights", &pointLights[0], sizeof(Light::LightComponent) * maxPLights); } int sCount = (int)spotLights.size(); pixel->SetInt("sCount", sCount); if (sCount != 0) { pixel->SetData("spotLights", &spotLights[0], sizeof(Light::LightComponent) * maxSLights); } } void Renderer::DrawForwardPass(RenderingComponent* component) { vertexFShader->SetMatrix4x4("world", component->worldMat); vertexFShader->SetMatrix4x4("view", cam->viewMatrix); vertexFShader->SetMatrix4x4("projection", cam->projectionMatrix); vertexFShader->SetMatrix4x4("worldInvTrans", component->worldInvTrans); vertexFShader->SetFloat4("surColor", component->mat.surfaceColor); vertexFShader->SetFloat3("camPosition",cam->transform.position); vertexFShader->CopyAllBufferData(); SimplePixelShader* currentPixel = nullptr; if (!component->mat.hasSurText) { currentPixel = pixelFShader; } else if (!component->mat.hasNorText) { currentPixel = pixelFSShader; currentPixel->SetShaderResourceView("surfaceTexture", component->mat.GetSurfaceTexture()); currentPixel->SetFloat("uvXOffset", component->mat.uvXOffSet); currentPixel->SetFloat("uvYOffset", component->mat.uvYOffSet); } else { currentPixel = pixelFSNShader; currentPixel->SetShaderResourceView("surfaceTexture", component->mat.GetSurfaceTexture()); currentPixel->SetShaderResourceView("normalTexture", component->mat.GetNormalTexture()); currentPixel->SetFloat("uvXOffset", component->mat.uvXOffSet); currentPixel->SetFloat("uvYOffset", component->mat.uvYOffSet); } currentPixel->SetSamplerState("basicSampler", textureSample); currentPixel->SetShaderResourceView("skyTexture", skyBoxSVR); currentPixel->SetFloat("reflectance", component->mat.surfaceReflectance); SetLights(currentPixel); currentPixel->CopyAllBufferData(); vertexFShader->SetShader(); currentPixel->SetShader(); UINT stride = sizeof(Vertex); UINT offset = 0; context->IASetVertexBuffers(0, 1, &assets->meshStorage[component->meshName]->vertArr, &stride, &offset); context->IASetIndexBuffer(assets->meshStorage[component->meshName]->indArr, DXGI_FORMAT_R32_UINT, 0); context->DrawIndexed( assets->meshStorage[component->meshName]->indCount, // The number of indices to use (we could draw a subset if we wanted) 0, // Offset to the first index we want to use 0); // Offset to add to each index when looking up vertices } void Renderer::DrawFInstance(std::string meshName, InstanceData * components, unsigned int count) { D3D11_MAPPED_SUBRESOURCE mapped = {}; context->Map(instanceWorldMatrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped); // Copy to the resource memcpy(mapped.pData, components, sizeof(InstanceData) * numInstances); // Unmap so the GPU can use it again context->Unmap(instanceWorldMatrixBuffer, 0); ID3D11Buffer* vbs[2] = { assets->meshStorage[meshName]->vertArr, // Per-vertex data instanceWorldMatrixBuffer // Per-instance data }; // Two buffers means two strides and two offsets! UINT strides[2] = { sizeof(Vertex), sizeof(InstanceData) }; UINT offsets[2] = { 0, 0 }; // Set both vertex buffers context->IASetVertexBuffers(0, 2, vbs, strides, offsets); context->IASetIndexBuffer(assets->meshStorage[meshName]->indArr, DXGI_FORMAT_R32_UINT, 0); instanceFVShader->SetMatrix4x4("view", cam->viewMatrix); instanceFVShader->SetMatrix4x4("projection", cam->projectionMatrix); instanceFVShader->SetFloat3("camPosition", cam->transform.position); instanceFVShader->CopyAllBufferData(); SetLights(pixelFShader); pixelFShader->SetSamplerState("basicSampler", textureSample); pixelFShader->SetShaderResourceView("skyTexture", skyBoxSVR); pixelFShader->SetFloat("reflectance", 0.0f); pixelFShader->CopyAllBufferData(); instanceFVShader->SetShader(); pixelFShader->SetShader(); context->DrawIndexedInstanced( assets->meshStorage[meshName]->indCount, // Number of indices from index buffer count, // Number of instances to actually draw 0, 0, 0); // Offsets (unnecessary for us) } void Renderer::DrawDefferedPass(RenderingComponent * component) { } void Renderer::DrawDInstance(std::string meshName, InstanceData * components, unsigned int count) { } void Renderer::InitSkyBox() { D3D11_SAMPLER_DESC sDes = {}; sDes.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sDes.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sDes.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sDes.Filter = D3D11_FILTER_ANISOTROPIC; sDes.MaxAnisotropy = 16; sDes.MaxLOD = D3D11_FLOAT32_MAX; device->CreateSamplerState(&sDes, &sample); // Create a rasterizer state so we can render backfaces D3D11_RASTERIZER_DESC rsDesc = {}; rsDesc.FillMode = D3D11_FILL_SOLID; rsDesc.CullMode = D3D11_CULL_FRONT; rsDesc.DepthClipEnable = true; device->CreateRasterizerState(&rsDesc, &skyRast); // Create a depth state so that we can accept pixels // at a depth less than or EQUAL TO an existing depth D3D11_DEPTH_STENCIL_DESC dsDesc = {}; dsDesc.DepthEnable = true; dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; dsDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; // Make sure we can see the sky (at max depth) device->CreateDepthStencilState(&dsDesc, &skyDepth); ToggleSkyBox(); } void Renderer::ToggleSkyBox() { //if (skyBoxSVR != nullptr) { skyBoxSVR->Release(); skyBoxSVR = nullptr; } switch (skyBoxNum) { case 1: { skyBoxSVR = assets->GetSkyBoxTexture("sunny"); //CreateDDSTextureFromFile(device, L"Textures/Mars.dds", 0, &skyBoxSVR); break; } case 2: { skyBoxSVR = assets->GetSkyBoxTexture("mars"); break; } case 3: { skyBoxSVR = assets->GetSkyBoxTexture("space"); break; } } skyBoxNum += 1; if (skyBoxNum > 3) { skyBoxNum = 1; } } void Renderer::LoadSkyBox(int skyNum) { //if (skyBoxSVR != nullptr) { skyBoxSVR->Release(); skyBoxSVR = nullptr; } skyBoxNum = skyNum; switch (skyBoxNum) { case 1: { skyBoxSVR = assets->GetSkyBoxTexture("sunny"); //DirectX::CreateDDSTextureFromFile(device, L"Assets/Textures/SkyBox/SunnyCubeMap.dds", 0, &skyBoxSVR); //CreateDDSTextureFromFile(device, L"Textures/Mars.dds", 0, &skyBoxSVR); break; } case 2: { skyBoxSVR = assets->GetSkyBoxTexture("mars"); //DirectX::CreateDDSTextureFromFile(device, L"Assets/Textures/SkyBox/Mars.dds", 0, &skyBoxSVR); break; } case 3: { skyBoxSVR = assets->GetSkyBoxTexture("space"); //DirectX::CreateDDSTextureFromFile(device, L"Assets/Textures/SkyBox/space.dds", 0, &skyBoxSVR); break; } } skyBoxNum += 1; if (skyBoxNum > 3) { skyBoxNum = 1; } } void Renderer::DrawSkyBox() { ID3D11RasterizerState* oldR; context->RSGetState(&oldR); ID3D11Buffer* skyVB = assets->meshStorage["Cube"]->GetVertexBuffer(); ID3D11Buffer* skyIB = assets->meshStorage["Cube"]->GetIndicesBuffer(); unsigned int count = assets->meshStorage["Cube"]->indCount; UINT stride = sizeof(Vertex); UINT offset = 0; context->IASetVertexBuffers(0, 1, &skyVB, &stride, &offset); context->IASetIndexBuffer(skyIB, DXGI_FORMAT_R32_UINT, 0); skyVShader->SetMatrix4x4("view", cam->viewMatrix); skyVShader->SetMatrix4x4("projection", cam->projectionMatrix); skyVShader->CopyAllBufferData(); skyVShader->SetShader(); skyPShader->SetShaderResourceView("Sky", skyBoxSVR); skyPShader->SetSamplerState("Sampler", sample); skyPShader->CopyAllBufferData(); skyPShader->SetShader(); context->RSSetState(skyRast); context->OMSetDepthStencilState(skyDepth, 0); context->DrawIndexed(count, 0, 0); context->RSSetState(oldR); context->OMSetDepthStencilState(0, 0); oldR->Release(); } void Renderer::DrawEmiters() { float blend[4] = { 1,1,1,1 }; context->OMSetDepthStencilState(particleDepthState, 0); // No depth WRITING for (unsigned int i = 0; i < particleEmitters.size(); i++) { Emitter* curEmitter = particleEmitters[i]; if (!curEmitter->isActive) { continue; } switch (curEmitter->blendType) { case Emitter::BlendingType::Additive: context->OMSetBlendState(addBlendState, blend, 0xFFFFFFFF); // Additive blending case Emitter::BlendingType::AlphaBlend: context->OMSetBlendState(subBlendState, blend, 0xFFFFFFFF); // Additive blending case Emitter::BlendingType::CutOut: context->OMSetBlendState(cutBlendState, blend, 0xFFFFFFFF); // Additive blending } curEmitter->LoadParticlesForGPU(context); UINT stride = sizeof(ParticleVertex); UINT offset = 0; context->IASetVertexBuffers(0, 1, &curEmitter->emitterBuffer, &stride, &offset); context->IASetIndexBuffer(curEmitter->indBuffer, DXGI_FORMAT_R32_UINT, 0); particleVShader->SetMatrix4x4("view", cam->viewMatrix); particleVShader->SetMatrix4x4("projection", cam->projectionMatrix); particleVShader->SetShader(); particleVShader->CopyAllBufferData(); particlePShader->SetShaderResourceView("particle", curEmitter->particleMat.GetSurfaceTexture()); particlePShader->SetSamplerState("trilinear", textureSample); particlePShader->SetShader(); particlePShader->CopyAllBufferData(); // Draw the correct parts of the buffer if (curEmitter->oldestParticlePos < curEmitter->newestParticlePos) { context->DrawIndexed(curEmitter->particleCount * 6, curEmitter->oldestParticlePos * 6, 0); } else { // Draw first half (0 -> dead) context->DrawIndexed(curEmitter->newestParticlePos * 6, 0, 0); // Draw second half (alive -> max) context->DrawIndexed((curEmitter->maxParticles - curEmitter->oldestParticlePos) * 6, curEmitter->oldestParticlePos * 6, 0); } } context->OMSetBlendState(0, blend, 0xffffffff); context->OMSetDepthStencilState(0, 0); } void Renderer::DrawCanvas() { //float blend[4] = { 1,1,1,1 }; //context->OMSetDepthStencilState(particleDepthState, 0); //context->OMSetBlendState(cutBlendState, blend, 0xFFFFFFFF); // Additive blending for(unsigned int i = 0; i < canvasRendComponents.size(); i ++) { if(canvasRendComponents[i]->canRender) { canvasVShader->SetMatrix4x4("world", canvasRendComponents[i]->worldMat); canvasVShader->SetMatrix4x4("projection", cam->projectionMatrix); canvasVShader->SetFloat4("surColor", canvasRendComponents[i]->mat.surfaceColor); canvasVShader->CopyAllBufferData(); canvasVShader->SetShader(); SimplePixelShader* currentPixel = nullptr; if (!canvasRendComponents[i]->mat.hasSurText) { currentPixel = canvasPShader; } else { currentPixel = canvasPTShader; currentPixel->SetFloat("uvXOffset", canvasRendComponents[i]->mat.uvXOffSet); currentPixel->SetFloat("uvYOffset", canvasRendComponents[i]->mat.uvYOffSet); currentPixel->SetShaderResourceView("surfaceTexture", canvasRendComponents[i]->mat.GetSurfaceTexture()); currentPixel->SetSamplerState("Sampler", sample); } currentPixel->CopyAllBufferData(); currentPixel->SetShader(); UINT stride = sizeof(Vertex); UINT offset = 0; context->IASetVertexBuffers(0, 1, &assets->meshStorage[canvasRendComponents[i]->meshName]->vertArr, &stride, &offset); context->IASetIndexBuffer(assets->meshStorage[canvasRendComponents[i]->meshName]->indArr, DXGI_FORMAT_R32_UINT, 0); context->DrawIndexed(assets->meshStorage[canvasRendComponents[i]->meshName]->indCount, 0, 0); } } //context->OMSetBlendState(0, blend, 0xffffffff); //context->OMSetDepthStencilState(0, 0); }
30.659074
171
0.713998
[ "mesh", "render", "transform" ]
f65e8b13b873da054e64f5628d7ab02e279ddddf
28,621
cpp
C++
prman/Procedural/WriteGeo.cpp
ryu-sw/alembic
395450bad88f9d5ed6d20612e9201aac93a5eb54
[ "MIT" ]
1
2021-02-03T06:10:58.000Z
2021-02-03T06:10:58.000Z
prman/Procedural/WriteGeo.cpp
ryu-sw/alembic
395450bad88f9d5ed6d20612e9201aac93a5eb54
[ "MIT" ]
null
null
null
prman/Procedural/WriteGeo.cpp
ryu-sw/alembic
395450bad88f9d5ed6d20612e9201aac93a5eb54
[ "MIT" ]
1
2022-01-30T04:16:01.000Z
2022-01-30T04:16:01.000Z
//-***************************************************************************** // // Copyright (c) 2009-2011, // Sony Pictures Imageworks Inc. and // Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Sony Pictures Imageworks, nor // Industrial Light & Magic, nor the names of their 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 <ri.h> #include "WriteGeo.h" #include "SampleUtil.h" #include "ArbAttrUtil.h" #include "SubDTags.h" #ifdef PRMAN_USE_ABCMATERIAL #include "WriteMaterial.h" #endif //-***************************************************************************** void RestoreResource( const std::string & resourceName ) { ParamListBuilder paramListBuilder; paramListBuilder.addStringValue("restore", true); paramListBuilder.add( "string operation", paramListBuilder.finishStringVector() ); paramListBuilder.addStringValue("shading", true); paramListBuilder.add( "string subset", paramListBuilder.finishStringVector() ); RiResourceV( const_cast<char *>( resourceName.c_str() ), const_cast<char *>( "attributes" ), paramListBuilder.n(), paramListBuilder.nms(), paramListBuilder.vals()); } void SaveResource( const std::string & resourceName ) { ParamListBuilder paramListBuilder; paramListBuilder.addStringValue("save", true); paramListBuilder.add( "string operation", paramListBuilder.finishStringVector() ); RiResourceV( const_cast<char *>( resourceName.c_str() ), const_cast<char *>( "attributes" ), paramListBuilder.n(), paramListBuilder.nms(), paramListBuilder.vals()); } void ApplyResources( IObject object, ProcArgs &args ) { std::string resourceName; //first check full name... resourceName = args.getResource( object.getFullName() ); if ( resourceName.empty() ) { //...and then base name resourceName = args.getResource( object.getName() ); } if ( !resourceName.empty() ) { RestoreResource(resourceName); } } //-***************************************************************************** void ProcessXform( IXform &xform, ProcArgs &args ) { IXformSchema &xs = xform.getSchema(); TimeSamplingPtr ts = xs.getTimeSampling(); size_t xformSamps = xs.getNumSamples(); SampleTimeSet sampleTimes; GetRelevantSampleTimes( args, ts, xformSamps, sampleTimes ); bool multiSample = sampleTimes.size() > 1; std::vector<XformSample> sampleVectors; sampleVectors.resize( sampleTimes.size() ); //fetch all operators at each sample time first size_t sampleTimeIndex = 0; for ( SampleTimeSet::iterator I = sampleTimes.begin(); I != sampleTimes.end(); ++I, ++sampleTimeIndex ) { ISampleSelector sampleSelector( *I ); xs.get( sampleVectors[sampleTimeIndex], sampleSelector ); } if (xs.getInheritsXforms () == false) { RiIdentity (); } //loop through the operators individually since a MotionBegin block //can enclose only homogenous statements for ( size_t i = 0, e = xs.getNumOps(); i < e; ++i ) { if ( multiSample ) { WriteMotionBegin(args, sampleTimes); } for ( size_t j = 0; j < sampleVectors.size(); ++j ) { XformOp &op = sampleVectors[j][i]; switch ( op.getType() ) { case kScaleOperation: { V3d value = op.getScale(); RiScale( value.x, value.y, value.z ); break; } case kTranslateOperation: { V3d value = op.getTranslate(); RiTranslate( value.x, value.y, value.z ); break; } case kRotateOperation: case kRotateXOperation: case kRotateYOperation: case kRotateZOperation: { V3d axis = op.getAxis(); float degrees = op.getAngle(); RiRotate( degrees, axis.x, axis.y, axis.z ); break; } case kMatrixOperation: { WriteConcatTransform( op.getMatrix() ); break; } } } if ( multiSample ) { RiMotionEnd(); } } } //-***************************************************************************** void ProcessPolyMesh( IPolyMesh &polymesh, ProcArgs &args ) { IPolyMeshSchema &ps = polymesh.getSchema(); TimeSamplingPtr ts = ps.getTimeSampling(); SampleTimeSet sampleTimes; GetRelevantSampleTimes( args, ts, ps.getNumSamples(), sampleTimes ); bool multiSample = sampleTimes.size() > 1; if ( multiSample ) { WriteMotionBegin( args, sampleTimes ); } for ( SampleTimeSet::iterator iter = sampleTimes.begin(); iter != sampleTimes.end(); ++ iter ) { ISampleSelector sampleSelector( *iter ); IPolyMeshSchema::Sample sample = ps.getValue( sampleSelector ); RtInt npolys = (RtInt) sample.getFaceCounts()->size(); ParamListBuilder paramListBuilder; paramListBuilder.add( "P", (RtPointer)sample.getPositions()->get() ); IV2fGeomParam uvParam = ps.getUVsParam(); if ( uvParam.valid() ) { ICompoundProperty parent = uvParam.getParent(); if ( !args.flipv ) { AddGeomParamToParamListBuilder<IV2fGeomParam>( parent, uvParam.getHeader(), sampleSelector, "float", paramListBuilder, 2, "st"); } else if ( std::vector<float> * values = AddGeomParamToParamListBuilderAsFloat<IV2fGeomParam, float>( parent, uvParam.getHeader(), sampleSelector, "float", paramListBuilder, "st") ) { for ( size_t i = 1, e = values->size(); i < e; i += 2 ) { (*values)[i] = 1.0 - (*values)[i]; } } } IN3fGeomParam nParam = ps.getNormalsParam(); if ( nParam.valid() ) { ICompoundProperty parent = nParam.getParent(); AddGeomParamToParamListBuilder<IN3fGeomParam>( parent, nParam.getHeader(), sampleSelector, "normal", paramListBuilder); } ICompoundProperty arbGeomParams = ps.getArbGeomParams(); AddArbitraryGeomParams( arbGeomParams, sampleSelector, paramListBuilder ); RiPointsPolygonsV( npolys, (RtInt*) sample.getFaceCounts()->get(), (RtInt*) sample.getFaceIndices()->get(), paramListBuilder.n(), paramListBuilder.nms(), paramListBuilder.vals() ); } if (multiSample) RiMotionEnd(); } //-***************************************************************************** void ProcessSubD( ISubD &subd, ProcArgs &args, const std::string & facesetName ) { ISubDSchema &ss = subd.getSchema(); TimeSamplingPtr ts = ss.getTimeSampling(); SampleTimeSet sampleTimes; GetRelevantSampleTimes( args, ts, ss.getNumSamples(), sampleTimes ); bool multiSample = sampleTimes.size() > 1; //include this code path for future expansion bool isHierarchicalSubD = false; bool hasLocalResources = false; std::vector<IFaceSet> faceSets; std::vector<std::string> faceSetResourceNames; if ( facesetName.empty() ) { std::vector <std::string> childFaceSetNames; ss.getFaceSetNames(childFaceSetNames); faceSets.reserve(childFaceSetNames.size()); faceSetResourceNames.reserve(childFaceSetNames.size()); for (size_t i = 0; i < childFaceSetNames.size(); ++i) { faceSets.push_back(ss.getFaceSet(childFaceSetNames[i])); IFaceSet & faceSet = faceSets.back(); std::string resourceName = args.getResource( faceSet.getFullName() ); if ( resourceName.empty() ) { resourceName = args.getResource( faceSet.getName() ); } #ifdef PRMAN_USE_ABCMATERIAL Mat::MaterialFlatten mafla(faceSet); if (!mafla.empty()) { if (!hasLocalResources) { RiResourceBegin(); hasLocalResources = true; } RiAttributeBegin(); if ( !resourceName.empty() ) { //restore existing resource state here RestoreResource( resourceName ); } WriteMaterial( mafla, args ); resourceName = faceSet.getFullName(); SaveResource( resourceName ); RiAttributeEnd(); } #endif faceSetResourceNames.push_back(resourceName); } } #ifdef PRMAN_USE_ABCMATERIAL else { //handle single faceset material directly if ( ss.hasFaceSet( facesetName ) ) { IFaceSet faceSet = ss.getFaceSet( facesetName ); ApplyObjectMaterial(faceSet, args); } } #endif if ( multiSample ) { WriteMotionBegin( args, sampleTimes ); } for ( SampleTimeSet::iterator iter = sampleTimes.begin(); iter != sampleTimes.end(); ++iter ) { ISampleSelector sampleSelector( *iter ); ISubDSchema::Sample sample = ss.getValue( sampleSelector ); RtInt npolys = (RtInt) sample.getFaceCounts()->size(); ParamListBuilder paramListBuilder; paramListBuilder.add( "P", (RtPointer)sample.getPositions()->get() ); IV2fGeomParam uvParam = ss.getUVsParam(); if ( uvParam.valid() ) { ICompoundProperty parent = uvParam.getParent(); if ( !args.flipv ) { AddGeomParamToParamListBuilder<IV2fGeomParam>( parent, uvParam.getHeader(), sampleSelector, "float", paramListBuilder, 2, "st"); } else if ( std::vector<float> * values = AddGeomParamToParamListBuilderAsFloat<IV2fGeomParam, float>( parent, uvParam.getHeader(), sampleSelector, "float", paramListBuilder, "st") ) { for ( size_t i = 1, e = values->size(); i < e; i += 2 ) { (*values)[i] = 1.0 - (*values)[i]; } } } ICompoundProperty arbGeomParams = ss.getArbGeomParams(); AddArbitraryGeomParams( arbGeomParams, sampleSelector, paramListBuilder ); std::string subdScheme = sample.getSubdivisionScheme(); SubDTagBuilder tags; ProcessFacevaryingInterpolateBoundry( tags, sample ); ProcessInterpolateBoundry( tags, sample ); ProcessFacevaryingPropagateCorners( tags, sample ); ProcessHoles( tags, sample ); ProcessCreases( tags, sample ); ProcessCorners( tags, sample ); if ( !facesetName.empty() ) { if ( ss.hasFaceSet( facesetName ) ) { IFaceSet faceSet = ss.getFaceSet( facesetName ); ApplyResources( faceSet, args ); // TODO, move the hold test outside of MotionBegin // as it's not meaningful to change per sample IFaceSetSchema::Sample faceSetSample = faceSet.getSchema().getValue( sampleSelector ); std::set<int> facesToKeep; facesToKeep.insert( faceSetSample.getFaces()->get(), faceSetSample.getFaces()->get() + faceSetSample.getFaces()->size() ); for ( int i = 0; i < npolys; ++i ) { if ( facesToKeep.find( i ) == facesToKeep.end() ) { tags.add( "hole" ); tags.addIntArg( i ); } } } } else { //loop through the facesets and determine whether there are any //resources assigned to each for (size_t i = 0; i < faceSetResourceNames.size(); ++i) { const std::string & resourceName = faceSetResourceNames[i]; //TODO, visibility? if ( !resourceName.empty() ) { IFaceSet & faceSet = faceSets[i]; isHierarchicalSubD = true; tags.add("faceedit"); Int32ArraySamplePtr faces = faceSet.getSchema().getValue( sampleSelector ).getFaces(); for (size_t j = 0, e = faces->size(); j < e; ++j) { tags.addIntArg(1); //yep, every face gets a 1 in front of it too tags.addIntArg( (int) faces->get()[j]); } tags.addStringArg( "attributes" ); tags.addStringArg( resourceName ); tags.addStringArg( "shading" ); } } } if ( isHierarchicalSubD ) { RiHierarchicalSubdivisionMeshV( const_cast<RtToken>( subdScheme.c_str() ), npolys, (RtInt*) sample.getFaceCounts()->get(), (RtInt*) sample.getFaceIndices()->get(), tags.nt(), tags.tags(), tags.nargs( true ), tags.intargs(), tags.floatargs(), tags.stringargs(), paramListBuilder.n(), paramListBuilder.nms(), paramListBuilder.vals() ); } else { RiSubdivisionMeshV( const_cast<RtToken>(subdScheme.c_str() ), npolys, (RtInt*) sample.getFaceCounts()->get(), (RtInt*) sample.getFaceIndices()->get(), tags.nt(), tags.tags(), tags.nargs( false ), tags.intargs(), tags.floatargs(), paramListBuilder.n(), paramListBuilder.nms(), paramListBuilder.vals() ); } } if ( multiSample ) { RiMotionEnd(); } if ( hasLocalResources ) { RiResourceEnd(); } } //-***************************************************************************** void ProcessNuPatch( INuPatch &patch, ProcArgs &args ) { INuPatchSchema &ps = patch.getSchema(); TimeSamplingPtr ts = ps.getTimeSampling(); SampleTimeSet sampleTimes; GetRelevantSampleTimes( args, ts, ps.getNumSamples(), sampleTimes ); //trim curves are described outside the motion blocks if ( ps.hasTrimCurve() ) { //get the current time sample independent of any shutter values INuPatchSchema::Sample sample = ps.getValue( ISampleSelector( args.frame / args.fps ) ); RiTrimCurve( sample.getTrimNumCurves()->size(), //numloops (RtInt*) sample.getTrimNumCurves()->get(), (RtInt*) sample.getTrimOrders()->get(), (RtFloat*) sample.getTrimKnots()->get(), (RtFloat*) sample.getTrimMins()->get(), (RtFloat*) sample.getTrimMaxes()->get(), (RtInt*) sample.getTrimNumVertices()->get(), (RtFloat*) sample.getTrimU()->get(), (RtFloat*) sample.getTrimV()->get(), (RtFloat*) sample.getTrimW()->get() ); } bool multiSample = sampleTimes.size() > 1; if ( multiSample ) { WriteMotionBegin( args, sampleTimes ); } for ( SampleTimeSet::iterator iter = sampleTimes.begin(); iter != sampleTimes.end(); ++iter ) { ISampleSelector sampleSelector( *iter ); INuPatchSchema::Sample sample = ps.getValue( sampleSelector ); ParamListBuilder paramListBuilder; //build this here so that it's still in scope when RiNuPatchV is //called. std::vector<RtFloat> pwValues; if ( sample.getPositionWeights() ) { if ( sample.getPositionWeights()->size() == sample.getPositions()->size() ) { //need to combine P with weight form Pw pwValues.reserve( sample.getPositions()->size() * 4 ); const float32_t * pStart = reinterpret_cast<const float32_t * >( sample.getPositions()->get() ); const float32_t * wStart = reinterpret_cast<const float32_t * >( sample.getPositionWeights()->get() ); for ( size_t i = 0, e = sample.getPositionWeights()->size(); i < e; ++i ) { pwValues.push_back( pStart[i*3] ); pwValues.push_back( pStart[i*3+1] ); pwValues.push_back( pStart[i*3+2] ); pwValues.push_back( wStart[i] ); } paramListBuilder.add( "Pw", (RtPointer) &pwValues[0] ); } } if ( pwValues.empty() ) { //no Pw so go straight with P paramListBuilder.add( "P", (RtPointer)sample.getPositions()->get() ); } ICompoundProperty arbGeomParams = ps.getArbGeomParams(); AddArbitraryGeomParams( arbGeomParams, sampleSelector, paramListBuilder ); //For now, use the last knot value for umin and umax as it's //not described in the alembic data RiNuPatchV( sample.getNumU(), sample.getUOrder(), (RtFloat *) sample.getUKnot()->get(), 0.0, //umin sample.getUKnot()->get()[sample.getUKnot()->size()-1],//umax sample.getNumV(), sample.getVOrder(), (RtFloat *) sample.getVKnot()->get(), 0.0, //vmin sample.getVKnot()->get()[sample.getVKnot()->size()-1], //vmax paramListBuilder.n(), paramListBuilder.nms(), paramListBuilder.vals() ); } if ( multiSample ) { RiMotionEnd(); } } //-***************************************************************************** void ProcessPoints( IPoints &points, ProcArgs &args ) { IPointsSchema &ps = points.getSchema(); TimeSamplingPtr ts = ps.getTimeSampling(); SampleTimeSet sampleTimes; //for now, punt on the changing point count case -- even for frame ranges //for which the point count isn't changing if ( ps.getIdsProperty().isConstant() ) { //grab only the current time sampleTimes.insert( args.frame / args.fps ); } else { GetRelevantSampleTimes( args, ts, ps.getNumSamples(), sampleTimes ); } bool multiSample = sampleTimes.size() > 1; if ( multiSample ) { WriteMotionBegin( args, sampleTimes ); } for ( SampleTimeSet::iterator iter = sampleTimes.begin(); iter != sampleTimes.end(); ++iter ) { ISampleSelector sampleSelector( *iter ); IPointsSchema::Sample sample = ps.getValue( sampleSelector ); ParamListBuilder paramListBuilder; paramListBuilder.add( "P", (RtPointer)sample.getPositions()->get() ); ICompoundProperty arbGeomParams = ps.getArbGeomParams(); AddArbitraryGeomParams( arbGeomParams, sampleSelector, paramListBuilder ); RiPointsV(sample.getPositions()->size(), paramListBuilder.n(), paramListBuilder.nms(), paramListBuilder.vals() ); } if ( multiSample ) { RiMotionEnd(); } } //-***************************************************************************** void ProcessCurves( ICurves &curves, ProcArgs &args ) { ICurvesSchema &cs = curves.getSchema(); TimeSamplingPtr ts = cs.getTimeSampling(); SampleTimeSet sampleTimes; GetRelevantSampleTimes( args, ts, cs.getNumSamples(), sampleTimes ); bool multiSample = sampleTimes.size() > 1; bool firstSample = true; for ( SampleTimeSet::iterator iter = sampleTimes.begin(); iter != sampleTimes.end(); ++iter ) { ISampleSelector sampleSelector( *iter ); ICurvesSchema::Sample sample = cs.getValue( sampleSelector ); //need to set the basis prior to the MotionBegin block if ( firstSample ) { firstSample = false; BasisType basisType = sample.getBasis(); if ( basisType != kNoBasis ) { RtBasis * basis = NULL; RtInt step = 0; switch ( basisType ) { case kBezierBasis: basis = &RiBezierBasis; step = RI_BEZIERSTEP; break; case kBsplineBasis: basis = &RiBSplineBasis; step = RI_BSPLINESTEP; break; case kCatmullromBasis: basis = &RiCatmullRomBasis; step = RI_CATMULLROMSTEP; break; case kHermiteBasis: basis = &RiHermiteBasis; step = RI_HERMITESTEP; break; case kPowerBasis: basis = &RiPowerBasis; step = RI_POWERSTEP; break; default: break; } if ( basis != NULL ) { RiBasis( *basis, step, *basis, step); } } if ( multiSample ) { WriteMotionBegin( args, sampleTimes ); } } ParamListBuilder paramListBuilder; paramListBuilder.add( "P", (RtPointer)sample.getPositions()->get() ); IFloatGeomParam widthParam = cs.getWidthsParam(); if ( widthParam.valid() ) { ICompoundProperty parent = widthParam.getParent(); //prman requires "width" to be named "constantwidth" when //constant instead of declared as "constant float width". //It's even got an error message specifically for it. std::string widthName; if ( widthParam.getScope() == kConstantScope || widthParam.getScope() == kUnknownScope ) { widthName = "constantwidth"; } else { widthName = "width"; } AddGeomParamToParamListBuilder<IFloatGeomParam>( parent, widthParam.getHeader(), sampleSelector, "float", paramListBuilder, 1, widthName); } IN3fGeomParam nParam = cs.getNormalsParam(); if ( nParam.valid() ) { ICompoundProperty parent = nParam.getParent(); AddGeomParamToParamListBuilder<IN3fGeomParam>( parent, nParam.getHeader(), sampleSelector, "normal", paramListBuilder); } IV2fGeomParam uvParam = cs.getUVsParam(); if ( uvParam.valid() ) { ICompoundProperty parent = uvParam.getParent(); AddGeomParamToParamListBuilder<IV2fGeomParam>( parent, uvParam.getHeader(), sampleSelector, "float", paramListBuilder, 2, "st"); } ICompoundProperty arbGeomParams = cs.getArbGeomParams(); AddArbitraryGeomParams( arbGeomParams, sampleSelector, paramListBuilder ); RtToken curveType; switch ( sample.getType() ) { case kCubic: curveType = const_cast<RtToken>( "cubic" ); break; default: curveType = const_cast<RtToken>( "linear" ); } RtToken wrap; switch ( sample.getWrap() ) { case kPeriodic: wrap = const_cast<RtToken>( "periodic" ); break; default: wrap = const_cast<RtToken>( "nonperiodic" ); } RiCurvesV(curveType, sample.getNumCurves(), (RtInt*) sample.getCurvesNumVertices()->get(), wrap, paramListBuilder.n(), paramListBuilder.nms(), paramListBuilder.vals() ); } if ( multiSample ) { RiMotionEnd(); } } //-***************************************************************************** void WriteIdentifier( const ObjectHeader &ohead ) { std::string name = ohead.getFullName(); char* nameArray[] = { const_cast<char*>( name.c_str() ), RI_NULL }; RiAttribute(const_cast<char*>( "identifier" ), const_cast<char*>( "name" ), nameArray, RI_NULL ); }
32.59795
88
0.497572
[ "object", "vector" ]
f65f09dcc0556d8014e7bdea0f7bb0e89be0d32c
2,377
hpp
C++
graphs/Graph.hpp
subox/algorithms
bb5473a4edfdbf69f6600d1667d98b5529773801
[ "Apache-2.0" ]
null
null
null
graphs/Graph.hpp
subox/algorithms
bb5473a4edfdbf69f6600d1667d98b5529773801
[ "Apache-2.0" ]
null
null
null
graphs/Graph.hpp
subox/algorithms
bb5473a4edfdbf69f6600d1667d98b5529773801
[ "Apache-2.0" ]
null
null
null
#ifndef __ALGORITHMS_GRAPH_HPP__ #define __ALGORITHMS_GRAPH_HPP__ #include "helpers/Base.hpp" #include <vector> #include <iostream> #include <string> #include <algorithm> namespace subox { namespace algorithms { namespace graphs { template< typename TObject = unsigned, template< typename...> class TContainer = std::vector > struct Graph : public Base<TObject> { typedef typename Base<TObject>::MyArr EdgeList; typedef TContainer<EdgeList> AdjacList; typedef typename AdjacList::iterator iterator; typedef typename AdjacList::const_iterator const_iterator; Graph( typename AdjacList::size_type const vertexSize = 0 ) { generateNumbers(vertexSize); } ~Graph(){} void assignNumbers( AdjacList&& _adjList ){ adjList = _adjList; } void generateNumbers( std::size_t const capacity = 0, bool const = false ) override { if (capacity) { adjList.clear(); increaseAdjList( capacity ); } } void addEdge( TObject const& v1, TObject const& v2 ) { if (adjList.size() <= v1){ increaseAdjList( v1 ); } if (adjList.size() <= v2 ) { increaseAdjList( v2 ); } adjList[ v1 ].emplace_back( v2 ); adjList[ v2 ].emplace_back( v1 ); } EdgeList const& getEdges( TObject const& vertex ) const { return adjList[vertex]; } const_iterator begin() const { return adjList.cbegin(); } const_iterator end() const { return adjList.cend(); } EdgeList const& operator[]( TObject const& item ) const { return getEdges( item ); } typename AdjacList::size_type size() const { return adjList.size(); } void print() const override { for (typename AdjacList::size_type v = 0; v < adjList.size(); ++v ) { for( TObject const& item : adjList[v] ) { std::cout << v << " --- " << item << std::endl; } } }; bool calc(TObject const=1) { //todo std::cerr << "Error: Not a sort type" << std::endl; return false; } constexpr std::string name() const override { return "Graph"; } private: void increaseAdjList( TObject const newSize ) { adjList.reserve( newSize + 1 ); for (std::size_t i = adjList.size(); i < newSize; ++i) { adjList.emplace_back( typename Base<TObject>::MyArr() ); } } void assignNumbers( EdgeList const& /*initNumbers */ ) override { } inline void push( TObject const& item ) { adjList.emplace_back( item ); } AdjacList adjList; }; } } } #endif // __ALGORITHMS_GRAPH_HPP__
21.223214
94
0.675642
[ "vector" ]
f66158015cd880e38b92afd6b0326b9255628ee9
20,789
cpp
C++
src/Conversion/KrnlToAffine/KrnlMatmul.cpp
redbopo/onnx-mlir
3305a13ddcdfa73ddd6c241b64c8d856e78b9455
[ "Apache-2.0" ]
null
null
null
src/Conversion/KrnlToAffine/KrnlMatmul.cpp
redbopo/onnx-mlir
3305a13ddcdfa73ddd6c241b64c8d856e78b9455
[ "Apache-2.0" ]
null
null
null
src/Conversion/KrnlToAffine/KrnlMatmul.cpp
redbopo/onnx-mlir
3305a13ddcdfa73ddd6c241b64c8d856e78b9455
[ "Apache-2.0" ]
null
null
null
/* * SPDX-License-Identifier: Apache-2.0 */ //===-------------- KrnlMatmul.cpp - Lower KrnlMatmulOp -------------------===// // // Copyright 2019-2020 The IBM Research Authors. // // ============================================================================= // // This file lowers the KrnlMatmulOp operator. // //===----------------------------------------------------------------------===// #include "mlir/Conversion/LLVMCommon/TypeConverter.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/IR/BuiltinTypes.h" #include "src/Conversion/KrnlToAffine/ConvertKrnlToAffine.hpp" #include "src/Conversion/KrnlToAffine/KrnlToAffineHelper.hpp" #include "src/Conversion/KrnlToLLVM/RuntimeAPI.hpp" #include "src/Dialect/Krnl/KrnlOps.hpp" #include "src/Support/KrnlSupport.hpp" #include "llvm/Support/Debug.h" #include <mutex> #define DEBUG_TYPE "krnl_to_affine" using namespace mlir; using namespace onnx_mlir; namespace onnx_mlir { namespace krnl { static constexpr int BUFFER_ALIGN = 64; extern UnrollAndJamMap unrollAndJamMap; extern std::mutex unrollAndJamMutex; // Affine expressions compared to >= 0 static IndexExpr isFullTile(IndexExpr UB, IndexExpr block, IndexExpr GI) { // Determine if the current tile is full. It is full if the begining of // the tile (nGI) is smaller or equal to UB - bloc, namely // PredicateIndexExpr nIsFullTile = (nGI <= (nUB - nBlock)); // However, if UB is divisible by Block, then its full no matter what. if (UB.isLiteral() && (UB.getLiteral() % block.getLiteral() == 0)) { // Last tile is guaranteed to be full because UB is divisable by block. return LiteralIndexExpr(1); // 1 >= 0 is true } // true if GI <= (UB - block), namely UB - block - GI >= 0 IndexExpr res = UB - block - GI; return res; } static IndexExpr partialTrip(IndexExpr UB, IndexExpr block, IndexExpr GI) { // Trip count for partial tiles: leftover = UB - GI in general. If UB is // known at compile time, then without loss of generality, leftover = (UB- // GI) % Block, and since GI is by definition a multiple of Block (GI is // index at begining of tile), then leftover = UB % Block. // IndexExpr nPartialTrip = nUB.isLiteral() ? nUB % nBlock : nUB - nGI; if (UB.isLiteral()) { IndexExpr partialTrip = UB % block; assert(partialTrip.isLiteral() && "op on 2 literals has to be literal"); return partialTrip; } // don't have to take the mod since we know we have a partial tile already. return UB - GI; } // KrnlMatmul will be lowered to vector and affine expressions class KrnlMatmulLowering : public ConversionPattern { public: explicit KrnlMatmulLowering( TypeConverter &typeConverter, MLIRContext *context) : ConversionPattern( typeConverter, KrnlMatMulOp::getOperationName(), 1, context) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { auto matmulOp = cast<KrnlMatMulOp>(op); KrnlMatMulOpAdaptor operandAdaptor(matmulOp); // Option. bool fullUnrollAndJam = matmulOp.unroll(); // Operands and types. Type elementType = operandAdaptor.A().getType().cast<MemRefType>().getElementType(); bool simdize = matmulOp.simdize(); // Init scope and emit constants. Location loc = matmulOp.getLoc(); AffineBuilderKrnlMem createAffine(rewriter, loc); IndexExprScope indexScope(createAffine); // Gather A, B, C tile sizes. SmallVector<IndexExpr, 2> aTileSize, bTileSize, cTileSize; Value A(operandAdaptor.A()), B(operandAdaptor.B()), C(operandAdaptor.C()); MemRefBoundsIndexCapture aBounds(A), bBounds(B), cBounds(C); int64_t aRank(aBounds.getRank()), bRank(bBounds.getRank()), cRank(cBounds.getRank()); // Tile sizes for A/B/C are determined by their memref unless explicitly // specified by an optional argument. That allows A/B/C memrefs to be // padded if needed for SIMD/unroll and jam, for example. ArrayAttributeIndexCapture aSizeCapture(matmulOp.aTileSizeAttr()); if (aSizeCapture.size()) aTileSize = {aSizeCapture.getLiteral(0), aSizeCapture.getLiteral(1)}; else aTileSize = {aBounds.getSymbol(aRank - 2), aBounds.getSymbol(aRank - 1)}; ArrayAttributeIndexCapture bSizeCapture(matmulOp.bTileSizeAttr()); if (bSizeCapture.size()) bTileSize = {bSizeCapture.getLiteral(0), bSizeCapture.getLiteral(1)}; else bTileSize = {bBounds.getSymbol(bRank - 2), bBounds.getSymbol(bRank - 1)}; ArrayAttributeIndexCapture cSizeCapture(matmulOp.cTileSizeAttr()); if (cSizeCapture.size()) cTileSize = {cSizeCapture.getLiteral(0), cSizeCapture.getLiteral(1)}; else cTileSize = {cBounds.getSymbol(cRank - 2), cBounds.getSymbol(cRank - 1)}; // Gather N, M, K compute tile size. This is the size of the computations, // if the tile is full. Because computation in the buffers could be further // subtiled, the default size can be overridden from the tile sizes using // the computeTileSize attribute. Tiles may not be full if they are at the // outer boundaries of the original data. IndexExpr iComputeTileSize = cTileSize[0]; IndexExpr jComputeTileSize = cTileSize[1]; IndexExpr kComputeTileSize = aTileSize[1]; ArrayAttributeIndexCapture computeSizeCapture( matmulOp.computeTileSizeAttr()); if (computeSizeCapture.size()) { iComputeTileSize = computeSizeCapture.getLiteral(0); jComputeTileSize = computeSizeCapture.getLiteral(1); kComputeTileSize = computeSizeCapture.getLiteral(2); } // If we simdize, its along M for the full compute tile. IndexExpr vectorLen = jComputeTileSize; if (!vectorLen.isLiteral()) { // Cannot simdize if the vector length is not a compile time constant. simdize = false; LLVM_DEBUG(llvm::dbgs() << "Matmul: No simd due to vl not a literal\n"); } if (!simdize) vectorLen = LiteralIndexExpr(1); // Now get global start indices, which would define the first element of the // tiles in the original computations. DimIndexExpr iComputeStart(operandAdaptor.iComputeStart()), jComputeStart(operandAdaptor.jComputeStart()), kComputeStart(operandAdaptor.kComputeStart()); // And get the global upper bound of the original computations. SymbolIndexExpr iGlobalUB(operandAdaptor.iGlobalUB()), jGlobalUB(operandAdaptor.jGlobalUB()), kGlobalUB(operandAdaptor.kGlobalUB()); // A[i, k]; SmallVector<IndexExpr, 4> aStart, bStart, cStart; for (int t = 0; t < aRank - 2; t++) aStart.emplace_back(SymbolIndexExpr(operandAdaptor.aMemStart()[t])); aStart.emplace_back( iComputeStart - DimIndexExpr(operandAdaptor.aMemStart()[aRank - 2])); aStart.emplace_back( kComputeStart - DimIndexExpr(operandAdaptor.aMemStart()[aRank - 1])); // B[k, j]; for (int t = 0; t < bRank - 2; t++) bStart.emplace_back(SymbolIndexExpr(operandAdaptor.bMemStart()[t])); bStart.emplace_back( kComputeStart - DimIndexExpr(operandAdaptor.bMemStart()[bRank - 2])); bStart.emplace_back( jComputeStart - DimIndexExpr(operandAdaptor.bMemStart()[bRank - 1])); // C[i, j] for (int t = 0; t < cRank - 2; t++) cStart.emplace_back(SymbolIndexExpr(operandAdaptor.cMemStart()[t])); cStart.emplace_back( iComputeStart - DimIndexExpr(operandAdaptor.cMemStart()[cRank - 2])); cStart.emplace_back( jComputeStart - DimIndexExpr(operandAdaptor.cMemStart()[cRank - 1])); // Now determine if we have full/partial tiles. This is determined by the // outer dimensions of the original computations, as by definition tiling // within the buffer always results in full tiles. In other words, partial // tiles only occurs because of "runing out" of the original data. IndexExpr iIsFullTile = isFullTile(iGlobalUB, iComputeTileSize, iComputeStart); IndexExpr jIsFullTile = isFullTile(jGlobalUB, jComputeTileSize, jComputeStart); IndexExpr kIsFullTile = isFullTile(kGlobalUB, kComputeTileSize, kComputeStart); SmallVector<IndexExpr, 3> allFullTiles = { iIsFullTile, jIsFullTile, kIsFullTile}; SmallVector<IndexExpr, 1> jFullTiles = {jIsFullTile}; // And if the tiles are not full, determine how many elements to compute. // With overcompute, this could be relaxed. IndexExpr iTrip = trip( iGlobalUB, iComputeTileSize, iComputeStart); // May or may not be full. IndexExpr jTrip = trip( jGlobalUB, jComputeTileSize, jComputeStart); // May or may not be full. IndexExpr kTrip = trip( kGlobalUB, kComputeTileSize, kComputeStart); // May or may not be full. IndexExpr jPartialTrip = partialTrip(jGlobalUB, jComputeTileSize, jComputeStart); if (simdize) { // SIMD code generator. // clang-format off createAffine.ifThenElse(indexScope, allFullTiles, /* then full tiles */ [&](AffineBuilderKrnlMem &createAffine) { genSimd(rewriter, loc, matmulOp, elementType, aStart, bStart, cStart, iComputeTileSize, jComputeTileSize, kComputeTileSize, vectorLen, fullUnrollAndJam); }, /* has some partial tiles */ [&](AffineBuilderKrnlMem &createAffine) { // Trip regardless of full/partial for N & K // Test if SIMD dim (M) is full. createAffine.ifThenElse(indexScope, jFullTiles, /* full SIMD */ [&](AffineBuilderKrnlMem &createAffine) { genSimd(rewriter, loc, matmulOp, elementType, aStart, bStart, cStart, iTrip, jComputeTileSize, kTrip, vectorLen, /*unroll*/ false); }, /* else partial SIMD */ [&](AffineBuilderKrnlMem &createAffine) { // TODO: evaluate if get performance from partial SIMD if (false && jPartialTrip.isLiteral() && jPartialTrip.getLiteral() >=2) { // has a known trip count along the simd dimension of at least 2 // elements, use simd again. genSimd(rewriter, loc, matmulOp, elementType, aStart, bStart, cStart, iTrip, jPartialTrip, kTrip, vectorLen, /*unroll*/ false); } else { genScalar(rewriter, matmulOp, elementType, aStart, bStart, cStart, iTrip, jPartialTrip, kTrip, /*unroll*/ false); } }); }); // clang-format on } else { // Scalar code generator. // clang-format off createAffine.ifThenElse(indexScope, allFullTiles, /* then full */ [&](AffineBuilderKrnlMem &createAffine) { genScalar(rewriter, matmulOp, elementType, aStart, bStart, cStart, iComputeTileSize, jComputeTileSize, kComputeTileSize, fullUnrollAndJam); }, /* else partial */ [&](AffineBuilderKrnlMem &createAffine) { genScalar(rewriter, matmulOp, elementType, aStart, bStart, cStart, iTrip, jTrip, kTrip, false); }); // clang-format on } rewriter.eraseOp(op); return success(); } private: void genScalar(PatternRewriter &rewriter, KrnlMatMulOp op, Type elementType, ArrayRef<IndexExpr> aStart, ArrayRef<IndexExpr> bStart, ArrayRef<IndexExpr> cStart, IndexExpr I, IndexExpr J, IndexExpr K, bool unrollJam) const { // Get operands. KrnlMatMulOpAdaptor operandAdaptor(op); Location loc = op.getLoc(); AffineBuilderKrnlMem createAffine(rewriter, loc); MemRefBuilder createMemRef(createAffine); Value A(operandAdaptor.A()), B(operandAdaptor.B()), C(operandAdaptor.C()); int64_t aRank(aStart.size()), bRank(bStart.size()), cRank(cStart.size()); int64_t unrollFactor = (unrollJam && J.isLiteral()) ? J.getLiteral() : 1; // Have to privatize CTmpType by unroll factor (1 if none). MemRefType CTmpType = MemRefType::get({unrollFactor}, elementType); assert(BUFFER_ALIGN >= gDefaultAllocAlign); Value TmpC = createMemRef.alignedAlloc(CTmpType, BUFFER_ALIGN); // For i, j loops. LiteralIndexExpr zero(0); Value jSaved; createAffine.forIE( zero, I, 1, [&](AffineBuilderKrnlMem &createAffine, Value i) { createAffine.forIE( zero, J, 1, [&](AffineBuilderKrnlMem &createAffine, Value j) { MathBuilder createMath(createAffine); // Defines induction variables, and possibly initialize C. jSaved = j; // Alloc and init temp c storage. SmallVector<Value, 4> cAccess; // CC(i + cStart0.getValue(), j + cStart1.getValue()); IndexExpr::getValues(cStart, cAccess); cAccess[cRank - 2] = createMath.add(i, cAccess[cRank - 2]); cAccess[cRank - 1] = createMath.add(j, cAccess[cRank - 1]); Value initVal = createAffine.load(C, cAccess); Value tmpCAccess = (unrollFactor > 1) ? j : zero.getValue(); createAffine.store(initVal, TmpC, tmpCAccess); // TTmpC() = affine_load(C, cAccess); // Sum over k. createAffine.forIE(zero, K, 1, [&](AffineBuilderKrnlMem &createAffine, Value k) { MathBuilder createMath(createAffine); SmallVector<Value, 4> aAccess, bAccess; // AA(i + aStart0.getValue(), k + aStart1.getValue()) IndexExpr::getValues(aStart, aAccess); aAccess[aRank - 2] = createMath.add(i, aAccess[aRank - 2]); aAccess[aRank - 1] = createMath.add(k, aAccess[aRank - 1]); Value a = createAffine.load(A, aAccess); // BB(k + bStart0.getValue(), j + bStart1.getValue()) IndexExpr::getValues(bStart, bAccess); bAccess[bRank - 2] = createMath.add(k, bAccess[bRank - 2]); bAccess[bRank - 1] = createMath.add(j, bAccess[bRank - 1]); Value b = createAffine.load(B, bAccess); Value res = createMath.mul(a, b); res = createMath.add( res, createAffine.load(TmpC, tmpCAccess)); createAffine.store(res, TmpC, tmpCAccess); // TTmpC() = a * b + TTmpC(); }); // Store temp result into C(i, j) Value finalVal = createAffine.load(TmpC, tmpCAccess); createAffine.store(finalVal, C, cAccess); // affine_store(TTmpC(), C, cAccess); }); }); if (unrollJam && J.isLiteral()) { UnrollAndJamRecord record( getForInductionVarOwner(jSaved), J.getLiteral()); getUnrollAndJamList(op)->emplace_back(record); } } void genSimd(PatternRewriter &rewriter, Location loc, KrnlMatMulOp op, Type elementType, ArrayRef<IndexExpr> aStart, ArrayRef<IndexExpr> bStart, ArrayRef<IndexExpr> cStart, IndexExpr I, IndexExpr J, IndexExpr K, IndexExpr vectorLen, bool unrollJam) const { // can simdize only if K is compile time assert(J.isLiteral() && "can only simdize with compile time blocking factor on simd axis"); AffineBuilderKrnlMem createAffine(rewriter, loc); MemRefBuilder createMemRef(rewriter, loc); // Get operands. KrnlMatMulOpAdaptor operandAdaptor = KrnlMatMulOpAdaptor(op); Value A(operandAdaptor.A()), B(operandAdaptor.B()), C(operandAdaptor.C()); int64_t aRank(aStart.size()), bRank(bStart.size()), cRank(cStart.size()); // Generate the vector type conversions. int64_t VL = vectorLen.getLiteral(); VectorType vecType = VectorType::get({VL}, elementType); int64_t unrollFactor = (unrollJam && I.isLiteral()) ? I.getLiteral() : 1; // Have to privatize CTmpType by unroll factor (1 if none). MemRefType CTmpType = MemRefType::get({unrollFactor}, vecType); assert(BUFFER_ALIGN >= gDefaultAllocAlign); Value TmpC = createMemRef.alignedAlloca(CTmpType, BUFFER_ALIGN); // Iterates over the I indices (j are simd dim). Value iSaved, kSaved; LiteralIndexExpr zero(0); createAffine.forIE( zero, I, 1, [&](AffineBuilderKrnlMem &createAffine, Value i) { MultiDialectBuilder<MathBuilder, VectorBuilder> create(createAffine); iSaved = i; // Saved for unroll and jam. // Alloca temp vector TmpC and save C(i)/0.0 into it. SmallVector<Value, 4> cAccess; // cAccess = {i + cStart0.getValue(), cStart1.getValue()}; IndexExpr::getValues(cStart, cAccess); cAccess[cRank - 2] = create.math.add(i, cAccess[cRank - 2]); Value initVal = create.vec.load(vecType, C, cAccess); Value tmpCAccess = (unrollFactor > 1) ? i : zero.getValue(); createAffine.store(initVal, TmpC, tmpCAccess); // Sum over k. createAffine.forIE( zero, K, 1, [&](AffineBuilderKrnlMem &createAffine, Value k) { MultiDialectBuilder<MathBuilder, VectorBuilder> create( createAffine); kSaved = k; // Value a = AA(i + aStart0.getValue(), k + aStart1.getValue()); SmallVector<Value, 4> aAccess, bAccess; IndexExpr::getValues(aStart, aAccess); aAccess[aRank - 2] = create.math.add(i, aAccess[aRank - 2]); aAccess[aRank - 1] = create.math.add(k, aAccess[aRank - 1]); Value a = createAffine.load(A, aAccess); // Value va = vector_broadcast(vecType, a); Value va = create.vec.broadcast(vecType, a); // bAccess = {k + bStart0.getValue(), bStart1.getValue()}; IndexExpr::getValues(bStart, bAccess); bAccess[bRank - 2] = create.math.add(k, bAccess[bRank - 2]); Value vb = create.vec.load(vecType, B, bAccess); // TTmpC() = vector_fma(va, vb, TTmpC()); Value tmpVal = createAffine.load(TmpC, tmpCAccess); Value res = create.vec.fma(va, vb, tmpVal); createAffine.store(res, TmpC, tmpCAccess); }); // Store temp result into C(i) Value tmpResults = createAffine.load(TmpC, tmpCAccess); int64_t JLit = J.getLiteral(); if (JLit != VL) { // create vector constant SmallVector<int64_t, 8> mask; for (int64_t i = 0; i < VL; i++) mask.emplace_back((i < JLit) ? i : VL + i); // permute Value originalCvec = create.vec.load(vecType, C, cAccess); tmpResults = create.vec.shuffle(tmpResults, originalCvec, mask); } // CCvec(i + CStart0.getValue(), CStart1.getValue()) = tmpResults; create.vec.store(tmpResults, C, cAccess); }); if (unrollJam && (I.isLiteral() || K.isLiteral())) { auto list = getUnrollAndJamList(op); if (K.isLiteral()) { int64_t kUnroll = K.getLiteral(); // We know there is no unrolling along I, make a bigger cutoff. int64_t cutoff = (!I.isLiteral() || I.getLiteral() < 2) ? 8 : 4; if (kUnroll >= cutoff) { // When kUnroll is too big, reduce it by a divisor. for (int64_t m = cutoff; m >= 1; --m) { if (kUnroll % m == 0) { kUnroll = m; break; } } } if (kUnroll > 1) { LLVM_DEBUG( llvm::dbgs() << "Matmul: unroll k by " << kUnroll << "\n";); UnrollAndJamRecord record(getForInductionVarOwner(kSaved), kUnroll); list->emplace_back(record); } } if (I.isLiteral() && I.getLiteral() > 1) { LLVM_DEBUG(llvm::dbgs() << "Matmul: unroll i by " << (int)I.getLiteral() << "\n"); UnrollAndJamRecord record( getForInductionVarOwner(iSaved), I.getLiteral()); list->emplace_back(record); } } } UnrollAndJamList *getUnrollAndJamList(Operation *op) const { Operation *currFuncOp = getContainingFunction(op); assert(currFuncOp && "function expected"); const std::lock_guard<std::mutex> lock(unrollAndJamMutex); UnrollAndJamList *currUnrollAndJamList = unrollAndJamMap[currFuncOp]; assert(currUnrollAndJamList && "expected list for function"); return currUnrollAndJamList; } }; void populateLoweringKrnlMatmultOpPattern(TypeConverter &typeConverter, RewritePatternSet &patterns, MLIRContext *ctx) { patterns.insert<KrnlMatmulLowering>(typeConverter, ctx); } } // namespace krnl } // namespace onnx_mlir
45.993363
83
0.629708
[ "vector" ]
f662c2eef8959c4e62a14c27a013347e5271e4c2
1,544
cpp
C++
src/main.cpp
cazzwastaken/externalia
1c9db9ff92923cdb9933b4697bce9a6ef8866509
[ "MIT" ]
8
2022-01-13T20:58:06.000Z
2022-03-06T20:20:32.000Z
src/main.cpp
cazzwastaken/externalia
1c9db9ff92923cdb9933b4697bce9a6ef8866509
[ "MIT" ]
null
null
null
src/main.cpp
cazzwastaken/externalia
1c9db9ff92923cdb9933b4697bce9a6ef8866509
[ "MIT" ]
null
null
null
#include <iostream> #include <format> #include <thread> #include <algorithm> #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include "globals.h" #include "ui.h" #include "hacks/hacks.h" const int dialog(const std::string& text) noexcept { MessageBeep(MB_ICONERROR); return MessageBox( u::window ? u::window : NULL, text.c_str(), "Externalia", MB_ICONERROR | MB_OK ); } int __stdcall WinMain( const HINSTANCE instance, const HINSTANCE prev_instance, const LPSTR args, const int cmd_show ) { m::process_id("csgo.exe"); if (m::id == 0) { dialog("Please open cs:go!"); return 1; } // wait for csgo to load modules while (!m::module_address("serverbrowser.dll")) { std::this_thread::sleep_for(std::chrono::milliseconds(200)); } m::client = m::module_address("client.dll"); m::engine = m::module_address("engine.dll"); if (m::client == 0 || m::engine == 0) { return dialog("Failed to get module addresses."); } // create ui if (!m::open_handle()) { return dialog("Failed to open a handle to the game."); } if (!u::create_window("externalia")) { return dialog("Failed to create window."); } if (!u::create_device()) { u::destroy_window(); return dialog("Failed to create device."); } u::create_menu(); std::thread{ g::entities }.detach(); std::thread{ h::visuals }.detach(); while (g::run) { u::render(); std::this_thread::sleep_for(std::chrono::milliseconds(5)); } // cleanup u::destroy_menu(); u::destroy_device(); u::destroy_window(); m::close_handle(); return 0; }
19.061728
62
0.660622
[ "render" ]
f663edf7c8836b68499c4ed224983a776fa078f5
4,979
cpp
C++
openstudiocore/src/openstudio_lib/HVACTemplateHelperDialog.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-04-21T15:38:54.000Z
2019-04-21T15:38:54.000Z
openstudiocore/src/openstudio_lib/HVACTemplateHelperDialog.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
null
null
null
openstudiocore/src/openstudio_lib/HVACTemplateHelperDialog.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-07-18T06:52:29.000Z
2019-07-18T06:52:29.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. 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 any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * 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, THE UNITED STATES GOVERNMENT, OR ANY 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 "HVACTemplateHelperDialog.hpp" #include "../model/ThermalZone.hpp" #include "../model/ThermalZone_Impl.hpp" #include <QVBoxLayout> #include <QHBoxLayout> #include <QButtonGroup> #include <QPushButton> #include <QCheckBox> #include <QLabel> #include <QFrame> #include <QScrollArea> namespace openstudio { HVACTemplateHelperDialog::HVACTemplateHelperDialog(const model::Model & model, QWidget * parent) : QDialog(parent), m_model(model) { setMinimumSize(200,200); setSizeGripEnabled(false); auto mainVLayout = new QVBoxLayout(); mainVLayout->setSpacing(20); setLayout(mainVLayout); QLabel * message = new QLabel("Select zones to apply system to."); mainVLayout->addWidget(message); auto divider1 = new QFrame(); divider1->setFrameShape(QFrame::HLine); divider1->setFrameShadow(QFrame::Sunken); mainVLayout->addWidget(divider1); auto scrollArea = new QScrollArea(); mainVLayout->addWidget(scrollArea); auto scrollWidget = new QWidget(); scrollArea->setWidget(scrollWidget); scrollArea->setWidgetResizable(true); scrollArea->setFrameShape(QFrame::NoFrame); auto scrollLayout = new QVBoxLayout(); scrollLayout->setSpacing(20); scrollWidget->setLayout(scrollLayout); m_buttonGroup = new QButtonGroup(); m_buttonGroup->setExclusive(false); m_zones = m_model.getConcreteModelObjects<model::ThermalZone>(); int i = 1; for( auto it = m_zones.begin(); it < m_zones.end(); ++it ) { auto checkBox = new QCheckBox(); checkBox->setText(QString::fromStdString(it->name().get())); m_buttonGroup->addButton(checkBox,i); scrollLayout->addWidget(checkBox); i++; } auto divider2 = new QFrame(); divider2->setFrameShape(QFrame::HLine); divider2->setFrameShadow(QFrame::Sunken); mainVLayout->addWidget(divider2); mainVLayout->addStretch(); auto hLayout = new QHBoxLayout(); mainVLayout->addLayout(hLayout); hLayout->addStretch(); auto cancelButton = new QPushButton(); cancelButton->setText("Cancel"); hLayout->addWidget(cancelButton); connect(cancelButton, &QPushButton::clicked, this, &HVACTemplateHelperDialog::reject); auto okButton = new QPushButton(); okButton->setText("OK"); hLayout->addWidget(okButton); connect(okButton, &QPushButton::clicked, this, &HVACTemplateHelperDialog::accept); } std::vector<model::ThermalZone> HVACTemplateHelperDialog::selectedZones() { std::vector<model::ThermalZone> result; int i = 1; for( auto it = m_zones.begin(); it < m_zones.end(); ++it ) { QCheckBox * checkBox = qobject_cast<QCheckBox *>(m_buttonGroup->button(i)); if( checkBox->isChecked() ) { result.push_back( *it ); } i++; } return result; } } // openstudio
34.576389
120
0.699538
[ "vector", "model" ]
f6642de7f9fe8a6355a6190e9a730e3d884b0f74
14,983
cpp
C++
eagleeye/framework/pipeline/AnyNode.cpp
nihui/eagleeye
eeb69204b7322e79904a4406b44d61a1a30a5c9a
[ "Apache-2.0" ]
4
2020-06-19T06:46:01.000Z
2021-05-14T08:10:42.000Z
eagleeye/framework/pipeline/AnyNode.cpp
nihui/eagleeye
eeb69204b7322e79904a4406b44d61a1a30a5c9a
[ "Apache-2.0" ]
null
null
null
eagleeye/framework/pipeline/AnyNode.cpp
nihui/eagleeye
eeb69204b7322e79904a4406b44d61a1a30a5c9a
[ "Apache-2.0" ]
null
null
null
#include "eagleeye/framework/pipeline/AnyNode.h" #include "eagleeye/common/EagleeyeLog.h" #include "eagleeye/common/EagleeyeTime.h" #include<iostream> namespace eagleeye{ bool AnyNode::m_saved_resource = false; AnyNode::AnyNode(const char* unit_name) :AnyUnit(unit_name){ m_updating_flag = false; this->m_call_once = true; this->m_node_state = 0; this->m_action = 1; // "RUN" this->m_node_is_satisfied_cond = true; } AnyNode::~AnyNode() { std::vector<AnySignal*>::iterator iter,iend(m_output_signals.end()); for (iter = m_output_signals.begin(); iter != iend; ++iter) { if ((*iter)) { delete (*iter); } } } void AnyNode::addInputPort(AnySignal* sig) { m_input_signals.push_back(sig); // increment input signal out degree sig->incrementOutDegree(); modified(); } void AnyNode::setInputPort(AnySignal* sig,int index) { m_input_signals[index] = sig; // increment input signal out degree sig->incrementOutDegree(); modified(); } void AnyNode::removeInputPort(AnySignal* sig) { std::vector<AnySignal*>::iterator iter,iend(m_input_signals.end()); for (iter = m_input_signals.begin();iter != iend; ++iter) { if ((*iter) == sig) { // decrement input signal out degree sig->decrementOutDegree(); (*iter)=NULL; } } modified(); } void AnyNode::removeInputPort(int index) { if (index < int(m_input_signals.size())) { // decrement input signal out degree m_input_signals[index]->decrementOutDegree(); m_input_signals[index]=NULL; } modified(); } AnySignal* AnyNode::getInputPort(unsigned int index) { if (index < m_input_signals.size()) { return m_input_signals[index]; } else { return NULL; } } const AnySignal* AnyNode::getInputPort(unsigned int index) const { if (index < m_input_signals.size()) { return m_input_signals[index]; } else { return NULL; } } AnySignal* AnyNode::getOutputPort(unsigned int index) { if (index < m_output_signals.size()) { return m_output_signals[index]; } else { return NULL; } } const AnySignal* AnyNode::getOutputPort(unsigned int index) const { if (index < m_output_signals.size()) { return m_output_signals[index]; } else { return NULL; } } void AnyNode::setOutputPort(AnySignal* sig,int index) { //does this change anything? if (index < int(m_output_signals.size()) && sig == m_output_signals[index]) { return; } //expand array if necessary if (index >= int(m_output_signals.size())) { setNumberOfOutputSignals(index + 1); } if (m_output_signals[index]) { //delete the old output signal m_output_signals[index]->dislinkAnyNode(this,index); delete m_output_signals[index]; m_output_signals[index] = NULL; } if (sig) { sig->linkAnyNode(this,index); } //save this sig as output signals m_output_signals[index] = sig; modified(); } void AnyNode::setNumberOfOutputSignals(unsigned int outputnum) { if (outputnum != m_output_signals.size()) { std::vector<AnySignal*> output_signals; output_signals.resize(outputnum); std::vector<bool> output_port_states; output_port_states.resize(outputnum); int old_output_signals_num = m_output_signals.size(); if (old_output_signals_num < int(outputnum)) { for (int i = 0; i < old_output_signals_num; ++i) { output_signals[i] = m_output_signals[i]; output_port_states[i] = m_output_port_state[i]; } for (int i = old_output_signals_num; i < int(outputnum); ++i) { output_signals[i] = NULL; output_port_states[i] = true; } } else { for (int i = 0; i < int(outputnum); ++i) { output_signals[i] = m_output_signals[i]; output_port_states[i] = m_output_port_state[i]; } for (int i = outputnum; i < old_output_signals_num; ++i) { if (m_output_signals[i]) { m_output_signals[i]->dislinkAnyNode(this,i); delete m_output_signals[i]; } } } m_output_signals = output_signals; m_output_port_state = output_port_states; } } void AnyNode::setNumberOfInputSignals(unsigned int inputnum) { if (inputnum != m_input_signals.size()) { std::vector<AnySignal*> input_signals; input_signals.resize(inputnum); if (inputnum < m_input_signals.size()) { for (int i = 0; i < int(inputnum); ++i) { input_signals[i] = m_input_signals[i]; } } else { for (int i = 0; i < int(m_input_signals.size()); ++i) { input_signals[i] = m_input_signals[i]; } for (int i = int(m_input_signals.size()); i < int(inputnum); ++i) { input_signals[i] = NULL; } } m_input_signals = input_signals; } } void AnyNode::resetPipeline() { //call modified(), forcelly //Next starting off updateUnitInfo, this node would be update modified(); } AnySignal* AnyNode::makeOutputSignal() { return new AnySignal; } void AnyNode::passonNodeInfo(){ std::vector<AnySignal*>::iterator in_iter,in_iend(m_input_signals.end()); std::vector<AnySignal*>::iterator out_iter,out_iend(m_output_signals.end()); for (in_iter = m_input_signals.begin();in_iter != in_iend; ++in_iter){ for (out_iter = m_output_signals.begin(); out_iter != out_iend; ++out_iter){ (*out_iter)->copyInfo(*in_iter); } break; } } bool AnyNode::start(){ //update some necessary info, such as basic format or struct of AnySignal(without content), //re-assign update time std::vector<AnySignal*>::iterator out_iter,out_iend(m_output_signals.end()); for (out_iter = m_output_signals.begin(); out_iter != out_iend; ++out_iter){ (*out_iter)->updateUnitInfo(); } for (out_iter = m_output_signals.begin(); out_iter != out_iend; ++out_iter){ //complement some concrete task, such as generating some data and so on. (*out_iter)->processUnitInfo(); } // feadback std::map<std::string, int> node_state_map; for (out_iter = m_output_signals.begin(); out_iter != out_iend; ++out_iter){ (*out_iter)->feadback(node_state_map); } return this->isDataHasBeenUpdate(); } void AnyNode::reset(){ //reset pipeline backward std::vector<AnySignal*>::iterator in_iter,in_iend(m_input_signals.end()); for (in_iter = m_input_signals.begin(); in_iter != in_iend; ++in_iter){ (*in_iter)->reset(); } EAGLEEYE_LOGD("reset %s node", this->getUnitName()); } void AnyNode::print(){ //print input signal info std::vector<AnySignal*>::iterator in_iter,in_iend(m_input_signals.end()); for (in_iter = m_input_signals.begin(); in_iter != in_iend; ++in_iter){ (*in_iter)->printUnit(); } //print this node info printUnit(); } void AnyNode::updateUnitInfo() { unsigned long t1,t2; //watch out for loops in the pipeline //prevent from trapping into dead loop if (m_updating_flag) { modified(); return; } //get the parameter update time of of this Node //we now wish to set the PipelineMTime of each output signal // to the largest of this AnyNode's MTime, all input signal's PipelineMTime // , and all input's MTime. We begin with the MTime of this AnyNode. t1 = getMTime(); //Loop through the inputs for (unsigned int idx = 0; idx < m_input_signals.size(); ++idx) { if (m_input_signals[idx]) { AnySignal* input_signal = m_input_signals[idx]; //propagate update unit info //notify the upper unit update m_updating_flag = true; input_signal->updateUnitInfo(); m_updating_flag = false; //What is the PipelineTime of this input signal? Compare this with // our current computation to find the largest one. t2=input_signal->getPipelineTime(); if (t2 > t1) { t1 = t2; } //Pipeline Time of this input signal doesn't include the Time of //this input signal itself. t2 = input_signal->getMTime(); if (t2 > t1) { t1 = t2; } } } //judge whether the current node is need to update if (t1 > m_node_info_mtime.getMTime()) { //If the current node is needed to update, //we need to re-set the Pipeline Time of all output signals //to force them to update for (unsigned int idx = 0;idx < m_output_signals.size(); ++idx) { AnySignal* output_signal = m_output_signals[idx]; // modified by Jian // support output port enable/disable // if output port disable, output signal don't update time // all connected down-stream nodes, wouldn't run if(!this->m_output_port_state[idx]){ continue; } output_signal->setPipelineTime(t1); } //start off passing on node info //now we can use the struct info of all m_input_signals passonNodeInfo(); //record the time that updateUnitInfo() was called m_node_info_mtime.modified(); } this->m_finish_run = false; } void AnyNode::processUnitInfo() { //the upper unit should process unit info firstly. std::vector<AnySignal*>::iterator in_iter,in_iend(m_input_signals.end()); for (in_iter = m_input_signals.begin(); in_iter != in_iend; ++in_iter){ (*in_iter)->processUnitInfo(); } if (isNeedProcessed()){ //execute task //now we can use all info of m_input_signals EAGLEEYE_LOGD("start run execute node (%s)", getUnitName()); long start_time = EagleeyeTime::getCurrentTime(); executeNodeInfo(); long end_time = EagleeyeTime::getCurrentTime(); //clear some compute resource clearSomething(); EAGLEEYE_LOGI("finish run node (%s) -- (%s) (%d us)\n",getClassIdentity(),getUnitName(), int(end_time-start_time)); } else{ //clear some compute resource clearSomething(); EAGLEEYE_LOGI("skip execute node (%s) -- (%s)\n",getClassIdentity(),getUnitName()); } //all info of m_output_signals has been generated //we should change their time stamp std::vector<AnySignal*>::iterator out_iter,out_iend(m_output_signals.end()); for (out_iter = m_output_signals.begin(); out_iter != out_iend; ++out_iter){ (*out_iter)->signalHasBeenUpdate(); } // finish run this->m_finish_run = true; } void AnyNode::getPipelineMonitors(std::map<std::string,std::vector<AnyMonitor*>>& pipeline_monitor_pool) { if(pipeline_monitor_pool.find(getUnitName()) == pipeline_monitor_pool.end()) { pipeline_monitor_pool[getUnitName()] = m_unit_monitor_pool; } //traverse the whole pipeline std::vector<AnySignal*>::iterator signal_iter,signal_iend(m_input_signals.end()); for (signal_iter = m_input_signals.begin();signal_iter != signal_iend; ++signal_iter) { if ((*signal_iter)){ (*signal_iter)->getPipelineMonitors(pipeline_monitor_pool); } } } void AnyNode::getPipelineInputs(std::map<std::string,AnyNode*>& pipeline_inputs){ //traverse the whole pipeline if (m_input_signals.size() > 0){ std::vector<AnySignal*>::iterator signal_iter,signal_iend(m_input_signals.end()); for (signal_iter = m_input_signals.begin();signal_iter != signal_iend; ++signal_iter) { if ((*signal_iter)) (*signal_iter)->getPipelineInputs(pipeline_inputs); else return; } } else{ // start node, std::string input_key = std::string(this->getUnitName()); pipeline_inputs[input_key] = this; } } void AnyNode::getPipelineOutputs(std::map<std::string,AnyNode*>& pipeline_outputs){ pipeline_outputs[this->getUnitName()] = this; } void AnyNode::enableOutputPort(int index) { if (index < int(m_output_port_state.size())) { m_output_port_state[index] = true; } } void AnyNode::disableOutputPort(int index) { if (index < int(m_output_port_state.size())) { m_output_port_state[index] = false; } } bool AnyNode::selfcheck(){ // only run once if(this->m_call_once){ // set default unit name if (std::string(getUnitName()) == std::string("AnyNode")){ setUnitName(getClassIdentity()); } //it configure file exists, loading configure parameters //it would run only once // set false this->m_call_once = false; } return true; } void AnyNode::printUnit(){ EAGLEEYE_LOGI("node id--( %s ) name--( %s ) \n", getClassIdentity(),getUnitName()); } bool AnyNode::isNeedProcessed(){ // check all input signals bool is_need_processed = true; std::vector<AnySignal*>::iterator iter,iend(m_input_signals.end()); for (iter = m_input_signals.begin();iter != iend; ++iter){ if(!(*iter)->isPreparedOK()){ is_need_processed = false; break; } } std::vector<AnySignal*>::iterator o_iter,o_iend(m_output_signals.end()); bool is_one_ok = true; for (o_iter = m_output_signals.begin();o_iter != o_iend; ++o_iter){ is_one_ok = is_one_ok | (*o_iter)->isPreparedOK(); } is_need_processed = is_need_processed & is_one_ok; if(this->getNodeAction() != 1){ is_need_processed = false; } return is_need_processed; } void AnyNode::clearSomething(){ if(AnyNode::m_saved_resource){ // clear middle resource std::vector<AnySignal*>::iterator iter,iend(m_input_signals.end()); for (iter = m_input_signals.begin();iter != iend; ++iter){ EAGLEEYE_LOGD("try clear input resource for node %s",this->getUnitName()); (*iter)->makeempty(); } } } void AnyNode::enableSavedResource(){ AnyNode::m_saved_resource = true; } void AnyNode::disableSavedResource(){ AnyNode::m_saved_resource = false; } void AnyNode::addFeadbackRule(std::string trigger_node, int trigger_node_state, std::string response_action){ this->m_trigger_node.push_back(trigger_node); this->m_trigger_node_state.push_back(trigger_node_state); assert(response_action == "RUN" || response_action == "SKIP"); if(response_action == "RUN"){ this->m_response_actions.push_back(1); } else{ this->m_response_actions.push_back(0); } } void AnyNode::feadback(std::map<std::string, int>& node_state_map){ // change action for(int index=0; index<this->m_trigger_node.size(); ++index){ if(node_state_map.find(this->m_trigger_node[index]) != node_state_map.end()){ if(node_state_map[this->m_trigger_node[index]] == this->m_trigger_node_state[index]){ this->m_action = this->m_response_actions[index]; } } } // add node state into map node_state_map[this->getUnitName()] = this->getNodeState(); // continue to top std::vector<AnySignal*>::iterator signal_iter,signal_iend(m_input_signals.end()); for (signal_iter = m_input_signals.begin();signal_iter != signal_iend; ++signal_iter){ (*signal_iter)->feadback(node_state_map); } } void AnyNode::loadConfigure(std::map<std::string, std::shared_ptr<char>> nodes_config){ // 1.step load node configure if(nodes_config.find(this->m_unit_name) != nodes_config.end()){ this->setUnitPara(nodes_config[this->m_unit_name]); } // 2.step traverse upper nodes std::vector<AnySignal*>::iterator in_iter,in_iend(m_input_signals.end()); for (in_iter = m_input_signals.begin(); in_iter != in_iend; ++in_iter){ (*in_iter)->loadConfigure(nodes_config); } } void AnyNode::saveConfigure(std::map<std::string, std::shared_ptr<char>>& nodes_config){ // 1.step get node configure if(nodes_config.find(this->m_unit_name) == nodes_config.end()){ std::shared_ptr<char> node_param; this->getUnitPara(node_param); nodes_config[this->m_unit_name] = node_param; } // 2.step traverse upper nodes std::vector<AnySignal*>::iterator in_iter,in_iend(m_input_signals.end()); for (in_iter = m_input_signals.begin(); in_iter != in_iend; ++in_iter){ (*in_iter)->saveConfigure(nodes_config); } } }
25.223906
117
0.701996
[ "vector" ]
f667adf16799625ea35e59fc8b7d8965a862b572
39,204
cpp
C++
CapabilityAgents/Alerts/src/AlertsCapabilityAgent.cpp
skrowten-hermit/avs-device-sdk
1255f3398b9c9bdd92d8fcde89c90f19f49eb21d
[ "Apache-2.0" ]
1
2018-06-06T22:13:24.000Z
2018-06-06T22:13:24.000Z
CapabilityAgents/Alerts/src/AlertsCapabilityAgent.cpp
skrowten-hermit/avs-device-sdk
1255f3398b9c9bdd92d8fcde89c90f19f49eb21d
[ "Apache-2.0" ]
null
null
null
CapabilityAgents/Alerts/src/AlertsCapabilityAgent.cpp
skrowten-hermit/avs-device-sdk
1255f3398b9c9bdd92d8fcde89c90f19f49eb21d
[ "Apache-2.0" ]
3
2018-01-26T00:38:43.000Z
2018-03-29T00:28:48.000Z
/* * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 "Alerts/AlertsCapabilityAgent.h" #include "Alerts/Alarm.h" #include "Alerts/Reminder.h" #include "Alerts/Storage/SQLiteAlertStorage.h" #include "Alerts/Timer.h" #include "AVSCommon/AVS/CapabilityConfiguration.h" #include <AVSCommon/AVS/MessageRequest.h> #include <AVSCommon/AVS/SpeakerConstants/SpeakerConstants.h> #include <AVSCommon/Utils/File/FileUtils.h> #include <AVSCommon/Utils/JSON/JSONUtils.h> #include <AVSCommon/Utils/Timing/TimeUtils.h> #include <rapidjson/stringbuffer.h> #include <rapidjson/writer.h> #include <fstream> #include <algorithm> #include <unordered_map> #include <unordered_set> namespace alexaClientSDK { namespace capabilityAgents { namespace alerts { using namespace avsCommon::avs; using namespace avsCommon::utils::configuration; using namespace avsCommon::utils::file; using namespace avsCommon::utils::json::jsonUtils; using namespace avsCommon::utils::logger; using namespace avsCommon::utils::timing; using namespace avsCommon::sdkInterfaces; using namespace certifiedSender; using namespace rapidjson; /// Alerts capability constants /// Alerts interface type static const std::string ALERTS_CAPABILITY_INTERFACE_TYPE = "AlexaInterface"; /// Alerts interface name static const std::string ALERTS_CAPABILITY_INTERFACE_NAME = "Alerts"; /// Alerts interface version static const std::string ALERTS_CAPABILITY_INTERFACE_VERSION = "1.3"; /// The value for Type which we need for json parsing. static const std::string KEY_TYPE = "type"; // ==== Directives === /// The value of the SetAlert Directive. static const std::string DIRECTIVE_NAME_SET_ALERT = "SetAlert"; /// The value of the DeleteAlert Directive. static const std::string DIRECTIVE_NAME_DELETE_ALERT = "DeleteAlert"; /// The value of the DeleteAlerts Directive. static const std::string DIRECTIVE_NAME_DELETE_ALERTS = "DeleteAlerts"; /// The value of the SetVolume Directive. static const std::string DIRECTIVE_NAME_SET_VOLUME = "SetVolume"; /// The value of the AdjustVolume Directive. static const std::string DIRECTIVE_NAME_ADJUST_VOLUME = "AdjustVolume"; // ==== Events === /// The value of the SetAlertSucceeded Event name. static const std::string SET_ALERT_SUCCEEDED_EVENT_NAME = "SetAlertSucceeded"; /// The value of the SetAlertFailed Event name. static const std::string SET_ALERT_FAILED_EVENT_NAME = "SetAlertFailed"; /// The value of the DeleteAlertSucceeded Event name. static const std::string DELETE_ALERT_SUCCEEDED_EVENT_NAME = "DeleteAlertSucceeded"; /// The value of the DeleteAlertFailed Event name. static const std::string DELETE_ALERT_FAILED_EVENT_NAME = "DeleteAlertFailed"; /// The value of the AlertStarted Event name. static const std::string ALERT_STARTED_EVENT_NAME = "AlertStarted"; /// The value of the AlertStopped Event name. static const std::string ALERT_STOPPED_EVENT_NAME = "AlertStopped"; /// The value of the AlertEnteredForeground Event name. static const std::string ALERT_ENTERED_FOREGROUND_EVENT_NAME = "AlertEnteredForeground"; /// The value of the AlertEnteredBackground Event name. static const std::string ALERT_ENTERED_BACKGROUND_EVENT_NAME = "AlertEnteredBackground"; /// The value of the VolumeChanged Event name. static const std::string ALERT_VOLUME_CHANGED_EVENT_NAME = "VolumeChanged"; /// The value of the DeleteAlertsSucceeded Event name. static const std::string ALERT_DELETE_ALERTS_SUCCEEDED_EVENT_NAME = "DeleteAlertsSucceeded"; /// The value of the DeleteAlertsFailed Event name. static const std::string ALERT_DELETE_ALERTS_FAILED_EVENT_NAME = "DeleteAlertsFailed"; // ==== Other constants === /// The value of the event payload key for a single token. static const std::string EVENT_PAYLOAD_TOKEN_KEY = "token"; /// The value of the event payload key for multiple tokens. static const std::string EVENT_PAYLOAD_TOKENS_KEY = "tokens"; /// The value of Token text in a Directive we may receive. static const std::string DIRECTIVE_PAYLOAD_TOKEN_KEY = "token"; /// The value of Token list key in a Directive we may receive. static const std::string DIRECTIVE_PAYLOAD_TOKENS_KEY = "tokens"; /// The value of volume key in a Directive we may receive. static const std::string DIRECTIVE_PAYLOAD_VOLUME = "volume"; static const std::string AVS_CONTEXT_HEADER_NAMESPACE_VALUE_KEY = "Alerts"; /// The value of the Alerts Context Names. static const std::string AVS_CONTEXT_HEADER_NAME_VALUE_KEY = "AlertsState"; /// The value of the Alerts Context allAlerts node. static const std::string AVS_CONTEXT_ALL_ALERTS_TOKEN_KEY = "allAlerts"; /// The value of the Alerts Context activeAlerts node. static const std::string AVS_CONTEXT_ACTIVE_ALERTS_TOKEN_KEY = "activeAlerts"; /// The value of the Alerts Context token key. static const std::string AVS_CONTEXT_ALERT_TOKEN_KEY = "token"; /// The value of the Alerts Context type key. static const std::string AVS_CONTEXT_ALERT_TYPE_KEY = "type"; /// The value of the Alerts Context scheduled time key. static const std::string AVS_CONTEXT_ALERT_SCHEDULED_TIME_KEY = "scheduledTime"; /// The value of the volume state info volume key. static const std::string AVS_PAYLOAD_VOLUME_KEY = "volume"; /// An empty dialogRequestId. static const std::string EMPTY_DIALOG_REQUEST_ID = ""; /// The namespace for this capability agent. static const std::string NAMESPACE = "Alerts"; /// The SetAlert directive signature. static const avsCommon::avs::NamespaceAndName SET_ALERT{NAMESPACE, DIRECTIVE_NAME_SET_ALERT}; /// The DeleteAlert directive signature. static const avsCommon::avs::NamespaceAndName DELETE_ALERT{NAMESPACE, DIRECTIVE_NAME_DELETE_ALERT}; /// The DeleteAlerts directive signature. static const avsCommon::avs::NamespaceAndName DELETE_ALERTS{NAMESPACE, DIRECTIVE_NAME_DELETE_ALERTS}; /// The SetVolume directive signature. static const avsCommon::avs::NamespaceAndName SET_VOLUME{NAMESPACE, DIRECTIVE_NAME_SET_VOLUME}; /// The AdjustVolume directive signature. static const avsCommon::avs::NamespaceAndName ADJUST_VOLUME{NAMESPACE, DIRECTIVE_NAME_ADJUST_VOLUME}; /// String to identify log entries originating from this file. static const std::string TAG("AlertsCapabilityAgent"); /** * Create a LogEntry using this file's TAG and the specified event string. * * @param The event string for this @c LogEntry. */ #define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event) /** * Creates the alerts capability configuration. * * @return The alerts capability configuration. */ static std::shared_ptr<avsCommon::avs::CapabilityConfiguration> getAlertsCapabilityConfiguration(); /** * Utility function to construct a rapidjson array of alert details, representing all the alerts currently managed. * * @param alertsInfo All the alerts being managed by this Capability Agent. * @param allocator The rapidjson allocator, required for the results of this function to be mergable with other * rapidjson::Value objects. * @return The rapidjson::Value representing the array. */ static rapidjson::Value buildAllAlertsContext( const std::vector<Alert::ContextInfo>& alertsInfo, Document::AllocatorType& allocator) { rapidjson::Value alertArray(rapidjson::kArrayType); for (const auto& info : alertsInfo) { rapidjson::Value alertJson; alertJson.SetObject(); alertJson.AddMember(StringRef(AVS_CONTEXT_ALERT_TOKEN_KEY), info.token, allocator); alertJson.AddMember(StringRef(AVS_CONTEXT_ALERT_TYPE_KEY), info.type, allocator); alertJson.AddMember(StringRef(AVS_CONTEXT_ALERT_SCHEDULED_TIME_KEY), info.scheduledTime_ISO_8601, allocator); alertArray.PushBack(alertJson, allocator); } return alertArray; } /** * Utility function to construct a rapidjson array of alert details, representing all the currently active alerts. * * @param alertsInfo The currently active alert, which may be nullptr if no alert is active. * @param allocator The rapidjson allocator, required for the results of this function to be mergable with other * rapidjson::Value objects. * @return The rapidjson::Value representing the array. */ static rapidjson::Value buildActiveAlertsContext( const std::vector<Alert::ContextInfo>& alertsInfo, Document::AllocatorType& allocator) { rapidjson::Value alertArray(rapidjson::kArrayType); if (!alertsInfo.empty()) { auto& info = alertsInfo[0]; rapidjson::Value alertJson; alertJson.SetObject(); alertJson.AddMember(StringRef(AVS_CONTEXT_ALERT_TOKEN_KEY), info.token, allocator); alertJson.AddMember(StringRef(AVS_CONTEXT_ALERT_TYPE_KEY), info.type, allocator); alertJson.AddMember(StringRef(AVS_CONTEXT_ALERT_SCHEDULED_TIME_KEY), info.scheduledTime_ISO_8601, allocator); alertArray.PushBack(alertJson, allocator); } return alertArray; } std::shared_ptr<AlertsCapabilityAgent> AlertsCapabilityAgent::create( std::shared_ptr<avsCommon::sdkInterfaces::MessageSenderInterface> messageSender, std::shared_ptr<avsCommon::sdkInterfaces::AVSConnectionManagerInterface> connectionManager, std::shared_ptr<certifiedSender::CertifiedSender> certifiedMessageSender, std::shared_ptr<avsCommon::sdkInterfaces::FocusManagerInterface> focusManager, std::shared_ptr<avsCommon::sdkInterfaces::SpeakerManagerInterface> speakerManager, std::shared_ptr<avsCommon::sdkInterfaces::ContextManagerInterface> contextManager, std::shared_ptr<avsCommon::sdkInterfaces::ExceptionEncounteredSenderInterface> exceptionEncounteredSender, std::shared_ptr<storage::AlertStorageInterface> alertStorage, std::shared_ptr<avsCommon::sdkInterfaces::audio::AlertsAudioFactoryInterface> alertsAudioFactory, std::shared_ptr<renderer::RendererInterface> alertRenderer, std::shared_ptr<registrationManager::CustomerDataManager> dataManager) { auto alertsCA = std::shared_ptr<AlertsCapabilityAgent>(new AlertsCapabilityAgent( messageSender, certifiedMessageSender, focusManager, speakerManager, contextManager, exceptionEncounteredSender, alertStorage, alertsAudioFactory, alertRenderer, dataManager)); if (!alertsCA->initialize()) { ACSDK_ERROR(LX("createFailed").d("reason", "Initialization error.")); return nullptr; } focusManager->addObserver(alertsCA); connectionManager->addConnectionStatusObserver(alertsCA); speakerManager->addSpeakerManagerObserver(alertsCA); return alertsCA; } avsCommon::avs::DirectiveHandlerConfiguration AlertsCapabilityAgent::getConfiguration() const { avsCommon::avs::DirectiveHandlerConfiguration configuration; configuration[SET_ALERT] = avsCommon::avs::BlockingPolicy::NON_BLOCKING; configuration[DELETE_ALERT] = avsCommon::avs::BlockingPolicy::NON_BLOCKING; configuration[DELETE_ALERTS] = avsCommon::avs::BlockingPolicy::NON_BLOCKING; configuration[SET_VOLUME] = avsCommon::avs::BlockingPolicy::NON_BLOCKING; configuration[ADJUST_VOLUME] = avsCommon::avs::BlockingPolicy::NON_BLOCKING; return configuration; } void AlertsCapabilityAgent::handleDirectiveImmediately(std::shared_ptr<avsCommon::avs::AVSDirective> directive) { if (!directive) { ACSDK_ERROR(LX("handleDirectiveImmediatelyFailed").d("reason", "directive is nullptr.")); } auto info = createDirectiveInfo(directive, nullptr); m_executor.submit([this, info]() { executeHandleDirectiveImmediately(info); }); } void AlertsCapabilityAgent::preHandleDirective(std::shared_ptr<DirectiveInfo> info) { // intentional no-op. } void AlertsCapabilityAgent::handleDirective(std::shared_ptr<DirectiveInfo> info) { if (!info) { ACSDK_ERROR(LX("handleDirectiveFailed").d("reason", "info is nullptr.")); } m_executor.submit([this, info]() { executeHandleDirectiveImmediately(info); }); } void AlertsCapabilityAgent::cancelDirective(std::shared_ptr<DirectiveInfo> info) { // intentional no-op. } void AlertsCapabilityAgent::onDeregistered() { // intentional no-op. } void AlertsCapabilityAgent::onConnectionStatusChanged(const Status status, const ChangedReason reason) { m_executor.submit([this, status, reason]() { executeOnConnectionStatusChanged(status, reason); }); } void AlertsCapabilityAgent::onFocusChanged(avsCommon::avs::FocusState focusState) { ACSDK_DEBUG9(LX("onFocusChanged").d("focusState", focusState)); m_executor.submit([this, focusState]() { executeOnFocusChanged(focusState); }); } void AlertsCapabilityAgent::onFocusChanged(const std::string& channelName, avsCommon::avs::FocusState newFocus) { m_executor.submit([this, channelName, newFocus]() { executeOnFocusManagerFocusChanged(channelName, newFocus); }); } void AlertsCapabilityAgent::onAlertStateChange( const std::string& alertToken, AlertObserverInterface::State state, const std::string& reason) { ACSDK_DEBUG9(LX("onAlertStateChange").d("alertToken", alertToken).d("state", state).d("reason", reason)); m_executor.submit([this, alertToken, state, reason]() { executeOnAlertStateChange(alertToken, state, reason); }); } void AlertsCapabilityAgent::addObserver(std::shared_ptr<AlertObserverInterface> observer) { if (!observer) { ACSDK_ERROR(LX("addObserverFailed").d("reason", "nullObserver")); return; } m_executor.submit([this, observer]() { executeAddObserver(observer); }); } void AlertsCapabilityAgent::removeObserver(std::shared_ptr<AlertObserverInterface> observer) { if (!observer) { ACSDK_ERROR(LX("removeObserverFailed").d("reason", "nullObserver")); return; } m_executor.submit([this, observer]() { executeRemoveObserver(observer); }); } void AlertsCapabilityAgent::removeAllAlerts() { m_executor.submit([this]() { executeRemoveAllAlerts(); }); } void AlertsCapabilityAgent::onLocalStop() { ACSDK_DEBUG9(LX("onLocalStop")); m_executor.submitToFront([this]() { executeOnLocalStop(); }); } AlertsCapabilityAgent::AlertsCapabilityAgent( std::shared_ptr<avsCommon::sdkInterfaces::MessageSenderInterface> messageSender, std::shared_ptr<certifiedSender::CertifiedSender> certifiedMessageSender, std::shared_ptr<avsCommon::sdkInterfaces::FocusManagerInterface> focusManager, std::shared_ptr<avsCommon::sdkInterfaces::SpeakerManagerInterface> speakerManager, std::shared_ptr<avsCommon::sdkInterfaces::ContextManagerInterface> contextManager, std::shared_ptr<avsCommon::sdkInterfaces::ExceptionEncounteredSenderInterface> exceptionEncounteredSender, std::shared_ptr<storage::AlertStorageInterface> alertStorage, std::shared_ptr<avsCommon::sdkInterfaces::audio::AlertsAudioFactoryInterface> alertsAudioFactory, std::shared_ptr<renderer::RendererInterface> alertRenderer, std::shared_ptr<registrationManager::CustomerDataManager> dataManager) : CapabilityAgent("Alerts", exceptionEncounteredSender), RequiresShutdown("AlertsCapabilityAgent"), CustomerDataHandler(dataManager), m_messageSender{messageSender}, m_certifiedSender{certifiedMessageSender}, m_focusManager{focusManager}, m_speakerManager{speakerManager}, m_contextManager{contextManager}, m_isConnected{false}, m_alertScheduler{alertStorage, alertRenderer, ALERT_PAST_DUE_CUTOFF_MINUTES}, m_alertsAudioFactory{alertsAudioFactory} { m_capabilityConfigurations.insert(getAlertsCapabilityConfiguration()); } std::shared_ptr<CapabilityConfiguration> getAlertsCapabilityConfiguration() { std::unordered_map<std::string, std::string> configMap; configMap.insert({CAPABILITY_INTERFACE_TYPE_KEY, ALERTS_CAPABILITY_INTERFACE_TYPE}); configMap.insert({CAPABILITY_INTERFACE_NAME_KEY, ALERTS_CAPABILITY_INTERFACE_NAME}); configMap.insert({CAPABILITY_INTERFACE_VERSION_KEY, ALERTS_CAPABILITY_INTERFACE_VERSION}); return std::make_shared<CapabilityConfiguration>(configMap); } void AlertsCapabilityAgent::doShutdown() { m_executor.shutdown(); releaseChannel(); m_messageSender.reset(); m_certifiedSender.reset(); m_focusManager.reset(); m_contextManager.reset(); m_observers.clear(); m_alertScheduler.shutdown(); } bool AlertsCapabilityAgent::initialize() { if (!initializeAlerts()) { ACSDK_ERROR(LX("initializeFailed").m("Could not initialize alerts.")); return false; } // Initialize stored value for AVS_ALERTS_VOLUME speaker settings if (!getAlertVolumeSettings(&m_lastReportedSpeakerSettings)) { return false; } updateContextManager(); return true; } bool AlertsCapabilityAgent::initializeAlerts() { return m_alertScheduler.initialize(shared_from_this()); } bool AlertsCapabilityAgent::handleSetAlert( const std::shared_ptr<avsCommon::avs::AVSDirective>& directive, const rapidjson::Document& payload, std::string* alertToken) { ACSDK_DEBUG9(LX("handleSetAlert")); std::string alertType; if (!retrieveValue(payload, KEY_TYPE, &alertType)) { std::string errorMessage = "Alert type not specified for SetAlert"; ACSDK_ERROR(LX("handleSetAlertFailed").m(errorMessage)); sendProcessingDirectiveException(directive, errorMessage); return false; } std::shared_ptr<Alert> parsedAlert; if (Alarm::TYPE_NAME == alertType) { parsedAlert = std::make_shared<Alarm>(m_alertsAudioFactory->alarmDefault(), m_alertsAudioFactory->alarmShort()); } else if (Timer::TYPE_NAME == alertType) { parsedAlert = std::make_shared<Timer>(m_alertsAudioFactory->timerDefault(), m_alertsAudioFactory->timerShort()); } else if (Reminder::TYPE_NAME == alertType) { parsedAlert = std::make_shared<Reminder>(m_alertsAudioFactory->reminderDefault(), m_alertsAudioFactory->reminderShort()); } if (!parsedAlert) { ACSDK_ERROR(LX("handleSetAlertFailed").d("reason", "unknown alert type").d("type:", alertType)); return false; } std::string errorMessage; auto parseStatus = parsedAlert->parseFromJson(payload, &errorMessage); if (Alert::ParseFromJsonStatus::MISSING_REQUIRED_PROPERTY == parseStatus) { sendProcessingDirectiveException(directive, "Missing required property."); return false; } else if (Alert::ParseFromJsonStatus::INVALID_VALUE == parseStatus) { sendProcessingDirectiveException(directive, "Invalid value."); return false; } *alertToken = parsedAlert->getToken(); if (m_alertScheduler.isAlertActive(parsedAlert)) { return m_alertScheduler.snoozeAlert(parsedAlert->getToken(), parsedAlert->getScheduledTime_ISO_8601()); } if (!m_alertScheduler.scheduleAlert(parsedAlert)) { return false; } updateContextManager(); return true; } bool AlertsCapabilityAgent::handleDeleteAlert( const std::shared_ptr<avsCommon::avs::AVSDirective>& directive, const rapidjson::Document& payload, std::string* alertToken) { ACSDK_DEBUG5(LX(__func__)); if (!retrieveValue(payload, DIRECTIVE_PAYLOAD_TOKEN_KEY, alertToken)) { ACSDK_ERROR(LX("handleDeleteAlertFailed").m("Could not find token in the payload.")); return false; } if (!m_alertScheduler.deleteAlert(*alertToken)) { return false; } updateContextManager(); return true; } bool AlertsCapabilityAgent::handleDeleteAlerts( const std::shared_ptr<avsCommon::avs::AVSDirective>& directive, const rapidjson::Document& payload) { ACSDK_DEBUG5(LX(__func__)); std::list<std::string> alertTokens; auto tokensPayload = payload.FindMember(DIRECTIVE_PAYLOAD_TOKENS_KEY.c_str()); if (tokensPayload == payload.MemberEnd()) { ACSDK_ERROR(LX("handleDeleteAlertsFailed").d("reason", "Cannot find tokens in payload")); return false; } if (!tokensPayload->value.IsArray()) { ACSDK_ERROR(LX("handleDeleteAlertsFailed") .d("reason", "value is expected to be an array") .d("key", DIRECTIVE_PAYLOAD_TOKENS_KEY.c_str())); return false; } auto tokenArray = tokensPayload->value.GetArray(); for (rapidjson::SizeType i = 0; i < tokenArray.Size(); i++) { std::string token; if (!convertToValue(tokenArray[i], &token)) { ACSDK_WARN(LX("handleDeleteAlertsFailed").d("reason", "invalid token in payload")); continue; } alertTokens.push_back(token); } if (!m_alertScheduler.deleteAlerts(alertTokens)) { sendBulkEvent(ALERT_DELETE_ALERTS_FAILED_EVENT_NAME, alertTokens, true); return false; } sendBulkEvent(ALERT_DELETE_ALERTS_SUCCEEDED_EVENT_NAME, alertTokens, true); updateContextManager(); return true; } bool AlertsCapabilityAgent::handleSetVolume( const std::shared_ptr<avsCommon::avs::AVSDirective>& directive, const rapidjson::Document& payload) { ACSDK_DEBUG5(LX(__func__)); int64_t volumeValue = 0; if (!retrieveValue(payload, DIRECTIVE_PAYLOAD_VOLUME, &volumeValue)) { ACSDK_ERROR(LX("handleSetVolumeFailed").m("Could not find volume in the payload.")); return false; } setNextAlertVolume(volumeValue); return true; } bool AlertsCapabilityAgent::handleAdjustVolume( const std::shared_ptr<avsCommon::avs::AVSDirective>& directive, const rapidjson::Document& payload) { ACSDK_DEBUG5(LX(__func__)); int64_t adjustValue = 0; if (!retrieveValue(payload, DIRECTIVE_PAYLOAD_VOLUME, &adjustValue)) { ACSDK_ERROR(LX("handleAdjustVolumeFailed").m("Could not find volume in the payload.")); return false; } SpeakerInterface::SpeakerSettings speakerSettings; m_speakerManager->getSpeakerSettings(SpeakerInterface::Type::AVS_ALERTS_VOLUME, &speakerSettings); int64_t volume = adjustValue + speakerSettings.volume; setNextAlertVolume(volume); return true; } void AlertsCapabilityAgent::sendEvent(const std::string& eventName, const std::string& alertToken, bool isCertified) { rapidjson::Document payload(kObjectType); rapidjson::Document::AllocatorType& alloc = payload.GetAllocator(); payload.AddMember(StringRef(EVENT_PAYLOAD_TOKEN_KEY), alertToken, alloc); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); if (!payload.Accept(writer)) { ACSDK_ERROR(LX("sendEventFailed").m("Could not construct payload.")); return; } auto jsonEventString = buildJsonEventString(eventName, EMPTY_DIALOG_REQUEST_ID, buffer.GetString()).second; if (isCertified) { m_certifiedSender->sendJSONMessage(jsonEventString); } else { if (!m_isConnected) { ACSDK_WARN( LX("sendEvent").m("Not connected to AVS. Not sending Event.").d("event details", jsonEventString)); } else { auto request = std::make_shared<MessageRequest>(jsonEventString); m_messageSender->sendMessage(request); } } } void AlertsCapabilityAgent::sendBulkEvent( const std::string& eventName, const std::list<std::string>& tokenList, bool isCertified) { rapidjson::Document payload(kObjectType); rapidjson::Document::AllocatorType& alloc = payload.GetAllocator(); rapidjson::Value jsonTokenList(kArrayType); for (auto& token : tokenList) { jsonTokenList.PushBack(StringRef(token), alloc); } payload.AddMember(StringRef(EVENT_PAYLOAD_TOKENS_KEY), jsonTokenList, alloc); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); if (!payload.Accept(writer)) { ACSDK_ERROR(LX("sendBulkEventFailed").m("Could not construct payload.")); return; } auto jsonEventString = buildJsonEventString(eventName, EMPTY_DIALOG_REQUEST_ID, buffer.GetString()).second; if (isCertified) { m_certifiedSender->sendJSONMessage(jsonEventString); } else { if (!m_isConnected) { ACSDK_WARN(LX(__func__).m("Not connected to AVS. Not sending Event.").d("event details", jsonEventString)); } else { auto request = std::make_shared<MessageRequest>(jsonEventString); m_messageSender->sendMessage(request); } } } void AlertsCapabilityAgent::updateAVSWithLocalVolumeChanges(int8_t volume, bool forceUpdate) { if (!forceUpdate && volume == m_lastReportedSpeakerSettings.volume) { // Current speaker volume corresponds to what AVS has ACSDK_DEBUG7(LX("updateAVSWithLocalVolumeChanges").d("Alerts volume already set to this value", volume)); return; } m_lastReportedSpeakerSettings.volume = volume; rapidjson::Document payload(kObjectType); rapidjson::Document::AllocatorType& alloc = payload.GetAllocator(); payload.AddMember(StringRef(AVS_PAYLOAD_VOLUME_KEY), volume, alloc); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); if (!payload.Accept(writer)) { ACSDK_ERROR(LX("updateAVSWithLocalVolumeChangesFailed").m("Could not construct payload.")); return; } auto jsonEventString = buildJsonEventString(ALERT_VOLUME_CHANGED_EVENT_NAME, EMPTY_DIALOG_REQUEST_ID, buffer.GetString()).second; m_certifiedSender->sendJSONMessage(jsonEventString); } void AlertsCapabilityAgent::sendProcessingDirectiveException( const std::shared_ptr<AVSDirective>& directive, const std::string& errorMessage) { auto unparsedDirective = directive->getUnparsedDirective(); ACSDK_ERROR( LX("sendProcessingDirectiveException").m("Could not parse directive.").m(errorMessage).m(unparsedDirective)); m_exceptionEncounteredSender->sendExceptionEncountered( unparsedDirective, ExceptionErrorType::UNEXPECTED_INFORMATION_RECEIVED, errorMessage); } void AlertsCapabilityAgent::acquireChannel() { ACSDK_DEBUG9(LX("acquireChannel")); m_focusManager->acquireChannel(FocusManagerInterface::ALERTS_CHANNEL_NAME, shared_from_this(), NAMESPACE); } void AlertsCapabilityAgent::releaseChannel() { ACSDK_DEBUG9(LX("releaseChannel")); if (m_alertScheduler.getFocusState() != FocusState::NONE) { m_focusManager->releaseChannel(FocusManagerInterface::ALERTS_CHANNEL_NAME, shared_from_this()); } } void AlertsCapabilityAgent::executeHandleDirectiveImmediately(std::shared_ptr<DirectiveInfo> info) { ACSDK_DEBUG1(LX("executeHandleDirectiveImmediately")); auto& directive = info->directive; rapidjson::Document payload; payload.Parse(directive->getPayload()); if (payload.HasParseError()) { std::string errorMessage = "Unable to parse payload"; ACSDK_ERROR(LX("executeHandleDirectiveImmediatelyFailed").m(errorMessage)); sendProcessingDirectiveException(directive, errorMessage); return; } auto directiveName = directive->getName(); std::string alertToken; if (DIRECTIVE_NAME_SET_ALERT == directiveName) { if (handleSetAlert(directive, payload, &alertToken)) { sendEvent(SET_ALERT_SUCCEEDED_EVENT_NAME, alertToken, true); } else { sendEvent(SET_ALERT_FAILED_EVENT_NAME, alertToken, true); } } else if (DIRECTIVE_NAME_DELETE_ALERT == directiveName) { if (handleDeleteAlert(directive, payload, &alertToken)) { sendEvent(DELETE_ALERT_SUCCEEDED_EVENT_NAME, alertToken, true); } else { sendEvent(DELETE_ALERT_FAILED_EVENT_NAME, alertToken, true); } } else if (DIRECTIVE_NAME_DELETE_ALERTS == directiveName) { handleDeleteAlerts(directive, payload); } else if (DIRECTIVE_NAME_SET_VOLUME == directiveName) { handleSetVolume(directive, payload); } else if (DIRECTIVE_NAME_ADJUST_VOLUME == directiveName) { handleAdjustVolume(directive, payload); } } void AlertsCapabilityAgent::executeOnConnectionStatusChanged(const Status status, const ChangedReason reason) { ACSDK_DEBUG1(LX("executeOnConnectionStatusChanged").d("status", status).d("reason", reason)); m_isConnected = (Status::CONNECTED == status); } void AlertsCapabilityAgent::executeOnFocusChanged(avsCommon::avs::FocusState focusState) { ACSDK_DEBUG1(LX("executeOnFocusChanged").d("focusState", focusState)); m_alertScheduler.updateFocus(focusState); } void AlertsCapabilityAgent::executeOnFocusManagerFocusChanged( const std::string& channelName, avsCommon::avs::FocusState focusState) { bool stateIsActive = focusState != FocusState::NONE; if (FocusManagerInterface::CONTENT_CHANNEL_NAME == channelName) { m_contentChannelIsActive = stateIsActive; } else if (FocusManagerInterface::COMMUNICATIONS_CHANNEL_NAME == channelName) { m_commsChannelIsActive = stateIsActive; } else { return; } if (m_alertIsSounding) { if (!m_commsChannelIsActive && !m_contentChannelIsActive) { // All lower channels of interest are stopped playing content. Return alert volume to base value // if needed. SpeakerInterface::SpeakerSettings speakerSettings; if (!getAlertVolumeSettings(&speakerSettings)) { ACSDK_ERROR(LX("executeOnFocusChangedFailed").d("reason", "Failed to get speaker settings.")); return; } if (speakerSettings.volume > m_lastReportedSpeakerSettings.volume) { // Alert is sounding with volume higher than Base Volume. Assume that it was adjusted because of // content being played and reset it to the base one. Keep lower values, though. m_speakerManager->setVolume( SpeakerInterface::Type::AVS_ALERTS_VOLUME, m_lastReportedSpeakerSettings.volume); } } } } void AlertsCapabilityAgent::executeOnAlertStateChange( const std::string& alertToken, AlertObserverInterface::State state, const std::string& reason) { ACSDK_DEBUG1(LX("executeOnAlertStateChange").d("alertToken", alertToken).d("state", state).d("reason", reason)); bool alertIsActive = false; switch (state) { case AlertObserverInterface::State::READY: acquireChannel(); break; case AlertObserverInterface::State::STARTED: sendEvent(ALERT_STARTED_EVENT_NAME, alertToken, true); updateContextManager(); alertIsActive = true; break; case AlertObserverInterface::State::SNOOZED: releaseChannel(); updateContextManager(); break; case AlertObserverInterface::State::STOPPED: sendEvent(ALERT_STOPPED_EVENT_NAME, alertToken, true); releaseChannel(); updateContextManager(); break; case AlertObserverInterface::State::COMPLETED: sendEvent(ALERT_STOPPED_EVENT_NAME, alertToken, true); releaseChannel(); updateContextManager(); break; case AlertObserverInterface::State::ERROR: releaseChannel(); updateContextManager(); break; case AlertObserverInterface::State::PAST_DUE: sendEvent(ALERT_STOPPED_EVENT_NAME, alertToken, true); break; case AlertObserverInterface::State::FOCUS_ENTERED_FOREGROUND: alertIsActive = true; sendEvent(ALERT_ENTERED_FOREGROUND_EVENT_NAME, alertToken); break; case AlertObserverInterface::State::FOCUS_ENTERED_BACKGROUND: alertIsActive = true; sendEvent(ALERT_ENTERED_BACKGROUND_EVENT_NAME, alertToken); break; } if (alertIsActive) { // Alert is going to go off m_alertIsSounding = true; // Check if there are lower channels with content being played and increase alert volume if needed. if (m_contentChannelIsActive || m_commsChannelIsActive) { SpeakerInterface::SpeakerSettings contentSpeakerSettings; if (getSpeakerVolumeSettings(&contentSpeakerSettings)) { if (m_lastReportedSpeakerSettings.volume < contentSpeakerSettings.volume) { // Adjust alerts volume to be at least as loud as content volume m_speakerManager->setVolume( SpeakerInterface::Type::AVS_ALERTS_VOLUME, contentSpeakerSettings.volume); } } } } else { if (m_alertIsSounding) { // Alert has just switched from STARTED to something else, since it could not transition from STARTED to // READY we may treat it as it is stopping. // Reset Active Alerts Volume volume to the Base Alerts Volume when alert stops m_alertIsSounding = false; m_speakerManager->setVolume( SpeakerInterface::Type::AVS_ALERTS_VOLUME, m_lastReportedSpeakerSettings.volume); } } m_executor.submit([this, alertToken, state, reason]() { executeNotifyObservers(alertToken, state, reason); }); } void AlertsCapabilityAgent::executeAddObserver(std::shared_ptr<AlertObserverInterface> observer) { ACSDK_DEBUG1(LX("executeAddObserver").d("observer", observer.get())); m_observers.insert(observer); } void AlertsCapabilityAgent::executeRemoveObserver(std::shared_ptr<AlertObserverInterface> observer) { ACSDK_DEBUG1(LX("executeRemoveObserver").d("observer", observer.get())); m_observers.erase(observer); } void AlertsCapabilityAgent::executeNotifyObservers( const std::string& alertToken, AlertObserverInterface::State state, const std::string& reason) { ACSDK_DEBUG1(LX("executeNotifyObservers").d("alertToken", alertToken).d("state", state).d("reason", reason)); for (auto observer : m_observers) { observer->onAlertStateChange(alertToken, state, reason); } } void AlertsCapabilityAgent::executeRemoveAllAlerts() { ACSDK_DEBUG1(LX("executeRemoveAllAlerts")); m_alertScheduler.clearData(); } void AlertsCapabilityAgent::executeOnLocalStop() { ACSDK_DEBUG1(LX("executeOnLocalStop")); m_alertScheduler.onLocalStop(); } void AlertsCapabilityAgent::updateContextManager() { std::string contextString = getContextString(); NamespaceAndName namespaceAndName{AVS_CONTEXT_HEADER_NAMESPACE_VALUE_KEY, AVS_CONTEXT_HEADER_NAME_VALUE_KEY}; auto setStateSuccess = m_contextManager->setState(namespaceAndName, contextString, StateRefreshPolicy::NEVER); if (setStateSuccess != SetStateResult::SUCCESS) { ACSDK_ERROR(LX("updateContextManagerFailed") .m("Could not set the state on the contextManager") .d("result", static_cast<int>(setStateSuccess))); } } std::string AlertsCapabilityAgent::getContextString() { rapidjson::Document state(kObjectType); rapidjson::Document::AllocatorType& alloc = state.GetAllocator(); auto alertsContextInfo = m_alertScheduler.getContextInfo(); auto allAlertsJsonValue = buildAllAlertsContext(alertsContextInfo.scheduledAlerts, alloc); auto activeAlertsJsonValue = buildActiveAlertsContext(alertsContextInfo.activeAlerts, alloc); state.AddMember(StringRef(AVS_CONTEXT_ALL_ALERTS_TOKEN_KEY), allAlertsJsonValue, alloc); state.AddMember(StringRef(AVS_CONTEXT_ACTIVE_ALERTS_TOKEN_KEY), activeAlertsJsonValue, alloc); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); if (!state.Accept(writer)) { ACSDK_ERROR(LX("getContextStringFailed").d("reason", "writerRefusedJsonObject")); return ""; } return buffer.GetString(); } void AlertsCapabilityAgent::clearData() { auto result = m_executor.submit([this]() { m_alertScheduler.clearData(Alert::StopReason::LOG_OUT); }); result.wait(); } std::unordered_set<std::shared_ptr<avsCommon::avs::CapabilityConfiguration>> AlertsCapabilityAgent:: getCapabilityConfigurations() { return m_capabilityConfigurations; } void AlertsCapabilityAgent::onSpeakerSettingsChanged( const SpeakerManagerObserverInterface::Source& source, const SpeakerInterface::Type& type, const SpeakerInterface::SpeakerSettings& settings) { m_executor.submit([this, settings, type]() { executeOnSpeakerSettingsChanged(type, settings); }); } bool AlertsCapabilityAgent::getAlertVolumeSettings( avsCommon::sdkInterfaces::SpeakerInterface::SpeakerSettings* speakerSettings) { if (!m_speakerManager->getSpeakerSettings(SpeakerInterface::Type::AVS_ALERTS_VOLUME, speakerSettings).get()) { ACSDK_ERROR(LX("getAlertSpeakerSettingsFailed").d("reason", "Failed to get speaker settings")); return false; } return true; } bool AlertsCapabilityAgent::getSpeakerVolumeSettings( avsCommon::sdkInterfaces::SpeakerInterface::SpeakerSettings* speakerSettings) { if (!m_speakerManager->getSpeakerSettings(SpeakerInterface::Type::AVS_SPEAKER_VOLUME, speakerSettings).get()) { ACSDK_ERROR(LX("getContentSpeakerSettingsFailed").d("reason", "Failed to get speaker settings")); return false; } return true; } void AlertsCapabilityAgent::setNextAlertVolume(int64_t volume) { if (volume < speakerConstants::AVS_SET_VOLUME_MIN) { volume = speakerConstants::AVS_SET_VOLUME_MIN; ACSDK_DEBUG7(LX(__func__).m("Requested volume is lower than allowed minimum, using minimum instead.")); } else if (volume > speakerConstants::AVS_SET_VOLUME_MAX) { volume = speakerConstants::AVS_SET_VOLUME_MAX; ACSDK_DEBUG7(LX(__func__).m("Requested volume is higher than allowed maximum, using maximum instead.")); } ACSDK_DEBUG5(LX(__func__).d("New Alerts volume", volume)); // Check if there are alerts currently active and change actual volume only if there is none if (!m_alertIsSounding) { m_speakerManager ->setVolume( avsCommon::sdkInterfaces::SpeakerInterface::Type::AVS_ALERTS_VOLUME, static_cast<int8_t>(volume)) .get(); } // Always notify AVS of volume changes here updateAVSWithLocalVolumeChanges(static_cast<int8_t>(volume), true); } void AlertsCapabilityAgent::executeOnSpeakerSettingsChanged( const SpeakerInterface::Type& type, const SpeakerInterface::SpeakerSettings& speakerSettings) { if (SpeakerInterface::Type::AVS_ALERTS_VOLUME == type && !m_alertIsSounding) { updateAVSWithLocalVolumeChanges(speakerSettings.volume, false); } } } // namespace alerts } // namespace capabilityAgents } // namespace alexaClientSDK
40.583851
120
0.731277
[ "vector" ]
f669c271a8c947b545b78faad48f05467210b763
63,343
cpp
C++
UnrealEngine-4.11.2-release/Engine/Source/Developer/SimplygonSwarm/Private/SimplygonSwarm.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2016-10-01T21:35:52.000Z
2016-10-01T21:35:52.000Z
UnrealEngine-4.11.2-release/Engine/Source/Developer/SimplygonSwarm/Private/SimplygonSwarm.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
null
null
null
UnrealEngine-4.11.2-release/Engine/Source/Developer/SimplygonSwarm/Private/SimplygonSwarm.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2021-04-27T08:48:33.000Z
2021-04-27T08:48:33.000Z
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "SimplygonSwarmPrivatePCH.h" #include <algorithm> #define LOCTEXT_NAMESPACE "SimplygonSwarm" #include "MeshMergeData.h" // Standard Simplygon channels have some issues with extracting color data back from simplification, // so we use this workaround with user channels static const char* USER_MATERIAL_CHANNEL_METALLIC = "UserMetallic"; static const char* USER_MATERIAL_CHANNEL_ROUGHNESS = "UserRoughness"; static const char* USER_MATERIAL_CHANNEL_SPECULAR = "UserSpecular"; static const TCHAR* BASECOLOR_CHANNEL = TEXT("Basecolor"); static const TCHAR* METALLIC_CHANNEL = TEXT("Metallic"); static const TCHAR* SPECULAR_CHANNEL = TEXT("Specular"); static const TCHAR* ROUGHNESS_CHANNEL = TEXT("Roughness"); static const TCHAR* NORMAL_CHANNEL = TEXT("Normals"); static const TCHAR* OPACITY_CHANNEL = TEXT("Opacity"); static const TCHAR* EMISSIVE_CHANNEL = TEXT("Emissive"); #define SIMPLYGON_COLOR_CHANNEL "VertexColors" #define KEEP_SIMPLYGON_SWARM_TEMPFILES //@third party code BEGIN SIMPLYGON #define USE_USER_OPACITY_CHANNEL 1 #if USE_USER_OPACITY_CHANNEL static const char* USER_MATERIAL_CHANNEL_OPACITY = "UserOpacity"; #endif //@third party code END SIMPLYGON static const TCHAR* SG_UE_INTEGRATION_REV = TEXT("#SG_UE_INTEGRATION_REV"); #ifdef __clang__ // SimplygonSDK.h uses 'deprecated' pragma which Clang does not recognize #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown pragma ignored [-Wunknown-pragmas] #endif #ifdef __clang__ #pragma clang diagnostic pop #endif static const TCHAR* SPL_TEMPLATE_REMESHING = TEXT("{\"Header\":{\"SPLVersion\":\"7.0\",\"ClientName\":\"UE4\",\"ClientVersion\":\"UE4.9\",\"SimplygonVersion\":\"7.0\"},\"ProcessGraph\":{\"Type\":\"ContainerNode\",\"Name\":\"Node\",\"Children\":[{\"Processor\":{\"RemeshingSettings\":{\"CuttingPlaneSelectionSetName\":0,\"EmptySpaceOverride\":0.0,\"MaxTriangleSize\":32,\"OnScreenSize\":%d,\"ProcessSelectionSetName\":\"\",\"SurfaceTransferMode\":1,\"TransferColors\":false,\"TransferNormals\":false,\"UseCuttingPlanes\":%s,\"UseEmptySpaceOverride\":false,\"Enabled\":true%s},\"MappingImageSettings\":{\"AutomaticTextureSizeMultiplier\":1.0,\"ChartAggregatorMode\":0,\"ChartAggregatorOriginalTexCoordLevel\":0,\"ChartAggregatorUseAreaWeighting\":true,\"ChartAggregatorKeepOriginalChartProportions\":true,\"ChartAggregatorKeepOriginalChartProportionsFromChannel\":\"\",\"ChartAggregatorKeepOriginalChartSizes\":false,\"ChartAggregatorSeparateOverlappingCharts\":true,\"ForcePower2Texture\":true,\"GenerateMappingImage\":true,\"GenerateTangents\":true,\"GenerateTexCoords\":true,\"GutterSpace\":4,\"Height\":%d,\"MaximumLayers\":3,\"MultisamplingLevel\":3,\"ParameterizerMaxStretch\":6.0,\"ParameterizerUseVertexWeights\":false,\"ParameterizerUseVisibilityWeights\":false,\"TexCoordGeneratorType\":0,\"TexCoordLevel\":255,\"UseAutomaticTextureSize\":false,\"UseFullRetexturing\":false,\"Width\":%d,\"Enabled\":true},%s\"Type\":\"RemeshingProcessor\"},\"MaterialCaster\":[%s],\"DefaultTBNType\":2,\"AllowGPUAcceleration\":false,\"Type\":\"ProcessNode\",\"Name\":\"Node\",\"Children\":[{\"Format\":\"ssf\",\"Type\":\"WriteNode\",\"Name\":\"outputlod_0\",\"Children\":[]}]}]}}"); static const TCHAR* SPL_TEMPLATE_COLORCASTER = TEXT("{\"BakeOpacityInAlpha\":false,\"ColorType\":\"%s\",\"Dilation\":8,\"FillMode\":2,\"IsSRGB\":true,\"OutputChannelBitDepth\":8,\"OutputChannels\":4,\"Type\":\"ColorCaster\",\"Name\":\"%s\",\"Channel\":\"%s\",\"DitherType\":0}"); static const TCHAR* SPL_NORMAL_RECALC = TEXT("\"HardEdgeAngleInRadians\":%f"); static const TCHAR* SPL_MERGE_DIST = TEXT("\"MergeDistance\":%f"); static const TCHAR* CUTTING_PLANE_SETTINGS = TEXT("\"CuttingPlaneSettings\": [%s],"); static const TCHAR* CUTTING_PLANE = TEXT("{\"PointX\": %f,\"PointY\": %f,\"PointZ\": %f,\"NormalX\": %f,\"NormalY\": %f,\"NormalZ\": %f,\"Enabled\": true}"); static const TCHAR* SPL_TEMPLATE_NORMALCASTER = TEXT("{\"Dilation\":8,\"FillMode\":2,\"FlipBackfacingNormals\":false,\"FlipGreen\":false,\"GenerateTangentSpaceNormals\":true,\"NormalMapTextureLevel\":0,\"OutputChannelBitDepth\":8,\"OutputChannels\":3,\"Type\":\"NormalCaster\",\"Name\":\"%s\",\"Channel\":\"%s\",\"DitherType\":0}"); static const TCHAR* SHADING_NETWORK_TEMPLATE = TEXT("<SimplygonShadingNetwork version=\"1.0\">\n\t<ShadingTextureNode ref=\"node_0\" name=\"ShadingTextureNode\">\n\t\t<DefaultColor0>\n\t\t\t<DefaultValue>1 1 1 1</DefaultValue>\n\t\t</DefaultColor0>\n\t\t<TextureName>%s</TextureName>\n\t\t<TexCoordSet>%s</TexCoordSet>\n\t\t<UseSRGB>%d</UseSRGB>\n\t\t<TileU>1.000000</TileU>\n\t\t<TileV>1.000000</TileV>\n\t</ShadingTextureNode>\n</SimplygonShadingNetwork>"); class FSimplygonSwarmModule : public IMeshReductionModule { public: // IModuleInterface interface. virtual void StartupModule() override; virtual void ShutdownModule() override; // IMeshReductionModule interface. virtual class IMeshReduction* GetMeshReductionInterface() override; virtual class IMeshMerging* GetMeshMergingInterface() override; private: }; DEFINE_LOG_CATEGORY_STATIC(LogSimplygonSwarm, Log, All); IMPLEMENT_MODULE(FSimplygonSwarmModule, SimplygonSwarm); struct FSimplygonSSFHelper { public: static ssf::ssfString SSFNewGuid() { return TCHARToSSFString(*FGuid::NewGuid().ToString()); } static ssf::ssfString SFFEmptyGuid() { return TCHARToSSFString(*FGuid::FGuid().ToString()); } static ssf::ssfString TCHARToSSFString(const TCHAR* str) { return ssf::ssfString(std::basic_string<TCHAR>(str)); } static bool CompareSSFStr(ssf::ssfString lhs, ssf::ssfString rhs) { if (lhs.Value == rhs.Value) return true; return false; } static FString SimplygonDirectory() { return FPaths::GameIntermediateDir() + TEXT("Simplygon/"); } }; class FSimplygonSwarm : public IMeshMerging { public: virtual ~FSimplygonSwarm() { } static FSimplygonSwarm* Create() { return new FSimplygonSwarm(); } struct FMaterialCastingProperties { bool bCastMaterials; bool bCastNormals; bool bCastMetallic; bool bCastRoughness; bool bCastSpecular; FMaterialCastingProperties() : bCastMaterials(false) , bCastNormals(false) , bCastMetallic(false) , bCastRoughness(false) , bCastSpecular(false) { } }; void BuildProxy( const TArray<UStaticMeshComponent*> InputStaticMeshComponents, const struct FMeshProxySettings& InProxySettings, FRawMesh& OutProxyMesh, FFlattenMaterial& OutMaterial, FBox& OutProxyBox) { } virtual void ProxyLOD(const TArray<FMeshMergeData>& InData, const struct FMeshProxySettings& InProxySettings, const TArray<struct FFlattenMaterial>& InputMaterials, const FGuid InJobGUID) { FRawMesh OutProxyMesh; FFlattenMaterial OutMaterial; //setup path variables FString JobPath = FGuid::NewGuid().ToString(); FString JobDirectory = FString::Printf(TEXT("%s%s"), *FSimplygonSSFHelper::SimplygonDirectory(), *JobPath); FString InputFolderPath = FString::Printf(TEXT("%s/Input"), *JobDirectory); FString ZipFileName = FString::Printf(TEXT("%s/%s.zip"), *JobDirectory, *JobPath); FString OutputZipFileName = FString::Printf(TEXT("%s/%s_output.zip"), *JobDirectory, *JobPath); FString SPLFileOutputFullPath = FString::Printf(TEXT("%s/input.spl"), *InputFolderPath); FString RemeshingSPLText; //Create an spl template CreateRemeshingSPL(InProxySettings, RemeshingSPLText); //output spl to file. Since REST Interface SaveSPL(RemeshingSPLText, SPLFileOutputFullPath); ssf::pssfScene SsfScene; TArray<FRawMesh> InputMeshes; for (auto Data : InData) { InputMeshes.Push(Data.RawMesh); } //converts UE entities to ssf, Textures will be exported to file ConvertToSsfScene(InData, InputMaterials, InProxySettings, InputFolderPath, SsfScene); FString SsfOuputPath = FString::Printf(TEXT("%s/input.ssf"), *InputFolderPath); //save out ssf file. WriteSsfFile(SsfScene, SsfOuputPath); //zip contents and spawn a task if (ZipContentsForUpload(InputFolderPath, ZipFileName)) { //NOTE : Currently SgRESTInterface is not cleaned up and Task ref counted . The FSimplygonSwarmTask & FSimplygonRESTClient pari can be stored in a TArray or TMap to make aync calls // The pair can be cleanup after the import process SwarmTask = MakeShareable(new FSimplygonSwarmTask(ZipFileName, SPLFileOutputFullPath, OutputZipFileName, JobDirectory, &InStateLock, InJobGUID, CompleteDelegate)); SwarmTask->OnAssetDownloaded().BindRaw(this, &FSimplygonSwarm::ImportFile); SwarmTask->OnAssetUploaded().BindRaw(this, &FSimplygonSwarm::Cleanup); SgRESTInterface = new FSimplygonRESTClient(SwarmTask); SgRESTInterface->StartJobAsync(); } } //@third party code BEGIN SIMPLYGON //virtual void ProxyLOD( // const TArray<FMeshMaterialReductionData*>& InData, // const struct FSimplygonRemeshingSettings& InProxySettings, // FRawMesh& OutProxyMesh, // FFlattenMaterial& OutMaterial) //{ // //TODO : Implment only if Epic are not using Build Proxy //} // IMeshMerging interface virtual void BuildProxy( const TArray<FRawMesh>& InputMeshes, const TArray<FFlattenMaterial>& InputMaterials, const struct FMeshProxySettings& InProxySettings, FRawMesh& OutProxyMesh, FFlattenMaterial& OutMaterial) { //setup path variables FString JobPath = FGuid::NewGuid().ToString(); FString JobDirectory = FString::Printf(TEXT("%s%s"), *FSimplygonSSFHelper::SimplygonDirectory(), *JobPath); FString InputFolderPath = FString::Printf(TEXT("%s/Input"), *JobDirectory); FString ZipFileName = FString::Printf(TEXT("%s/%s.zip"), *JobDirectory,*JobPath); FString OutputZipFileName = FString::Printf(TEXT("%s/%s_output.zip"), *JobDirectory, *JobPath); FString SPLFileOutputFullPath = FString::Printf(TEXT("%s/input.spl"), *InputFolderPath); FString RemeshingSPLText; //Create an spl template CreateRemeshingSPL(InProxySettings, RemeshingSPLText); //output spl to file. Since REST Interface SaveSPL(RemeshingSPLText, SPLFileOutputFullPath); ssf::pssfScene SsfScene; //converts UE entities to ssf, Textures will be exported to file ConvertToSsfScene(InputMeshes, InputMaterials, InProxySettings, InputFolderPath, SsfScene); FString SsfOuputPath = FString::Printf(TEXT("%s/input.ssf"), *InputFolderPath); //save out ssf file. WriteSsfFile(SsfScene, SsfOuputPath); //zip contents and spawn a task if (ZipContentsForUpload(InputFolderPath, ZipFileName)) { //NOTE : Currently SgRESTInterface is not cleaned up and Task ref counted . The FSimplygonSwarmTask & FSimplygonRESTClient pari can be stored in a TArray or TMap to make aync calls // The pair can be cleanup after the import process SwarmTask = MakeShareable(new FSimplygonSwarmTask(ZipFileName, SPLFileOutputFullPath, OutputZipFileName, JobDirectory, &InStateLock, FGuid::NewGuid(), CompleteDelegate)); SwarmTask->OnAssetDownloaded().BindRaw(this, &FSimplygonSwarm::ImportFile); SwarmTask->OnAssetUploaded().BindRaw(this, &FSimplygonSwarm::Cleanup); SgRESTInterface = new FSimplygonRESTClient(SwarmTask); SgRESTInterface->StartJobAsync(); } } /* The Following method will cleanup temp files and folders created to upload the job to the simplygon job manager */ void Cleanup(const FSimplygonSwarmTask& InSwarmTask) { #ifndef KEEP_SIMPLYGON_SWARM_TEMPFILES FString InputFolderPath = FString::Printf(TEXT("%s/Input"), *InSwarmTask.JobDirectory); //remove folder folder if (FPaths::DirectoryExists(InputFolderPath)) { if (!IFileManager::Get().DeleteDirectory(*InputFolderPath, true, true)) { UE_LOG(LogSimplygonSwarm, Log, TEXT("Failed to remove simplygon swarm task temp directory %s"), *InputFolderPath); } } //remove uploaded zip file if (FPaths::FileExists(InSwarmTask.ZipFilePath)) { if (!IFileManager::Get().Delete(*InSwarmTask.ZipFilePath)) { UE_LOG(LogSimplygonSwarm, Log, TEXT("Failed to remove Simplygon Swarm Task temp file %s"), *InSwarmTask.ZipFilePath); } } #endif } /* This mehtod would be fired when the job has been download on the machine. A good plane to hook contents to the LODActor. Note this would need to run on the Main Thread */ void ImportFile(const FSimplygonSwarmTask& InSwarmTask) { FRawMesh OutProxyMesh; FFlattenMaterial OutMaterial; FString OutputFolderPath = FString::Printf(TEXT("%s/Output"), *InSwarmTask.JobDirectory); FString ParentDirForOutputSsf = FString::Printf(TEXT("%s/Node/Node/outputlod_0"), *OutputFolderPath); //for import the file back in uncomment if (UnzipDownloadedContent(InSwarmTask.OutputFilename, OutputFolderPath)) { //FString InOuputSsfPath = FString::Printf(TEXT("%s/Node/Node/outputlod_0/output.ssf"), *OutputFolderPath); FString InOuputSsfPath = FString::Printf(TEXT("%s/output.ssf"), *ParentDirForOutputSsf); ssf::pssfScene OutSsfScene = new ssf::ssfScene(); FString SsfFullPath = FPaths::ConvertRelativePathToFull(InOuputSsfPath); if (!FPaths::FileExists(SsfFullPath)) { UE_LOG(LogSimplygonSwarm, Log, TEXT("Ssf file not found %s"), *SsfFullPath); return; } ReadSsfFile(SsfFullPath, OutSsfScene); ConvertFromSsfScene(OutSsfScene, OutProxyMesh, OutMaterial, ParentDirForOutputSsf); if (!OutProxyMesh.IsValid()) UE_LOG(LogSimplygonSwarm, Log, TEXT("RawMesh is invalid.")); CompleteDelegate.ExecuteIfBound(OutProxyMesh, OutMaterial, InSwarmTask.TestJobID); //do cleanup work #ifndef KEEP_SIMPLYGON_SWARM_TEMPFILES if (FPaths::DirectoryExists(OutputFolderPath)) { if (!IFileManager::Get().DeleteDirectory(*OutputFolderPath, true, true)) { UE_LOG(LogSimplygonSwarm, Log, TEXT("Failed to remove simplygon swarm task temp directory %s"), *OutputFolderPath); } } //remove uploaded zip file if (FPaths::FileExists(InSwarmTask.OutputFilename)) { if (!IFileManager::Get().Delete(*InSwarmTask.OutputFilename)) { UE_LOG(LogSimplygonSwarm, Log, TEXT("Failed to remove Simplygon Swarm Task temp file %s"), *InSwarmTask.OutputFilename); } } #endif } } private: FString VersionString; FSimplygonRESTClient* SgRESTInterface; FCriticalSection InStateLock; //FRunnableThread *Thread; TSharedPtr<class FSimplygonSwarmTask> SwarmTask; uint8 ToolMajorVersion; uint8 ToolMinorVersion; uint16 ToolBuildVersion; explicit FSimplygonSwarm() { VersionString = FString::Printf(TEXT("%s"), SG_UE_INTEGRATION_REV); ToolMajorVersion = FEngineVersion::Current().GetMajor(); ToolMinorVersion = FEngineVersion::Current().GetMinor(); ToolBuildVersion = FEngineVersion::Current().GetPatch(); } void ReadSsfFile(FString InSsfFilePath, ssf::pssfScene& SsfScene) { ssf::ssfString ToolName = FSimplygonSSFHelper::TCHARToSSFString(TEXT("UE4")); ssf::ssfBinaryInputStream InputStream; InputStream.OpenFile(FSimplygonSSFHelper::TCHARToSSFString(*InSsfFilePath)); SsfScene->ReadFile(&InputStream, ToolName, ToolMajorVersion, ToolMinorVersion, ToolBuildVersion); } void WriteSsfFile(ssf::pssfScene SsfScene, FString InSsfFilePath) { ssf::ssfString ToolName = FSimplygonSSFHelper::TCHARToSSFString(TEXT("UE4")); ssf::ssfBinaryOutputStream theOutputStream; theOutputStream.OpenFile(FSimplygonSSFHelper::TCHARToSSFString(*InSsfFilePath)); SsfScene->WriteFile(&theOutputStream, ToolName, ToolMajorVersion, ToolMinorVersion, ToolBuildVersion); theOutputStream.CloseFile(); } void CreateRemeshingSPL(const struct FMeshProxySettings& InProxySettings, FString& OutSplText) { ////Compute max mapping image size FIntPoint ImageSizes = ComputeMappingImageSize(InProxySettings.MaterialSettings); ////setup casters FString CasterSPLTempalte = CreateSPLTemplateChannels(InProxySettings.MaterialSettings); FString MergeDist = FString::Printf(SPL_MERGE_DIST, InProxySettings.MergeDistance); FString AdditionalSettings = FString::Printf(TEXT(",%s"), *MergeDist); FString RecalNormals = FString::Printf(SPL_NORMAL_RECALC, FMath::DegreesToRadians(InProxySettings.HardAngleThreshold)); if (InProxySettings.bRecalculateNormals) AdditionalSettings = FString::Printf(TEXT("%s,%s"), *AdditionalSettings, *RecalNormals); //Note : The Simplygon API now supports multiple clipping planes. SPL has recently added support for this. // FString CuttingPlaneSetting; if (InProxySettings.bUseClippingPlane) { // Note : An arbitary plane can be define using a point (position) and a normal (direction) // Since UE currently only has axis aligned plane. We need to convert values for SPL FVector OutPoint, OutNormal; GetAxisAlignedVectorsForCuttingPlanes(InProxySettings, OutPoint, OutNormal); FString CuttingPlane = FString::Printf(CUTTING_PLANE, OutPoint.X, OutPoint.Y, OutPoint.Z, OutNormal.X, OutNormal.Y, OutNormal.Z); CuttingPlaneSetting = FString::Printf(CUTTING_PLANE_SETTINGS, *CuttingPlane); } OutSplText = FString::Printf(SPL_TEMPLATE_REMESHING, InProxySettings.ScreenSize, InProxySettings.bUseClippingPlane ? TEXT("true") :TEXT("false"), *AdditionalSettings, ImageSizes.X, ImageSizes.Y, *CuttingPlaneSetting, *CasterSPLTempalte); } void GetAxisAlignedVectorsForCuttingPlanes(const struct FMeshProxySettings& InProxySettings, FVector& OutPoint, FVector& OutNormal) { // 0 -> X , 1 -> Y, 2 -> Z if (InProxySettings.AxisIndex == 0) { OutNormal.X = InProxySettings.bPlaneNegativeHalfspace ? -1 : 1 ; OutPoint.X = InProxySettings.ClippingLevel; } else if (InProxySettings.AxisIndex == 1) { OutNormal.Y = InProxySettings.bPlaneNegativeHalfspace ? -1 : 1; OutPoint.Y = InProxySettings.ClippingLevel; } else { OutNormal.Z = InProxySettings.bPlaneNegativeHalfspace ? -1 : 1; OutPoint.Z = InProxySettings.ClippingLevel; //default to z up } } /* Write the SPL string to file */ void SaveSPL(FString InSplText, FString InOutputFilePath) { FArchive* SPLFile = IFileManager::Get().CreateFileWriter(*InOutputFilePath); SPLFile->Logf(*InSplText); SPLFile->Close(); } void ConvertToSsfScene(const TArray<FMeshMergeData>& InputData, const TArray<FFlattenMaterial>& InputMaterials, const struct FMeshProxySettings& InProxySettings, FString InputFolderPath, ssf::pssfScene& OutSsfScene) { //creeate the ssf scene OutSsfScene = new ssf::ssfScene(); OutSsfScene->CoordinateSystem.Set(1); OutSsfScene->WorldOrientation.Set(2); OutSsfScene->TextureTable->TexturesDirectory.Set(FSimplygonSSFHelper::TCHARToSSFString(TEXT("/Textures"))); TMap<int, FString> MaterialMap; CreateSSFMaterialFromFlattenMaterial(InputMaterials, InProxySettings.MaterialSettings, OutSsfScene->MaterialTable, OutSsfScene->TextureTable, InputFolderPath, true, MaterialMap); //create the root node ssf::pssfNode SsfRootNode = new ssf::ssfNode(); SsfRootNode->Id.Set(FSimplygonSSFHelper::SSFNewGuid()); SsfRootNode->ParentId.Set(FSimplygonSSFHelper::SFFEmptyGuid()); //add root node to scene OutSsfScene->NodeTable->NodeList.push_back(SsfRootNode); int32 Count = 0; for (FMeshMergeData MergeData : InputData) { //create a the node that will contain the mesh ssf::pssfNode SsfNode = new ssf::ssfNode(); SsfNode->Id.Set(FSimplygonSSFHelper::SSFNewGuid()); SsfNode->ParentId.Set(SsfRootNode->Id.Get()); FString NodeName = FString::Printf(TEXT("Node%i"), Count); SsfNode->Name.Set(FSimplygonSSFHelper::TCHARToSSFString(*NodeName)); //create the mesh object ssf::pssfMesh SsfMesh = new ssf::ssfMesh(); SsfMesh->Id.Set(FSimplygonSSFHelper::SSFNewGuid()); FString MeshName = FString::Printf(TEXT("Mesh%i"), Count); SsfMesh->Name.Set(FSimplygonSSFHelper::TCHARToSSFString(*MeshName)); Count++; //setup mesh data ssf::pssfMeshData SsfMeshData = CreateSSFMeshDataFromRawMesh(MergeData.RawMesh, MergeData.TexCoordBounds, MergeData.NewUVs); SsfMesh->MeshDataList.push_back(SsfMeshData); //setup mesh material information SsfMesh->MaterialIds.Create(); TArray<int32> UniqueMaterialIds; UniqueMaterialIds.Reserve(InputMaterials.Num()); //get unqiue material ids GetUniqueMaterialIndices(MergeData.RawMesh.FaceMaterialIndices, UniqueMaterialIds); SsfMesh->MaterialIds->Items.reserve(UniqueMaterialIds.Num()); TMap<int, int> GlobalToLocal; //map ssfmesh local materials for (int32 GlobalMaterialId : UniqueMaterialIds) { SsfMesh->MaterialIds->Items.push_back(FSimplygonSSFHelper::TCHARToSSFString(*MaterialMap[GlobalMaterialId])); int32 localIndex = SsfMesh->MaterialIds->Items.size() - 1; //replace GlobalToLocal.Add(GlobalMaterialId, localIndex); } for (ssf::pssfMeshData MeshData : SsfMesh->MeshDataList) { for (int Index = 0; Index < MeshData->MaterialIndices.Get().Items.size(); Index++) { MeshData->MaterialIndices.Get().Items[Index] = GlobalToLocal[MeshData->MaterialIndices.Get().Items[Index]]; } } //link mesh to node SsfNode->MeshId.Set(SsfMesh->Id.Get().Value); //add mesh and node to their respective tables OutSsfScene->NodeTable->NodeList.push_back(SsfNode); OutSsfScene->MeshTable->MeshList.push_back(SsfMesh); } } void ConvertToSsfScene(const TArray<FRawMesh>& InputMeshes, const TArray<FFlattenMaterial>& InputMaterials, const struct FMeshProxySettings& InProxySettings, FString InputFolderPath, ssf::pssfScene& OutSsfScene) { //creeate the ssf scene OutSsfScene = new ssf::ssfScene(); OutSsfScene->CoordinateSystem.Set(1); OutSsfScene->WorldOrientation.Set(2); OutSsfScene->TextureTable->TexturesDirectory.Set(FSimplygonSSFHelper::TCHARToSSFString(TEXT("/Textures"))); TMap<int, FString> MaterialMap; CreateSSFMaterialFromFlattenMaterial(InputMaterials, InProxySettings.MaterialSettings, OutSsfScene->MaterialTable, OutSsfScene->TextureTable, InputFolderPath, true, MaterialMap); //create the root node ssf::pssfNode SsfRootNode = new ssf::ssfNode(); SsfRootNode->Id.Set(FSimplygonSSFHelper::SSFNewGuid()); SsfRootNode->ParentId.Set(FSimplygonSSFHelper::SFFEmptyGuid()); //add root node to scene OutSsfScene->NodeTable->NodeList.push_back(SsfRootNode); for (FRawMesh RawMesh : InputMeshes) { //create a the node that will contain the mesh ssf::pssfNode SsfNode = new ssf::ssfNode(); SsfNode->Id.Set(FSimplygonSSFHelper::SSFNewGuid()); SsfNode->ParentId.Set(SsfRootNode->Id.Get()); SsfNode->Name.Set(FSimplygonSSFHelper::TCHARToSSFString(TEXT("Node"))); //create the mesh object ssf::pssfMesh SsfMesh = new ssf::ssfMesh(); SsfMesh->Id.Set(FSimplygonSSFHelper::SSFNewGuid()); SsfMesh->Name.Set(FSimplygonSSFHelper::TCHARToSSFString(TEXT("Mesh"))); //setup mesh data ssf::pssfMeshData SsfMeshData = CreateSSFMeshDataFromRawMesh(RawMesh); SsfMesh->MeshDataList.push_back(SsfMeshData); //setup mesh material information SsfMesh->MaterialIds.Create(); TArray<int32> UniqueMaterialIds; UniqueMaterialIds.Reserve(InputMaterials.Num()); //get unqiue material ids GetUniqueMaterialIndices(RawMesh.FaceMaterialIndices, UniqueMaterialIds); SsfMesh->MaterialIds->Items.reserve(UniqueMaterialIds.Num()); TMap<int, int> GlobalToLocal; //map ssfmesh local materials for (int32 GlobalMaterialId : UniqueMaterialIds) { SsfMesh->MaterialIds->Items.push_back(FSimplygonSSFHelper::TCHARToSSFString(*MaterialMap[GlobalMaterialId])); int32 localIndex = SsfMesh->MaterialIds->Items.size() - 1; //replace GlobalToLocal.Add(GlobalMaterialId, localIndex); } for (ssf::pssfMeshData MeshData : SsfMesh->MeshDataList) { for (int Index = 0; Index < MeshData->MaterialIndices.Get().Items.size(); Index++) { MeshData->MaterialIndices.Get().Items[Index] = GlobalToLocal[MeshData->MaterialIndices.Get().Items[Index]]; } } //link mesh to node SsfNode->MeshId.Set(SsfMesh->Id.Get().Value); //add mesh and node to their respective tables OutSsfScene->NodeTable->NodeList.push_back(SsfNode); OutSsfScene->MeshTable->MeshList.push_back(SsfMesh); } } void ConvertFromSsfScene(ssf::pssfScene SceneGraph, FRawMesh& OutProxyMesh, FFlattenMaterial& OutMaterial, const FString OutputFolderPath) { for (ssf::pssfMesh Mesh : SceneGraph->MeshTable->MeshList) { //extract geometry data for (ssf::pssfMeshData MeshData : Mesh->MeshDataList) { int32 TotalVertices = MeshData->GetVerticesCount(); int32 ToatalCorners = MeshData->GetCornersCount(); int32 TotalTriangles = MeshData->GetTrianglesCount(); OutProxyMesh.VertexPositions.SetNumUninitialized(TotalVertices); int VertexIndex = 0; for (ssf::ssfVector3 VertexCoord : MeshData->Coordinates.Get().Items) { OutProxyMesh.VertexPositions[VertexIndex] = GetConversionMatrix().TransformPosition(FVector(VertexCoord.V[0], VertexCoord.V[1], VertexCoord.V[2])); VertexIndex++; } OutProxyMesh.WedgeIndices.SetNumUninitialized(ToatalCorners); for (int32 TriIndex = 0; TriIndex < TotalTriangles; ++TriIndex) { OutProxyMesh.WedgeIndices[TriIndex * 3 + 0] = MeshData->TriangleIndices.Get().Items[TriIndex].V[0]; OutProxyMesh.WedgeIndices[TriIndex * 3 + 1] = MeshData->TriangleIndices.Get().Items[TriIndex].V[1]; OutProxyMesh.WedgeIndices[TriIndex * 3 + 2] = MeshData->TriangleIndices.Get().Items[TriIndex].V[2]; } int32 TexCoordIndex = 0; for (ssf::ssfNamedList<ssf::ssfVector2> TexCoorChannel : MeshData->TextureCoordinatesList) { OutProxyMesh.WedgeTexCoords[TexCoordIndex].SetNumUninitialized(ToatalCorners); for (int32 CornerIndex = 0; CornerIndex < ToatalCorners; ++CornerIndex) { OutProxyMesh.WedgeTexCoords[TexCoordIndex][CornerIndex].X = TexCoorChannel.Items[CornerIndex].V[0]; OutProxyMesh.WedgeTexCoords[TexCoordIndex][CornerIndex].Y = TexCoorChannel.Items[CornerIndex].V[1]; } TexCoordIndex++; } //SSF Can store multiple color channels. However UE only supports one color channel int32 ColorChannelIndex = 0; for (ssf::ssfNamedList<ssf::ssfVector4> TexCoorChannel : MeshData->ColorsList) { OutProxyMesh.WedgeColors.SetNumUninitialized(ToatalCorners); for (int32 CornerIndex = 0; CornerIndex < ToatalCorners; ++CornerIndex) { OutProxyMesh.WedgeColors[CornerIndex].R = TexCoorChannel.Items[CornerIndex].V[0]; OutProxyMesh.WedgeColors[CornerIndex].G = TexCoorChannel.Items[CornerIndex].V[1]; OutProxyMesh.WedgeColors[CornerIndex].B = TexCoorChannel.Items[CornerIndex].V[2]; OutProxyMesh.WedgeColors[CornerIndex].A = TexCoorChannel.Items[CornerIndex].V[3]; } } bool Normals = !MeshData->Normals.IsEmpty() && MeshData->Normals.Get().Items.size() > 0; bool Tangents = !MeshData->Tangents.IsEmpty() && MeshData->Tangents.Get().Items.size() > 0; bool Bitangents = !MeshData->Bitangents.IsEmpty() && MeshData->Bitangents.Get().Items.size() > 0; bool MaterialIndices = !MeshData->MaterialIndices.IsEmpty() && MeshData->MaterialIndices.Get().Items.size() > 0; bool GroupIds = !MeshData->SmoothingGroup.IsEmpty() && MeshData->SmoothingGroup.Get().Items.size() > 0; if (Normals) { if (Tangents && Bitangents) { OutProxyMesh.WedgeTangentX.SetNumUninitialized(ToatalCorners); for (int32 WedgeIndex = 0; WedgeIndex < ToatalCorners; ++WedgeIndex) { OutProxyMesh.WedgeTangentX[WedgeIndex].X = MeshData->Tangents.Get().Items[WedgeIndex].V[0]; OutProxyMesh.WedgeTangentX[WedgeIndex].Y = MeshData->Tangents.Get().Items[WedgeIndex].V[1]; OutProxyMesh.WedgeTangentX[WedgeIndex].Z = MeshData->Tangents.Get().Items[WedgeIndex].V[2]; OutProxyMesh.WedgeTangentX[WedgeIndex] = GetConversionMatrix().TransformVector(OutProxyMesh.WedgeTangentX[WedgeIndex]); } OutProxyMesh.WedgeTangentY.SetNumUninitialized(ToatalCorners); for (int32 WedgeIndex = 0; WedgeIndex < ToatalCorners; ++WedgeIndex) { OutProxyMesh.WedgeTangentY[WedgeIndex].X = MeshData->Bitangents.Get().Items[WedgeIndex].V[0]; OutProxyMesh.WedgeTangentY[WedgeIndex].Y = MeshData->Bitangents.Get().Items[WedgeIndex].V[1]; OutProxyMesh.WedgeTangentY[WedgeIndex].Z = MeshData->Bitangents.Get().Items[WedgeIndex].V[2]; OutProxyMesh.WedgeTangentY[WedgeIndex] = GetConversionMatrix().TransformVector(OutProxyMesh.WedgeTangentY[WedgeIndex]); } } OutProxyMesh.WedgeTangentZ.SetNumUninitialized(ToatalCorners); for (int32 WedgeIndex = 0; WedgeIndex < ToatalCorners; ++WedgeIndex) { //Normals->GetTuple(WedgeIndex, (float*)&OutProxyMesh.WedgeTangentZ[WedgeIndex]); OutProxyMesh.WedgeTangentZ[WedgeIndex].X = MeshData->Normals.Get().Items[WedgeIndex].V[0]; OutProxyMesh.WedgeTangentZ[WedgeIndex].Y = MeshData->Normals.Get().Items[WedgeIndex].V[1]; OutProxyMesh.WedgeTangentZ[WedgeIndex].Z = MeshData->Normals.Get().Items[WedgeIndex].V[2]; OutProxyMesh.WedgeTangentZ[WedgeIndex] = GetConversionMatrix().TransformVector(OutProxyMesh.WedgeTangentZ[WedgeIndex]); } } OutProxyMesh.FaceMaterialIndices.SetNumUninitialized(TotalTriangles); if (MaterialIndices) { for (int32 TriIndex = 0; TriIndex < TotalTriangles; ++TriIndex) { OutProxyMesh.FaceMaterialIndices[TriIndex] = MeshData->MaterialIndices.Get().Items[TriIndex].Value; } } OutProxyMesh.FaceSmoothingMasks.SetNumUninitialized(TotalTriangles); if (GroupIds) { for (int32 TriIndex = 0; TriIndex < TotalTriangles; ++TriIndex) { OutProxyMesh.FaceSmoothingMasks[TriIndex] = MeshData->SmoothingGroup.Get().Items[TriIndex].Value; } } } //since its a proxy will only contain one material on it ssf::ssfString ProxyMaterialGuid = Mesh->MaterialIds.Get().Items[0].Value; ssf::pssfMaterial ProxyMaterial = FindMaterialById(SceneGraph, ProxyMaterialGuid); if (ProxyMaterial != nullptr) { SetupMaterail(SceneGraph, ProxyMaterial, OutMaterial, OutputFolderPath); } } } void ExtractTextureDescriptors(ssf::pssfScene SceneGraph, ssf::pssfMaterialChannel Channel, FString OutputFolderPath, FString ChannelName, TArray<FColor>& OutSamples, FIntPoint& OutTextureSize) { for (ssf::pssfMaterialChannelTextureDescriptor TextureDescriptor : Channel->MaterialChannelTextureDescriptorList) { //SceneGraph->TextureTable->TextureList. ssf::pssfTexture Texture = FindTextureById(SceneGraph, TextureDescriptor->TextureID.Get().Value); if (Texture != nullptr) { FString TextureFilePath = FString::Printf(TEXT("%s/%s"), *OutputFolderPath, ANSI_TO_TCHAR(Texture->Path.Get().Value.c_str())); CopyTextureData(OutSamples, OutTextureSize, ChannelName, TextureFilePath); } } } void SetupMaterail(ssf::pssfScene SceneGraph, ssf::pssfMaterial Material, FFlattenMaterial &OutMaterial, FString OutputFolderPath) { for (ssf::pssfMaterialChannel Channel : Material->MaterialChannelList) { const FString ChannelName(ANSI_TO_TCHAR(Channel->ChannelName.Get().Value.c_str())); if (ChannelName.Compare(BASECOLOR_CHANNEL) == 0) { ExtractTextureDescriptors(SceneGraph, Channel, OutputFolderPath, ChannelName, OutMaterial.DiffuseSamples, OutMaterial.DiffuseSize); } else if (ChannelName.Compare(NORMAL_CHANNEL) == 0) { ExtractTextureDescriptors(SceneGraph, Channel, OutputFolderPath, ChannelName, OutMaterial.NormalSamples, OutMaterial.NormalSize); } else if (ChannelName.Compare(SPECULAR_CHANNEL) == 0) { ExtractTextureDescriptors(SceneGraph, Channel, OutputFolderPath, ChannelName, OutMaterial.SpecularSamples, OutMaterial.SpecularSize); } else if (ChannelName.Compare(ROUGHNESS_CHANNEL) == 0) { ExtractTextureDescriptors(SceneGraph, Channel, OutputFolderPath, ChannelName, OutMaterial.RoughnessSamples, OutMaterial.RoughnessSize); } else if (ChannelName.Compare(METALLIC_CHANNEL) == 0) { ExtractTextureDescriptors(SceneGraph, Channel, OutputFolderPath, ChannelName, OutMaterial.MetallicSamples, OutMaterial.MetallicSize); } else if (ChannelName.Compare(OPACITY_CHANNEL) == 0) { ExtractTextureDescriptors(SceneGraph, Channel, OutputFolderPath, ChannelName, OutMaterial.OpacitySamples, OutMaterial.OpacitySize); } } } ssf::pssfTexture FindTextureById(ssf::pssfScene SceneGraph, ssf::ssfString TextureId) { auto Texture = std::find_if(SceneGraph->TextureTable->TextureList.begin(), SceneGraph->TextureTable->TextureList.end(), [TextureId](const ssf::pssfTexture tex) { if (FSimplygonSSFHelper::CompareSSFStr(tex->Id.Get().Value, TextureId)) { return true; } return false; }); if (Texture != std::end(SceneGraph->TextureTable->TextureList)) { if (!Texture->IsNull()) { return *Texture; } } return nullptr; } ssf::pssfMaterial FindMaterialById(ssf::pssfScene SceneGraph, ssf::ssfString MaterailId) { auto ProxyMaterial = std::find_if(SceneGraph->MaterialTable->MaterialList.begin(), SceneGraph->MaterialTable->MaterialList.end(), [MaterailId](const ssf::pssfMaterial mat) { if (FSimplygonSSFHelper::CompareSSFStr(mat->Id.Get().Value, MaterailId)) { return true; } return false; }); if (ProxyMaterial != std::end(SceneGraph->MaterialTable->MaterialList)) { if (!ProxyMaterial->IsNull()) { return *ProxyMaterial; } } return nullptr; } bool UnzipDownloadedContent(FString ZipFileName, FString OutputFolderPath) { if (!FPaths::FileExists(FPaths::ConvertRelativePathToFull(ZipFileName))) return false; FString CommandLine = FString::Printf(TEXT("x %s -o%s * -y"), *FPaths::ConvertRelativePathToFull(ZipFileName), *FPaths::ConvertRelativePathToFull(OutputFolderPath)); FString CmdExe = TEXT("cmd.exe"); FString ZipToolPath = FPaths::ConvertRelativePathToFull(FPaths::EngineDir() / TEXT("Binaries/ThirdParty/NotForLicensees/7-Zip/7z.exe")); if (!FPaths::FileExists(ZipToolPath)) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("File"), FText::FromString(ZipToolPath)); FMessageDialog::Open(EAppMsgType::Ok, FText::Format(LOCTEXT("RequiredFileNotFoundMessage", "A required file could not be found:\n{File}"), Arguments)); return false; } FString FullCommandLine = FString::Printf(TEXT("/c \"\"%s\" %s\""), *ZipToolPath, *CommandLine); TSharedPtr<FMonitoredProcess> UatProcess = MakeShareable(new FMonitoredProcess(CmdExe, FullCommandLine, true)); UatProcess->Launch(); //ugly spin lock while (UatProcess->IsRunning()) { FPlatformProcess::Sleep(0.01f); } return true; } bool ZipContentsForUpload(FString InputDirectoryPath, FString OutputFileName) { FString CommandLine = FString::Printf(TEXT("a %s %s/*"), *FPaths::ConvertRelativePathToFull(OutputFileName), *FPaths::ConvertRelativePathToFull(InputDirectoryPath)); FString CmdExe = TEXT("cmd.exe"); FString ZipToolPath = FPaths::ConvertRelativePathToFull(FPaths::EngineDir() / TEXT("Binaries/ThirdParty/NotForLicensees/7-Zip/7z.exe")); if (!FPaths::FileExists(ZipToolPath)) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("File"), FText::FromString(ZipToolPath)); FMessageDialog::Open(EAppMsgType::Ok, FText::Format(LOCTEXT("RequiredFileNotFoundMessage", "A required file could not be found:\n{File}"), Arguments)); return false; } FString FullCommandLine = FString::Printf(TEXT("/c \"\"%s\" %s\""), *ZipToolPath, *CommandLine); TSharedPtr<FMonitoredProcess> UatProcess = MakeShareable(new FMonitoredProcess(CmdExe, FullCommandLine, true)); UatProcess->Launch(); //ugly spin lock while (UatProcess->IsRunning()) { FPlatformProcess::Sleep(0.01f); } return true; } void GetUniqueMaterialIndices(const TArray<int32>& OriginalMaterialIds, TArray<int32>& UniqueMaterialIds) { for (int32 index : OriginalMaterialIds) { UniqueMaterialIds.AddUnique(index); } } struct FSkeletalMeshData { TArray<FVertInfluence> Influences; TArray<FMeshWedge> Wedges; TArray<FMeshFace> Faces; TArray<FVector> Points; uint32 TexCoordCount; }; FString CreateSPLTemplateChannels(const FMaterialProxySettings& Settings) { FString FinalTemplate; FinalTemplate += FString::Printf(TEXT("%s"), *FString::Printf(SPL_TEMPLATE_COLORCASTER, BASECOLOR_CHANNEL, BASECOLOR_CHANNEL, BASECOLOR_CHANNEL)); if (Settings.bMetallicMap) { FinalTemplate += FString::Printf(TEXT(",%s"), *FString::Printf(SPL_TEMPLATE_COLORCASTER, METALLIC_CHANNEL, METALLIC_CHANNEL, METALLIC_CHANNEL)); } if (Settings.bRoughnessMap) { FinalTemplate += FString::Printf(TEXT(",%s"), *FString::Printf(SPL_TEMPLATE_COLORCASTER, ROUGHNESS_CHANNEL, ROUGHNESS_CHANNEL, ROUGHNESS_CHANNEL)); } if (Settings.bSpecularMap) { FinalTemplate += FString::Printf(TEXT(",%s"), *FString::Printf(SPL_TEMPLATE_COLORCASTER, SPECULAR_CHANNEL, SPECULAR_CHANNEL, SPECULAR_CHANNEL)); } if (Settings.bNormalMap) { FinalTemplate += FString::Printf(TEXT(",%s"), *FString::Printf(SPL_TEMPLATE_NORMALCASTER, NORMAL_CHANNEL, NORMAL_CHANNEL)); } return FinalTemplate; } /** * Calculates the view distance that a mesh should be displayed at. * @param MaxDeviation - The maximum surface-deviation between the reduced geometry and the original. This value should be acquired from Simplygon * @returns The calculated view distance */ float CalculateViewDistance( float MaxDeviation ) { // We want to solve for the depth in world space given the screen space distance between two pixels // // Assumptions: // 1. There is no scaling in the view matrix. // 2. The horizontal FOV is 90 degrees. // 3. The backbuffer is 1920x1080. // // If we project two points at (X,Y,Z) and (X',Y,Z) from view space, we get their screen // space positions: (X/Z, Y'/Z) and (X'/Z, Y'/Z) where Y' = Y * AspectRatio. // // The distance in screen space is then sqrt( (X'-X)^2/Z^2 + (Y'-Y')^2/Z^2 ) // or (X'-X)/Z. This is in clip space, so PixelDist = 1280 * 0.5 * (X'-X)/Z. // // Solving for Z: ViewDist = (X'-X * 640) / PixelDist const float ViewDistance = (MaxDeviation * 960.0f); return ViewDistance; } static FIntPoint ComputeMappingImageSize(const FMaterialProxySettings& Settings) { FIntPoint ImageSize = Settings.TextureSize;/* Settings.BaseColorMapSize; ImageSize = ImageSize.ComponentMax(Settings.NormalMapSize); ImageSize = ImageSize.ComponentMax(Settings.MetallicMapSize); ImageSize = ImageSize.ComponentMax(Settings.RoughnessMapSize); ImageSize = ImageSize.ComponentMax(Settings.SpecularMapSize);*/ return ImageSize; } /** * The method converts ESimplygonTextureSamplingQuality * @param InSamplingQuality - The Caster Settings used to setup the Simplygon Caster. * @param InMappingImage - Simplygon MappingImage. * @result */ uint8 GetSamples(ESimplygonTextureSamplingQuality::Type InSamplingQuality) { switch (InSamplingQuality) { case ESimplygonTextureSamplingQuality::Poor: return 1; case ESimplygonTextureSamplingQuality::Low: return 2; case ESimplygonTextureSamplingQuality::Medium: return 6; case ESimplygonTextureSamplingQuality::High: return 8; } return 1; } uint8 ConvertColorChannelToInt(ESimplygonColorChannels::Type InSamplingQuality) { switch (InSamplingQuality) { case ESimplygonColorChannels::RGBA: return 4; case ESimplygonColorChannels::RGB: return 3; case ESimplygonColorChannels::L: return 1; } return 3; } /* * (-1, 0, 0) * (0, 1, 0) * (0, 0, 1) */ const FMatrix& GetConversionMatrix() { static FMatrix m; static bool bInitialized = false; if (!bInitialized) { m.SetIdentity(); m.SetAxis(0, FVector(1, 0, 0)); m.SetAxis(1, FVector(0, 0, 1)); m.SetAxis(2, FVector(0, 1, 0)); bInitialized = true; } return m; } /* * (1,0,0) * (0,0,1) * (0,1,0) */ const FMatrix& GetConversionMatrixYUP() { static FMatrix m; static bool bInitialized = false; if (!bInitialized) { m.SetIdentity(); m.SetAxis(0, FVector(1, 0, 0)); m.SetAxis(1, FVector(0, 0, 1)); m.SetAxis(2, FVector(0, 1, 0)); bInitialized = true; } return m; } ssf::pssfMeshData CreateSSFMeshDataFromRawMesh(const FRawMesh& RawMesh,TArray<FBox2D> TextureBounds, TArray<FVector2D> InTexCoords) { int32 NumVertices = RawMesh.VertexPositions.Num(); int32 NumWedges = RawMesh.WedgeIndices.Num(); int32 NumTris = NumWedges / 3; if (NumWedges == 0) { return NULL; } //assuming everything is left-handed so no need to change winding order and handedness. SSF supports both ssf::pssfMeshData SgMeshData = new ssf::ssfMeshData(); //setup vertex coordinates ssf::ssfList<ssf::ssfVector3> & SgCoords = SgMeshData->Coordinates.Create(); SgCoords.Items.resize(NumVertices); for (int32 VertexIndex = 0; VertexIndex < NumVertices; ++VertexIndex) { ssf::ssfVector3 SgCurrentVertex; FVector4 Position = GetConversionMatrixYUP().TransformPosition(RawMesh.VertexPositions[VertexIndex]); SgCurrentVertex.V[0] = double(Position.X); SgCurrentVertex.V[1] = double(Position.Y); SgCurrentVertex.V[2] = double(Position.Z); SgCoords.Items[VertexIndex] = SgCurrentVertex; } //setup triangle data ssf::ssfList<ssf::ssfIndex3>& SgTriangleIds = SgMeshData->TriangleIndices.Create(); ssf::ssfList<ssf::ssfUInt32>& SgMaterialIds = SgMeshData->MaterialIndices.Create(); ssf::ssfList<ssf::ssfInt32>& SgSmoothingGroupIds = SgMeshData->SmoothingGroup.Create(); SgTriangleIds.Items.resize(NumTris); SgMaterialIds.Items.resize(NumTris); SgSmoothingGroupIds.Items.resize(NumTris); for (int32 TriIndex = 0; TriIndex < NumTris; ++TriIndex) { SgTriangleIds.Items[TriIndex].V[0] = RawMesh.WedgeIndices[TriIndex * 3 + 0]; SgTriangleIds.Items[TriIndex].V[1] = RawMesh.WedgeIndices[TriIndex * 3 + 1]; SgTriangleIds.Items[TriIndex].V[2] = RawMesh.WedgeIndices[TriIndex * 3 + 2]; } for (int32 TriIndex = 0; TriIndex < NumTris; ++TriIndex) { SgMaterialIds.Items[TriIndex] = RawMesh.FaceMaterialIndices[TriIndex]; SgSmoothingGroupIds.Items[TriIndex] = RawMesh.FaceSmoothingMasks[TriIndex]; } SgMeshData->MaterialIndices.Create(); //setup texcoords for (int32 TexCoordIndex = 0; TexCoordIndex < MAX_MESH_TEXTURE_COORDS; ++TexCoordIndex) { const TArray<FVector2D>& SrcTexCoords = (TexCoordIndex == 0 && InTexCoords.Num() == NumWedges) ? InTexCoords : RawMesh.WedgeTexCoords[TexCoordIndex]; if (SrcTexCoords.Num() == NumWedges) { ssf::ssfNamedList<ssf::ssfVector2> SgTexCoord; //Since SSF uses Named Channels SgTexCoord.Name = FSimplygonSSFHelper::TCHARToSSFString(*FString::Printf(TEXT("TexCoord%d"), TexCoordIndex)); SgTexCoord.Items.resize(NumWedges); int32 WedgeIndex = 0; for (int32 TriIndex = 0; TriIndex < NumTris; ++TriIndex) { int32 MaterialIndex = RawMesh.FaceMaterialIndices[TriIndex]; // Compute texture bounds for current material. float MinU = 0, ScaleU = 1; float MinV = 0, ScaleV = 1; if (TextureBounds.IsValidIndex(MaterialIndex) && TexCoordIndex == 0 && InTexCoords.Num() == 0) { const FBox2D& Bounds = TextureBounds[MaterialIndex]; if (Bounds.GetArea() > 0) { MinU = Bounds.Min.X; MinV = Bounds.Min.Y; ScaleU = 1.0f / (Bounds.Max.X - Bounds.Min.X); ScaleV = 1.0f / (Bounds.Max.Y - Bounds.Min.Y); } } for (int32 CornerIndex = 0; CornerIndex < 3; ++CornerIndex, ++WedgeIndex) { const FVector2D& TexCoord = SrcTexCoords[WedgeIndex]; ssf::ssfVector2 temp; temp.V[0] = (TexCoord.X - MinU) * ScaleU; temp.V[1] = (TexCoord.Y - MinV) * ScaleV; SgTexCoord.Items[WedgeIndex] = temp; } } SgMeshData->TextureCoordinatesList.push_back(SgTexCoord); } } //setup colors if (RawMesh.WedgeColors.Num() == NumWedges) { //setup the color named channel . Currently its se to index zero. If multiple colors channel are need then use an index instead of 0 ssf::ssfNamedList<ssf::ssfVector4> SgColors; SgColors.Name = FSimplygonSSFHelper::TCHARToSSFString(*FString::Printf(TEXT("Colors%d"), 0)); SgColors.Items.resize(NumWedges); for (int32 WedgeIndex = 0; WedgeIndex < NumWedges; ++WedgeIndex) { FLinearColor LinearColor(RawMesh.WedgeColors[WedgeIndex]); SgColors.Items[WedgeIndex].V[0] = LinearColor.R; SgColors.Items[WedgeIndex].V[1] = LinearColor.G; SgColors.Items[WedgeIndex].V[2] = LinearColor.B; SgColors.Items[WedgeIndex].V[3] = LinearColor.A; } SgMeshData->ColorsList.push_back(SgColors); } if (RawMesh.WedgeTangentZ.Num() == NumWedges) { if (RawMesh.WedgeTangentX.Num() == NumWedges && RawMesh.WedgeTangentY.Num() == NumWedges) { ssf::ssfList<ssf::ssfVector3> & SgTangents = SgMeshData->Tangents.Create(); SgTangents.Items.resize(NumWedges); for (int32 WedgeIndex = 0; WedgeIndex < NumWedges; ++WedgeIndex) { ssf::ssfVector3 SsfTangent; FVector4 Tangent = GetConversionMatrixYUP().TransformPosition(RawMesh.WedgeTangentX[WedgeIndex]); SsfTangent.V[0] = double(Tangent.X); SsfTangent.V[1] = double(Tangent.Y); SsfTangent.V[2] = double(Tangent.Z); SgTangents.Items[WedgeIndex] = SsfTangent; } ssf::ssfList<ssf::ssfVector3> & SgBitangents = SgMeshData->Bitangents.Create(); SgBitangents.Items.resize(NumWedges); for (int32 WedgeIndex = 0; WedgeIndex < NumWedges; ++WedgeIndex) { ssf::ssfVector3 SsfBitangent; FVector4 Bitangent = GetConversionMatrixYUP().TransformPosition(RawMesh.WedgeTangentY[WedgeIndex]); SsfBitangent.V[0] = double(RawMesh.WedgeTangentY[WedgeIndex].X); SsfBitangent.V[1] = double(RawMesh.WedgeTangentY[WedgeIndex].Y); SsfBitangent.V[2] = double(RawMesh.WedgeTangentY[WedgeIndex].Z); SgBitangents.Items[WedgeIndex] = SsfBitangent; } } ssf::ssfList<ssf::ssfVector3> & SgNormals = SgMeshData->Normals.Create(); SgNormals.Items.resize(NumWedges); for (int32 WedgeIndex = 0; WedgeIndex < NumWedges; ++WedgeIndex) { ssf::ssfVector3 SsfNormal; FVector4 Normal = GetConversionMatrixYUP().TransformPosition(RawMesh.WedgeTangentZ[WedgeIndex]); SsfNormal.V[0] = double(Normal.X); SsfNormal.V[1] = double(Normal.Y); SsfNormal.V[2] = double(Normal.Z); SgNormals.Items[WedgeIndex] = SsfNormal; } } return SgMeshData; } ssf::pssfMeshData CreateSSFMeshDataFromRawMesh(const FRawMesh& RawMesh) { int32 NumVertices = RawMesh.VertexPositions.Num(); int32 NumWedges = RawMesh.WedgeIndices.Num(); int32 NumTris = NumWedges / 3; if (NumWedges == 0) { return NULL; } //assuming everything is left-handed so no need to change winding order and handedness. SSF supports both ssf::pssfMeshData SgMeshData = new ssf::ssfMeshData(); //setup vertex coordinates ssf::ssfList<ssf::ssfVector3> & SgCoords = SgMeshData->Coordinates.Create(); SgCoords.Items.resize(NumVertices); for (int32 VertexIndex = 0; VertexIndex < NumVertices; ++VertexIndex) { ssf::ssfVector3 SgCurrentVertex; FVector4 Position = GetConversionMatrixYUP().TransformPosition(RawMesh.VertexPositions[VertexIndex]); SgCurrentVertex.V[0] = double(Position.X); SgCurrentVertex.V[1] = double(Position.Y); SgCurrentVertex.V[2] = double(Position.Z); SgCoords.Items[VertexIndex] = SgCurrentVertex; } //setup triangle data ssf::ssfList<ssf::ssfIndex3>& SgTriangleIds = SgMeshData->TriangleIndices.Create(); ssf::ssfList<ssf::ssfUInt32>& SgMaterialIds = SgMeshData->MaterialIndices.Create(); ssf::ssfList<ssf::ssfInt32>& SgSmoothingGroupIds = SgMeshData->SmoothingGroup.Create(); SgTriangleIds.Items.resize(NumTris); SgMaterialIds.Items.resize(NumTris); SgSmoothingGroupIds.Items.resize(NumTris); for (int32 TriIndex = 0; TriIndex < NumTris; ++TriIndex) { SgTriangleIds.Items[TriIndex].V[0] = RawMesh.WedgeIndices[TriIndex * 3 + 0]; SgTriangleIds.Items[TriIndex].V[1] = RawMesh.WedgeIndices[TriIndex * 3 + 1]; SgTriangleIds.Items[TriIndex].V[2] = RawMesh.WedgeIndices[TriIndex * 3 + 2]; } for (int32 TriIndex = 0; TriIndex < NumTris; ++TriIndex) { SgMaterialIds.Items[TriIndex] = RawMesh.FaceMaterialIndices[TriIndex]; SgSmoothingGroupIds.Items[TriIndex] = RawMesh.FaceSmoothingMasks[TriIndex]; } SgMeshData->MaterialIndices.Create(); //setup texcoords for (int32 TexCoordIndex = 0; TexCoordIndex < MAX_MESH_TEXTURE_COORDS; ++TexCoordIndex) { if (RawMesh.WedgeTexCoords[TexCoordIndex].Num() == NumWedges) { ssf::ssfNamedList<ssf::ssfVector2> SgTexCoord; //Since SSF uses Named Channels SgTexCoord.Name = FSimplygonSSFHelper::TCHARToSSFString(*FString::Printf(TEXT("TexCoord%d"), TexCoordIndex)); SgTexCoord.Items.resize(NumWedges); for (int WedgeIndex = 0; WedgeIndex < NumWedges; WedgeIndex++) { ssf::ssfVector2 temp; temp.V[0] = RawMesh.WedgeTexCoords[TexCoordIndex][WedgeIndex].X; temp.V[1] = RawMesh.WedgeTexCoords[TexCoordIndex][WedgeIndex].Y; SgTexCoord.Items[WedgeIndex] = temp; } SgMeshData->TextureCoordinatesList.push_back(SgTexCoord); } } //setup colors if (RawMesh.WedgeColors.Num() == NumWedges) { //setup the color named channel . Currently its se to index zero. If multiple colors channel are need then use an index instead of 0 ssf::ssfNamedList<ssf::ssfVector4> SgColors; SgColors.Name = FSimplygonSSFHelper::TCHARToSSFString(*FString::Printf(TEXT("Colors%d"), 0)); SgColors.Items.resize(NumWedges); for (int32 WedgeIndex = 0; WedgeIndex < NumWedges; ++WedgeIndex) { FLinearColor LinearColor(RawMesh.WedgeColors[WedgeIndex]); SgColors.Items[WedgeIndex].V[0] = LinearColor.R; SgColors.Items[WedgeIndex].V[1] = LinearColor.G; SgColors.Items[WedgeIndex].V[2] = LinearColor.B; SgColors.Items[WedgeIndex].V[3] = LinearColor.A; } SgMeshData->ColorsList.push_back(SgColors); } if (RawMesh.WedgeTangentZ.Num() == NumWedges) { if (RawMesh.WedgeTangentX.Num() == NumWedges && RawMesh.WedgeTangentY.Num() == NumWedges) { ssf::ssfList<ssf::ssfVector3> & SgTangents = SgMeshData->Tangents.Create(); SgTangents.Items.resize(NumWedges); for (int32 WedgeIndex = 0; WedgeIndex < NumWedges; ++WedgeIndex) { ssf::ssfVector3 SsfTangent; FVector4 Tangent = GetConversionMatrixYUP().TransformPosition(RawMesh.WedgeTangentX[WedgeIndex]); SsfTangent.V[0] = double(Tangent.X); SsfTangent.V[1] = double(Tangent.Y); SsfTangent.V[2] = double(Tangent.Z); SgTangents.Items[WedgeIndex] = SsfTangent; } ssf::ssfList<ssf::ssfVector3> & SgBitangents = SgMeshData->Bitangents.Create(); SgBitangents.Items.resize(NumWedges); for (int32 WedgeIndex = 0; WedgeIndex < NumWedges; ++WedgeIndex) { ssf::ssfVector3 SsfBitangent; FVector4 Bitangent = GetConversionMatrixYUP().TransformPosition(RawMesh.WedgeTangentY[WedgeIndex]); SsfBitangent.V[0] = double(RawMesh.WedgeTangentY[WedgeIndex].X); SsfBitangent.V[1] = double(RawMesh.WedgeTangentY[WedgeIndex].Y); SsfBitangent.V[2] = double(RawMesh.WedgeTangentY[WedgeIndex].Z); SgBitangents.Items[WedgeIndex] = SsfBitangent; } } ssf::ssfList<ssf::ssfVector3> & SgNormals = SgMeshData->Normals.Create(); SgNormals.Items.resize(NumWedges); for (int32 WedgeIndex = 0; WedgeIndex < NumWedges; ++WedgeIndex) { ssf::ssfVector3 SsfNormal; FVector4 Normal = GetConversionMatrixYUP().TransformPosition(RawMesh.WedgeTangentZ[WedgeIndex]); SsfNormal.V[0] = double(Normal.X); SsfNormal.V[1] = double(Normal.Y); SsfNormal.V[2] = double(Normal.Z); SgNormals.Items[WedgeIndex] = SsfNormal; } } return SgMeshData; } void CopyTextureData( TArray<FColor>& OutSamples, FIntPoint& OutTextureSize, FString ChannelName, FString InputPath, bool IsNormalMap = false ) { IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper")); IImageWrapperPtr ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG); //if (ImageWrapper.IsValid() && ImageWrapper->GetRaw() TArray<uint8> TextureData; if (!FFileHelper::LoadFileToArray(TextureData, *FPaths::ConvertRelativePathToFull(InputPath)) && TextureData.Num() > 0) { UE_LOG(LogSimplygonSwarm, Warning, TEXT("Unable to find Texture file %s"), *InputPath); } else { const TArray<uint8>* RawData = NULL; if (ImageWrapper->SetCompressed(TextureData.GetData(), TextureData.Num()) && ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, RawData)) { OutTextureSize.X = ImageWrapper->GetHeight(); OutTextureSize.Y = ImageWrapper->GetWidth(); int32 TexelsCount = ImageWrapper->GetHeight() * ImageWrapper->GetWidth(); OutSamples.Empty(TexelsCount); OutSamples.AddUninitialized(TexelsCount); for (int32 X = 0; X < ImageWrapper->GetHeight(); ++X) { for (int32 Y = 0; Y < ImageWrapper->GetWidth(); ++Y) { int32 PixelIndex = ImageWrapper->GetHeight() * X + Y; OutSamples[PixelIndex].B = (*RawData)[PixelIndex*sizeof(FColor) + 0]; OutSamples[PixelIndex].G = (*RawData)[PixelIndex*sizeof(FColor) + 1]; OutSamples[PixelIndex].R = (*RawData)[PixelIndex*sizeof(FColor) + 2]; OutSamples[PixelIndex].A = (*RawData)[PixelIndex*sizeof(FColor) + 3]; } } } //just for the fun of it write it out } } ssf::pssfMaterialChannel SetMaterialChannelData( const TArray<FColor>& InSamples, FIntPoint InTextureSize, ssf::pssfTextureTable SgTextureTable, FString ChannelName, FString TextureName,FString OutputPath, bool IsSRGB = true) { ssf::pssfMaterialChannel SgMaterialChannel = new ssf::ssfMaterialChannel(); SgMaterialChannel->ChannelName.Set(FSimplygonSSFHelper::TCHARToSSFString(*ChannelName)); if (InSamples.Num() >= 1) { IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper")); IImageWrapperPtr ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG); FString TextureOutputRelative = FString::Printf(TEXT("%s/%s.png"), ANSI_TO_TCHAR(SgTextureTable->TexturesDirectory->Value.c_str()), *TextureName); FString TextureOutputPath = FString::Printf(TEXT("%s%s"), *OutputPath, *TextureOutputRelative); if (ImageWrapper.IsValid() && ImageWrapper->SetRaw(&InSamples[0], InSamples.Num() * sizeof(FColor), InTextureSize.X, InTextureSize.Y, ERGBFormat::BGRA, 8)) { if (FFileHelper::SaveArrayToFile(ImageWrapper->GetCompressed(), *TextureOutputPath)) { ssf::pssfTexture SgTexture = new ssf::ssfTexture(); ssf::pssfMaterialChannelTextureDescriptor SgTextureDescriptor = new ssf::ssfMaterialChannelTextureDescriptor(); SgTexture->Id.Set(FSimplygonSSFHelper::SSFNewGuid()); SgTexture->Name.Set(FSimplygonSSFHelper::TCHARToSSFString(*TextureName)); SgTexture->Path.Set(FSimplygonSSFHelper::TCHARToSSFString(*TextureOutputRelative)); SgTextureDescriptor->TextureID.Set(SgTexture->Id.Get()); //TODO: Some how get the TexCoord Channel information down here. This is a hack that will only work for a very simple mesh SgTextureDescriptor->TexCoordSet.Set(FSimplygonSSFHelper::TCHARToSSFString(TEXT("TexCoord0"))); SgMaterialChannel->MaterialChannelTextureDescriptorList.push_back(SgTextureDescriptor); FString ShadingNetwork = FString::Printf(SHADING_NETWORK_TEMPLATE, *TextureName, TEXT("TexCoord0"), (int)IsSRGB); SgMaterialChannel->ShadingNetwork.Set(FSimplygonSSFHelper::TCHARToSSFString(*ShadingNetwork)); SgTextureTable->TextureList.push_back(SgTexture); } else { //UE_LOG(LogSimplygonSwarm, Log, TEXT("%s"), TEXT("Could not save textrue to file"); } } } else { // InSGMaterial->SetColorRGB(SGMaterialChannelName, 1.0f, 1.0f, 1.0f); SgMaterialChannel->Color.Create(); SgMaterialChannel->Color->V[0] = 1.0f; SgMaterialChannel->Color->V[1] = 1.0f; SgMaterialChannel->Color->V[2] = 1.0f; SgMaterialChannel->Color->V[3] = 1.0f; } return SgMaterialChannel; } bool CreateSSFMaterialFromFlattenMaterial( const TArray<FFlattenMaterial>& InputMaterials, const FMaterialProxySettings& InMaterialLODSettings, ssf::pssfMaterialTable SgMaterialTable, ssf::pssfTextureTable SgTextureTable, FString OutputFolderPath, bool bReleaseInputMaterials, TMap<int,FString>& MaterialMapping) { if (InputMaterials.Num() == 0) { //If there are no materials, feed Simplygon with a default material instead. UE_LOG(LogSimplygonSwarm, Log, TEXT("Input meshes do not contain any materials. A proxy without material will be generated.")); return false; } for (int32 MaterialIndex = 0; MaterialIndex < InputMaterials.Num(); MaterialIndex++) { FString MaterialGuidString = FGuid::NewGuid().ToString(); const FFlattenMaterial& FlattenMaterial = InputMaterials[MaterialIndex]; FString MaterialName = FString::Printf(TEXT("Material%d"), MaterialIndex); ssf::pssfMaterial SgMaterial = new ssf::ssfMaterial(); SgMaterial->Id.Set(FSimplygonSSFHelper::TCHARToSSFString(*MaterialGuidString)); SgMaterial->Name.Set(FSimplygonSSFHelper::TCHARToSSFString(*MaterialName)); MaterialMapping.Add(MaterialIndex, MaterialGuidString); // Does current material have BaseColor? if (FlattenMaterial.DiffuseSamples.Num()) { FString ChannelName(BASECOLOR_CHANNEL); ssf::pssfMaterialChannel BaseColorChannel = SetMaterialChannelData(FlattenMaterial.DiffuseSamples, FlattenMaterial.DiffuseSize, SgTextureTable, ChannelName, FString::Printf(TEXT("%s%s"), *MaterialName, *ChannelName), OutputFolderPath); // if (InMaterialLODSettings.ChannelsToCast[0].bBakeVertexColors) //{ //This shit does not work with ssf unless a vertedc color node with a channel is set which is multiplied with the base color //SgMaterial->MaterialChannelList.push_back() //SGMaterial->SetVertexColorChannel(SimplygonSDK::SG_MATERIAL_CHANNEL_BASECOLOR, 0); //} SgMaterial->MaterialChannelList.push_back(BaseColorChannel); } // Does current material have Metallic? if (FlattenMaterial.MetallicSamples.Num()) { FString ChannelName(METALLIC_CHANNEL); ssf::pssfMaterialChannel MetallicChannel = SetMaterialChannelData(FlattenMaterial.MetallicSamples, FlattenMaterial.MetallicSize, SgTextureTable, ChannelName, FString::Printf(TEXT("%s%s"), *MaterialName, *ChannelName), OutputFolderPath); SgMaterial->MaterialChannelList.push_back(MetallicChannel); } // Does current material have Specular? if (FlattenMaterial.SpecularSamples.Num()) { FString ChannelName(SPECULAR_CHANNEL); ssf::pssfMaterialChannel SpecularChannel = SetMaterialChannelData(FlattenMaterial.SpecularSamples, FlattenMaterial.SpecularSize, SgTextureTable, ChannelName, FString::Printf(TEXT("%s%s"), *MaterialName, *ChannelName), OutputFolderPath); SgMaterial->MaterialChannelList.push_back(SpecularChannel); } // Does current material have Roughness? if (FlattenMaterial.RoughnessSamples.Num()) { FString ChannelName(ROUGHNESS_CHANNEL); ssf::pssfMaterialChannel RoughnessChannel = SetMaterialChannelData(FlattenMaterial.RoughnessSamples, FlattenMaterial.RoughnessSize, SgTextureTable, ChannelName, FString::Printf(TEXT("%s%s"), *MaterialName, *ChannelName), OutputFolderPath); SgMaterial->MaterialChannelList.push_back(RoughnessChannel); } //Does current material have a normalmap? if (FlattenMaterial.NormalSamples.Num()) { FString ChannelName(NORMAL_CHANNEL); SgMaterial->TangentSpaceNormals.Create(); SgMaterial->TangentSpaceNormals.Set(true); ssf::pssfMaterialChannel NormalChannel = SetMaterialChannelData(FlattenMaterial.NormalSamples, FlattenMaterial.NormalSize, SgTextureTable, ChannelName, FString::Printf(TEXT("%s%s"), *MaterialName, *ChannelName), OutputFolderPath, false); SgMaterial->MaterialChannelList.push_back(NormalChannel); } // Does current material have Opacity? if (FlattenMaterial.OpacitySamples.Num()) { FString ChannelName(OPACITY_CHANNEL); ssf::pssfMaterialChannel OpacityChannel = SetMaterialChannelData(FlattenMaterial.OpacitySamples, FlattenMaterial.OpacitySize, SgTextureTable, ChannelName, FString::Printf(TEXT("%s%s"), *MaterialName, *ChannelName), OutputFolderPath); SgMaterial->MaterialChannelList.push_back(OpacityChannel); } if (FlattenMaterial.EmissiveSamples.Num()) { FString ChannelName(EMISSIVE_CHANNEL); ssf::pssfMaterialChannel EmissiveChannel = SetMaterialChannelData(FlattenMaterial.EmissiveSamples, FlattenMaterial.EmissiveSize, SgTextureTable, ChannelName, FString::Printf(TEXT("%s%s"), *MaterialName, *ChannelName), OutputFolderPath); SgMaterial->MaterialChannelList.push_back(EmissiveChannel); } else { FString ChannelName(EMISSIVE_CHANNEL); TArray<FColor> BlackEmissive; BlackEmissive.AddZeroed(1); ssf::pssfMaterialChannel EmissiveChannel = SetMaterialChannelData(FlattenMaterial.EmissiveSamples, FlattenMaterial.EmissiveSize, SgTextureTable, ChannelName, FString::Printf(TEXT("%s%s"), *MaterialName, *ChannelName), OutputFolderPath); SgMaterial->MaterialChannelList.push_back(EmissiveChannel); } SgMaterialTable->MaterialList.push_back(SgMaterial); if (bReleaseInputMaterials) { // Release FlattenMaterial. Using const_cast here to avoid removal of "const" from input data here // and above the call chain. const_cast<FFlattenMaterial*>(&FlattenMaterial)->ReleaseData(); } } return true; } }; TScopedPointer<FSimplygonSwarm> GSimplygonMeshReduction; void FSimplygonSwarmModule::StartupModule() { GSimplygonMeshReduction = FSimplygonSwarm::Create(); } void FSimplygonSwarmModule::ShutdownModule() { } IMeshReduction* FSimplygonSwarmModule::GetMeshReductionInterface() { return nullptr; } IMeshMerging* FSimplygonSwarmModule::GetMeshMergingInterface() { return GSimplygonMeshReduction; } #undef LOCTEXT_NAMESPACE
38.647346
1,674
0.721832
[ "mesh", "geometry", "object" ]
f66b939d00fa8276cbbe85d8760bb90c87fee168
24,030
cpp
C++
src/sksl/SkSLMain.cpp
haocxy/googlesource-skia-skia
44b7568c8a4ef6bbdba8f892902b751afc19bf7d
[ "BSD-3-Clause" ]
null
null
null
src/sksl/SkSLMain.cpp
haocxy/googlesource-skia-skia
44b7568c8a4ef6bbdba8f892902b751afc19bf7d
[ "BSD-3-Clause" ]
null
null
null
src/sksl/SkSLMain.cpp
haocxy/googlesource-skia-skia
44b7568c8a4ef6bbdba8f892902b751afc19bf7d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #define SK_OPTS_NS skslc_standalone #include "src/opts/SkChecksum_opts.h" #include "src/opts/SkVM_opts.h" #include "src/gpu/GrShaderUtils.h" #include "src/sksl/SkSLCompiler.h" #include "src/sksl/SkSLDehydrator.h" #include "src/sksl/SkSLFileOutputStream.h" #include "src/sksl/SkSLIRGenerator.h" #include "src/sksl/SkSLStringStream.h" #include "src/sksl/SkSLUtil.h" #include "src/sksl/codegen/SkSLPipelineStageCodeGenerator.h" #include "src/sksl/codegen/SkSLVMCodeGenerator.h" #include "src/sksl/ir/SkSLUnresolvedFunction.h" #include "spirv-tools/libspirv.hpp" #include <fstream> #include <limits.h> #include <stdarg.h> #include <stdio.h> void SkDebugf(const char format[], ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); } namespace SkOpts { decltype(hash_fn) hash_fn = skslc_standalone::hash_fn; decltype(interpret_skvm) interpret_skvm = skslc_standalone::interpret_skvm; } enum class ResultCode { kSuccess = 0, kCompileError = 1, kInputError = 2, kOutputError = 3, kConfigurationError = 4, }; static std::unique_ptr<SkWStream> as_SkWStream(SkSL::OutputStream& s) { struct Adapter : public SkWStream { public: Adapter(SkSL::OutputStream& out) : fOut(out), fBytesWritten(0) {} bool write(const void* buffer, size_t size) override { fOut.write(buffer, size); fBytesWritten += size; return true; } void flush() override {} size_t bytesWritten() const override { return fBytesWritten; } private: SkSL::OutputStream& fOut; size_t fBytesWritten; }; return std::make_unique<Adapter>(s); } // Given the path to a file (e.g. src/gpu/effects/GrFooFragmentProcessor.fp) and the expected // filename prefix and suffix (e.g. "Gr" and ".fp"), returns the "base name" of the // file (in this case, 'FooFragmentProcessor'). If no match, returns the empty string. static SkSL::String base_name(const SkSL::String& fpPath, const char* prefix, const char* suffix) { SkSL::String result; const char* end = &*fpPath.end(); const char* fileName = end; // back up until we find a slash while (fileName != fpPath && '/' != *(fileName - 1) && '\\' != *(fileName - 1)) { --fileName; } if (!strncmp(fileName, prefix, strlen(prefix)) && !strncmp(end - strlen(suffix), suffix, strlen(suffix))) { result.append(fileName + strlen(prefix), end - fileName - strlen(prefix) - strlen(suffix)); } return result; } // Given a string containing an SkSL program, searches for a #pragma settings comment, like so: // /*#pragma settings Default Sharpen*/ // The passed-in Settings object will be updated accordingly. Any number of options can be provided. static bool detect_shader_settings(const SkSL::String& text, SkSL::Program::Settings* settings, const SkSL::ShaderCapsClass** caps) { using Factory = SkSL::ShaderCapsFactory; // Find a matching comment and isolate the name portion. static constexpr char kPragmaSettings[] = "/*#pragma settings "; const char* settingsPtr = strstr(text.c_str(), kPragmaSettings); if (settingsPtr != nullptr) { // Subtract one here in order to preserve the leading space, which is necessary to allow // consumeSuffix to find the first item. settingsPtr += strlen(kPragmaSettings) - 1; const char* settingsEnd = strstr(settingsPtr, "*/"); if (settingsEnd != nullptr) { SkSL::String settingsText{settingsPtr, size_t(settingsEnd - settingsPtr)}; // Apply settings as requested. Since they can come in any order, repeat until we've // consumed them all. for (;;) { const size_t startingLength = settingsText.length(); if (settingsText.consumeSuffix(" AddAndTrueToLoopCondition")) { static auto s_addAndTrueCaps = Factory::AddAndTrueToLoopCondition(); *caps = s_addAndTrueCaps.get(); } if (settingsText.consumeSuffix(" BlendModesFailRandomlyForAllZeroVec")) { static auto s_blendZeroCaps = Factory::BlendModesFailRandomlyForAllZeroVec(); *caps = s_blendZeroCaps.get(); } if (settingsText.consumeSuffix(" CannotUseFractForNegativeValues")) { static auto s_negativeFractCaps = Factory::CannotUseFractForNegativeValues(); *caps = s_negativeFractCaps.get(); } if (settingsText.consumeSuffix(" CannotUseFragCoord")) { static auto s_noFragCoordCaps = Factory::CannotUseFragCoord(); *caps = s_noFragCoordCaps.get(); } if (settingsText.consumeSuffix(" CannotUseMinAndAbsTogether")) { static auto s_minAbsCaps = Factory::CannotUseMinAndAbsTogether(); *caps = s_minAbsCaps.get(); } if (settingsText.consumeSuffix(" Default")) { static auto s_defaultCaps = Factory::Default(); *caps = s_defaultCaps.get(); } if (settingsText.consumeSuffix(" EmulateAbsIntFunction")) { static auto s_emulateAbsIntCaps = Factory::EmulateAbsIntFunction(); *caps = s_emulateAbsIntCaps.get(); } if (settingsText.consumeSuffix(" IncompleteShortIntPrecision")) { static auto s_incompleteShortIntCaps = Factory::IncompleteShortIntPrecision(); *caps = s_incompleteShortIntCaps.get(); } if (settingsText.consumeSuffix(" MustGuardDivisionEvenAfterExplicitZeroCheck")) { static auto s_div0Caps = Factory::MustGuardDivisionEvenAfterExplicitZeroCheck(); *caps = s_div0Caps.get(); } if (settingsText.consumeSuffix(" MustForceNegatedAtanParamToFloat")) { static auto s_negativeAtanCaps = Factory::MustForceNegatedAtanParamToFloat(); *caps = s_negativeAtanCaps.get(); } if (settingsText.consumeSuffix(" MustForceNegatedLdexpParamToMultiply")) { static auto s_negativeLdexpCaps = Factory::MustForceNegatedLdexpParamToMultiply(); *caps = s_negativeLdexpCaps.get(); } if (settingsText.consumeSuffix(" RemovePowWithConstantExponent")) { static auto s_powCaps = Factory::RemovePowWithConstantExponent(); *caps = s_powCaps.get(); } if (settingsText.consumeSuffix(" RewriteDoWhileLoops")) { static auto s_rewriteLoopCaps = Factory::RewriteDoWhileLoops(); *caps = s_rewriteLoopCaps.get(); } if (settingsText.consumeSuffix(" RewriteMatrixVectorMultiply")) { static auto s_rewriteMatVecMulCaps = Factory::RewriteMatrixVectorMultiply(); *caps = s_rewriteMatVecMulCaps.get(); } if (settingsText.consumeSuffix(" RewriteMatrixComparisons")) { static auto s_rewriteMatrixComparisons = Factory::RewriteMatrixComparisons(); *caps = s_rewriteMatrixComparisons.get(); } if (settingsText.consumeSuffix(" ShaderDerivativeExtensionString")) { static auto s_derivativeCaps = Factory::ShaderDerivativeExtensionString(); *caps = s_derivativeCaps.get(); } if (settingsText.consumeSuffix(" UnfoldShortCircuitAsTernary")) { static auto s_ternaryCaps = Factory::UnfoldShortCircuitAsTernary(); *caps = s_ternaryCaps.get(); } if (settingsText.consumeSuffix(" UsesPrecisionModifiers")) { static auto s_precisionCaps = Factory::UsesPrecisionModifiers(); *caps = s_precisionCaps.get(); } if (settingsText.consumeSuffix(" Version110")) { static auto s_version110Caps = Factory::Version110(); *caps = s_version110Caps.get(); } if (settingsText.consumeSuffix(" Version450Core")) { static auto s_version450CoreCaps = Factory::Version450Core(); *caps = s_version450CoreCaps.get(); } if (settingsText.consumeSuffix(" AllowNarrowingConversions")) { settings->fAllowNarrowingConversions = true; } if (settingsText.consumeSuffix(" ForceHighPrecision")) { settings->fForceHighPrecision = true; } if (settingsText.consumeSuffix(" NoES2Restrictions")) { settings->fEnforceES2Restrictions = false; } if (settingsText.consumeSuffix(" NoInline")) { settings->fInlineThreshold = 0; } if (settingsText.consumeSuffix(" InlineThresholdMax")) { settings->fInlineThreshold = INT_MAX; } if (settingsText.consumeSuffix(" Sharpen")) { settings->fSharpenTextures = true; } if (settingsText.empty()) { break; } if (settingsText.length() == startingLength) { printf("Unrecognized #pragma settings: %s\n", settingsText.c_str()); return false; } } } } return true; } /** * Displays a usage banner; used when the command line arguments don't make sense. */ static void show_usage() { printf("usage: skslc <input> <output> <flags>\n" " skslc <worklist>\n" "\n" "Allowed flags:\n" "--settings: honor embedded /*#pragma settings*/ comments.\n" "--nosettings: ignore /*#pragma settings*/ comments\n"); } /** * Handle a single input. */ ResultCode processCommand(std::vector<SkSL::String>& args) { bool honorSettings = true; if (args.size() == 4) { // Handle four-argument case: `skslc in.sksl out.glsl --settings` const SkSL::String& settingsArg = args[3]; if (settingsArg == "--settings") { honorSettings = true; } else if (settingsArg == "--nosettings") { honorSettings = false; } else { printf("unrecognized flag: %s\n\n", settingsArg.c_str()); show_usage(); return ResultCode::kInputError; } } else if (args.size() != 3) { show_usage(); return ResultCode::kInputError; } SkSL::ProgramKind kind; const SkSL::String& inputPath = args[1]; if (inputPath.ends_with(".vert")) { kind = SkSL::ProgramKind::kVertex; } else if (inputPath.ends_with(".frag") || inputPath.ends_with(".sksl")) { kind = SkSL::ProgramKind::kFragment; } else if (inputPath.ends_with(".rtb")) { kind = SkSL::ProgramKind::kRuntimeBlender; } else if (inputPath.ends_with(".rtcf")) { kind = SkSL::ProgramKind::kRuntimeColorFilter; } else if (inputPath.ends_with(".rts")) { kind = SkSL::ProgramKind::kRuntimeShader; } else { printf("input filename must end in '.vert', '.frag', '.rtb', '.rtcf', " "'.rts', or '.sksl'\n"); return ResultCode::kInputError; } std::ifstream in(inputPath); SkSL::String text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); if (in.rdstate()) { printf("error reading '%s'\n", inputPath.c_str()); return ResultCode::kInputError; } SkSL::Program::Settings settings; const SkSL::ShaderCapsClass* caps = &SkSL::standaloneCaps; if (honorSettings) { if (!detect_shader_settings(text, &settings, &caps)) { return ResultCode::kInputError; } } // This tells the compiler where the rt-flip uniform will live should it be required. For // testing purposes we don't care where that is, but the compiler will report an error if we // leave them at their default invalid values, or if the offset overlaps another uniform. settings.fRTFlipOffset = 16384; settings.fRTFlipSet = 0; settings.fRTFlipBinding = 0; const SkSL::String& outputPath = args[2]; auto emitCompileError = [&](SkSL::FileOutputStream& out, const char* errorText) { // Overwrite the compiler output, if any, with an error message. out.close(); SkSL::FileOutputStream errorStream(outputPath); errorStream.writeText("### Compilation failed:\n\n"); errorStream.writeText(errorText); errorStream.close(); // Also emit the error directly to stdout. puts(errorText); }; auto compileProgram = [&](const auto& writeFn) -> ResultCode { SkSL::FileOutputStream out(outputPath); SkSL::Compiler compiler(caps); if (!out.isValid()) { printf("error writing '%s'\n", outputPath.c_str()); return ResultCode::kOutputError; } std::unique_ptr<SkSL::Program> program = compiler.convertProgram(kind, text, settings); if (!program || !writeFn(compiler, *program, out)) { emitCompileError(out, compiler.errorText().c_str()); return ResultCode::kCompileError; } if (!out.close()) { printf("error writing '%s'\n", outputPath.c_str()); return ResultCode::kOutputError; } return ResultCode::kSuccess; }; if (outputPath.ends_with(".spirv")) { return compileProgram( [](SkSL::Compiler& compiler, SkSL::Program& program, SkSL::OutputStream& out) { return compiler.toSPIRV(program, out); }); } else if (outputPath.ends_with(".asm.frag") || outputPath.ends_with(".asm.vert")) { return compileProgram( [](SkSL::Compiler& compiler, SkSL::Program& program, SkSL::OutputStream& out) { // Compile program to SPIR-V assembly in a string-stream. SkSL::StringStream assembly; if (!compiler.toSPIRV(program, assembly)) { return false; } // Convert the string-stream to a SPIR-V disassembly. spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0); const SkSL::String& spirv(assembly.str()); std::string disassembly; if (!tools.Disassemble((const uint32_t*)spirv.data(), spirv.size() / 4, &disassembly)) { return false; } // Finally, write the disassembly to our output stream. out.write(disassembly.data(), disassembly.size()); return true; }); } else if (outputPath.ends_with(".glsl")) { return compileProgram( [](SkSL::Compiler& compiler, SkSL::Program& program, SkSL::OutputStream& out) { return compiler.toGLSL(program, out); }); } else if (outputPath.ends_with(".metal")) { return compileProgram( [](SkSL::Compiler& compiler, SkSL::Program& program, SkSL::OutputStream& out) { return compiler.toMetal(program, out); }); } else if (outputPath.ends_with(".skvm")) { return compileProgram( [](SkSL::Compiler&, SkSL::Program& program, SkSL::OutputStream& out) { skvm::Builder builder{skvm::Features{}}; if (!SkSL::testingOnly_ProgramToSkVMShader(program, &builder)) { return false; } std::unique_ptr<SkWStream> redirect = as_SkWStream(out); builder.done().dump(redirect.get()); return true; }); } else if (outputPath.ends_with(".stage")) { return compileProgram( [](SkSL::Compiler&, SkSL::Program& program, SkSL::OutputStream& out) { class Callbacks : public SkSL::PipelineStage::Callbacks { public: using String = SkSL::String; String getMangledName(const char* name) override { return String(name) + "_0"; } String declareUniform(const SkSL::VarDeclaration* decl) override { fOutput += decl->description(); return String(decl->var().name()); } void defineFunction(const char* decl, const char* body, bool /*isMain*/) override { fOutput += String(decl) + "{" + body + "}"; } void defineStruct(const char* definition) override { fOutput += definition; } void declareGlobal(const char* declaration) override { fOutput += declaration; } String sampleShader(int index, String coords) override { return "shade(child_" + SkSL::to_string(index) + ", " + coords + ")"; } String sampleColorFilter(int index, String color) override { return "filter(child_" + SkSL::to_string(index) + ", " + color + ")"; } String sampleBlender(int index, String src, String dst) override { return "blend(child_" + SkSL::to_string(index) + ", " + src + ", " + dst + ")"; } String fOutput; }; // The .stage output looks almost like valid SkSL, but not quite. // The PipelineStageGenerator bridges the gap between the SkSL in `program`, // and the C++ FP builder API (see GrSkSLFP). In that API, children don't need // to be declared (so they don't emit declarations here). Children are sampled // by index, not name - so all children here are just "child_N". // The input color and coords have names in the original SkSL (as parameters to // main), but those are ignored here. References to those variables become // "_coords" and "_inColor". At runtime, those variable names are irrelevant // when the new SkSL is emitted inside the FP - references to those variables // are replaced with strings from EmitArgs, and might be varyings or differently // named parameters. Callbacks callbacks; SkSL::PipelineStage::ConvertProgram(program, "_coords", "_inColor", "_canvasColor", &callbacks); out.writeString(GrShaderUtils::PrettyPrint(callbacks.fOutput)); return true; }); } else if (outputPath.ends_with(".dehydrated.sksl")) { SkSL::FileOutputStream out(outputPath); SkSL::Compiler compiler(caps); if (!out.isValid()) { printf("error writing '%s'\n", outputPath.c_str()); return ResultCode::kOutputError; } SkSL::LoadedModule module = compiler.loadModule(kind, SkSL::Compiler::MakeModulePath(inputPath.c_str()), /*base=*/nullptr, /*dehydrate=*/true); SkSL::Dehydrator dehydrator; dehydrator.write(*module.fSymbols); dehydrator.write(module.fElements); SkSL::String baseName = base_name(inputPath, "", ".sksl"); SkSL::StringStream buffer; dehydrator.finish(buffer); const SkSL::String& data = buffer.str(); out.printf("static uint8_t SKSL_INCLUDE_%s[] = {", baseName.c_str()); for (size_t i = 0; i < data.length(); ++i) { out.printf("%s%d,", dehydrator.prefixAtOffset(i), uint8_t(data[i])); } out.printf("};\n"); out.printf("static constexpr size_t SKSL_INCLUDE_%s_LENGTH = sizeof(SKSL_INCLUDE_%s);\n", baseName.c_str(), baseName.c_str()); if (!out.close()) { printf("error writing '%s'\n", outputPath.c_str()); return ResultCode::kOutputError; } } else { printf("expected output path to end with one of: .glsl, .metal, .spirv, .asm.frag, .skvm, " ".stage, .asm.vert (got '%s')\n", outputPath.c_str()); return ResultCode::kConfigurationError; } return ResultCode::kSuccess; } /** * Processes multiple inputs in a single invocation of skslc. */ ResultCode processWorklist(const char* worklistPath) { SkSL::String inputPath(worklistPath); if (!inputPath.ends_with(".worklist")) { printf("expected .worklist file, found: %s\n\n", worklistPath); show_usage(); return ResultCode::kConfigurationError; } // The worklist contains one line per argument to pass to skslc. When a blank line is reached, // those arguments will be passed to `processCommand`. auto resultCode = ResultCode::kSuccess; std::vector<SkSL::String> args = {"skslc"}; std::ifstream in(worklistPath); for (SkSL::String line; std::getline(in, line); ) { if (in.rdstate()) { printf("error reading '%s'\n", worklistPath); return ResultCode::kInputError; } if (!line.empty()) { // We found an argument. Remember it. args.push_back(std::move(line)); } else { // We found a blank line. If we have any arguments stored up, process them as a command. if (!args.empty()) { ResultCode outcome = processCommand(args); resultCode = std::max(resultCode, outcome); // Clear every argument except the first ("skslc"). args.resize(1); } } } // If the worklist ended with a list of arguments but no blank line, process those now. if (args.size() > 1) { ResultCode outcome = processCommand(args); resultCode = std::max(resultCode, outcome); } // Return the "worst" status we encountered. For our purposes, compilation errors are the least // serious, because they are expected to occur in unit tests. Other types of errors are not // expected at all during a build. return resultCode; } int main(int argc, const char** argv) { if (argc == 2) { // Worklists are the only two-argument case for skslc, and we don't intend to support // nested worklists, so we can process them here. return (int)processWorklist(argv[1]); } else { // Process non-worklist inputs. std::vector<SkSL::String> args; for (int index=0; index<argc; ++index) { args.push_back(argv[index]); } return (int)processCommand(args); } }
44.254144
100
0.563213
[ "object", "vector" ]
f66f560cd1f1cdd8ad8aecd8adddeef20c917922
1,229
cpp
C++
Algorithms/Rock Climbing.cpp
knroy/Competitive-Programming
5c03b1f4d15bdd1d4ba30a39464b42a7ded59e29
[ "Apache-2.0" ]
null
null
null
Algorithms/Rock Climbing.cpp
knroy/Competitive-Programming
5c03b1f4d15bdd1d4ba30a39464b42a7ded59e29
[ "Apache-2.0" ]
null
null
null
Algorithms/Rock Climbing.cpp
knroy/Competitive-Programming
5c03b1f4d15bdd1d4ba30a39464b42a7ded59e29
[ "Apache-2.0" ]
1
2019-08-07T15:26:19.000Z
2019-08-07T15:26:19.000Z
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cstring> #include <cctype> #define MEM(a,b) memset((a),(b),sizeof(a)) #define MAX(a,b) ((a)>(b)?(a):(b)) #define MIN(a,b) ((a)<(b)?(a):(b)) #define In freopen("In.txt", "r", stdin); #define Out freopen("out.txt", "w", stdout); using namespace std; #define inf 1<<28 int mat[][10]= { {-1, 2, 5}, {4, -2, 3}, {1 , 2 ,10,} }; int dp[10][10]; int r=3,c=3; int rockClimb(int i,int j) { if((i>=0 && i<r) && (j>=0 && j<c)) { if(dp[i][j]!=-1) return dp[i][j]; int ret = -inf; ret = MAX(ret,rockClimb(i+1,j)+mat[i][j]); ret = MAX(ret,rockClimb(i+1,j-1)+mat[i][j]); ret = MAX(ret,rockClimb(i+1,j+1)+mat[i][j]); return dp[i][j] = ret; } else return 0; } int main() { MEM(dp,-1); cout << rockClimb(0,0) << endl; return 0; }
20.147541
53
0.527258
[ "vector" ]