text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
/* (C) 2019 David Lettier lettier.com */ #version 150 #define NUMBER_OF_LIGHTS 4 #define MAX_SHININESS 127.75 #define MAX_FRESNEL_POWER 5.0 uniform float osg_FrameTime; uniform vec2 pi; uniform vec2 gamma; uniform mat4 trans_world_to_view; uniform mat4 trans_view_to_world; uniform sampler2D p3d_Texture0; uniform sampler2D p3d_Texture1; uniform sampler2D p3d_Texture2; uniform sampler2D flowTexture; uniform sampler2D ssaoBlurTexture; uniform struct { vec4 ambient ; vec4 diffuse ; vec4 emission ; vec3 specular ; float shininess ; } p3d_Material; uniform struct { vec4 ambient ; } p3d_LightModel; uniform struct p3d_LightSourceParameters { vec4 color ; vec4 ambient ; vec4 diffuse ; vec4 specular ; vec4 position ; vec3 spotDirection ; float spotExponent ; float spotCutoff ; float spotCosCutoff ; float constantAttenuation ; float linearAttenuation ; float quadraticAttenuation ; vec3 attenuation ; sampler2DShadow shadowMap ; mat4 shadowViewMatrix ; } p3d_LightSource[NUMBER_OF_LIGHTS]; uniform vec2 normalMapsEnabled; uniform vec2 fresnelEnabled; uniform vec2 rimLightEnabled; uniform vec2 blinnPhongEnabled; uniform vec2 celShadingEnabled; uniform vec2 flowMapsEnabled; uniform vec2 specularOnly; uniform vec2 isParticle; uniform vec2 isWater; uniform vec2 sunPosition; in vec4 vertexColor; in vec4 vertexInShadowSpaces[NUMBER_OF_LIGHTS]; in vec4 vertexPosition; in vec3 vertexNormal; in vec3 binormal; in vec3 tangent; in vec2 diffuseCoord; in vec2 normalCoord; out vec4 out0; out vec4 out1; void main() { vec3 shadowColor = pow(vec3(0.149, 0.220, 0.227), vec3(gamma.x)); int shadowSamples = 2; vec4 diffuseColor; if (isParticle.x == 1) { diffuseColor = texture(p3d_Texture0, diffuseCoord) * vertexColor; } else { diffuseColor = texture(p3d_Texture0, diffuseCoord); } diffuseColor.rgb = pow(diffuseColor.rgb, vec3(gamma.x)); vec3 materialSpecularColor = p3d_Material.specular; vec2 flow = texture(flowTexture, normalCoord).xy; flow = (flow - 0.5) * 2.0; flow.x = abs(flow.x) <= 0.02 ? 0.0 : flow.x; flow.y = abs(flow.y) <= 0.02 ? 0.0 : flow.y; vec4 normalTex = texture ( p3d_Texture1 , vec2 ( normalCoord.x + flowMapsEnabled.x * flow.x * osg_FrameTime , normalCoord.y + flowMapsEnabled.y * flow.y * osg_FrameTime ) ); vec3 normal; if (isParticle.x == 1) { normal = normalize((trans_world_to_view * vec4(0.0, 0.0, 1.0, 0.0)).xyz); } else if (normalMapsEnabled.x == 1) { vec3 normalRaw = normalize ( normalTex.rgb * 2.0 - 1.0 ); normal = normalize ( mat3 ( tangent , binormal , vertexNormal ) * normalRaw ); } else { normal = normalize(vertexNormal); } vec4 specularMap = texture(p3d_Texture2, diffuseCoord); vec4 diffuse = vec4(0.0, 0.0, 0.0, diffuseColor.a); vec4 specular = vec4(0.0, 0.0, 0.0, diffuseColor.a); for (int i = 0; i < p3d_LightSource.length(); ++i) { vec3 lightDirection = p3d_LightSource[i].position.xyz - vertexPosition.xyz * p3d_LightSource[i].position.w; vec3 unitLightDirection = normalize(lightDirection); vec3 eyeDirection = normalize(-vertexPosition.xyz); vec3 reflectedDirection = normalize(-reflect(unitLightDirection, normal)); vec3 halfwayDirection = normalize(unitLightDirection + eyeDirection); float lightDistance = length(lightDirection); float attenuation = 1.0 / ( p3d_LightSource[i].constantAttenuation + p3d_LightSource[i].linearAttenuation * lightDistance + p3d_LightSource[i].quadraticAttenuation * (lightDistance * lightDistance) ); if (attenuation <= 0.0) { continue; } float diffuseIntensity = dot(normal, unitLightDirection); if (diffuseIntensity < 0.0) { continue; } diffuseIntensity = celShadingEnabled.x == 1 ? smoothstep(0.1, 0.2, diffuseIntensity) : diffuseIntensity; vec4 lightDiffuseColor = p3d_LightSource[i].diffuse; lightDiffuseColor.rgb = pow(lightDiffuseColor.rgb, vec3(gamma.x)); vec4 diffuseTemp = vec4 ( clamp ( diffuseColor.rgb * lightDiffuseColor.rgb * diffuseIntensity , 0.0 , 1.0 ) , diffuseColor.a ); float specularIntensity = ( blinnPhongEnabled.x == 1 ? clamp(dot(normal, halfwayDirection), 0.0, 1.0) : clamp(dot(eyeDirection, reflectedDirection), 0.0, 1.0) ); specularIntensity = ( celShadingEnabled.x == 1 ? smoothstep(0.9, 1.0, specularIntensity) : specularIntensity ); vec4 lightSpecularColor = p3d_LightSource[i].specular; lightSpecularColor.rgb = pow(lightSpecularColor.rgb, vec3(gamma.x)); vec4 materialSpecularColor = vec4(vec3(specularMap.r), diffuseColor.a); if (fresnelEnabled.x == 1) { float fresnelFactor = dot((blinnPhongEnabled.x == 1 ? halfwayDirection : normal), eyeDirection); fresnelFactor = max(fresnelFactor, 0.0); fresnelFactor = 1.0 - fresnelFactor; fresnelFactor = pow(fresnelFactor, specularMap.b * MAX_FRESNEL_POWER); materialSpecularColor.rgb = mix(materialSpecularColor.rgb, vec3(1.0), clamp(fresnelFactor, 0.0, 1.0)); } vec4 specularTemp = vec4(vec3(0.0), diffuseColor.a); specularTemp.rgb = lightSpecularColor.rgb * pow(specularIntensity, specularMap.g * MAX_SHININESS); specularTemp.rgb *= materialSpecularColor.rgb; specularTemp.rgb *= (1 - isParticle.x); specularTemp.rgb = clamp(specularTemp.rgb, 0.0, 1.0); float unitLightDirectionDelta = dot ( normalize(p3d_LightSource[i].spotDirection) , -unitLightDirection ); if (unitLightDirectionDelta < p3d_LightSource[i].spotCosCutoff) { continue; } float spotExponent = p3d_LightSource[i].spotExponent; diffuseTemp.rgb *= (spotExponent <= 0.0 ? 1.0 : pow(unitLightDirectionDelta, spotExponent)); vec2 shadowMapSize = textureSize(p3d_LightSource[i].shadowMap, 0); float inShadow = 0.0; float count = 0.0; for ( int si = -shadowSamples; si <= shadowSamples; ++si) { for (int sj = -shadowSamples; sj <= shadowSamples; ++sj) { inShadow += ( 1.0 - textureProj ( p3d_LightSource[i].shadowMap , vertexInShadowSpaces[i] + vec4(vec2(si, sj) / shadowMapSize, vec2(0.0)) ) ); count += 1.0; } } inShadow /= count; vec3 shadow = mix ( vec3(1.0) , shadowColor , inShadow ); diffuseTemp.rgb *= mix(shadow, vec3(1.0), isParticle.x); specularTemp.rgb *= mix(shadow, vec3(1.0), isParticle.x); diffuseTemp.rgb *= attenuation; specularTemp.rgb *= attenuation; diffuse.rgb += diffuseTemp.rgb; specular.rgb += specularTemp.rgb; } vec4 rimLight = vec4(vec3(0.0), diffuseColor.a); if (rimLightEnabled.x == 1) { rimLight.rgb = vec3 ( 1.0 - max ( 0.0 , dot(normalize(-vertexPosition.xyz), normalize(normal)) ) ); rimLight.rgb = ( celShadingEnabled.x == 1 ? smoothstep(0.3, 0.4, rimLight.rgb) : pow(rimLight.rgb, vec3(2.0)) * 1.2 ); rimLight.rgb *= diffuse.rgb; } vec2 ssaoBlurTexSize = textureSize(ssaoBlurTexture, 0).xy; vec2 ssaoBlurTexCoord = gl_FragCoord.xy / ssaoBlurTexSize; vec3 ssao = texture(ssaoBlurTexture, ssaoBlurTexCoord).rgb; ssao = mix(shadowColor, vec3(1.0), clamp(ssao.r, 0.0, 1.0)); float sunPosition = sin(sunPosition.x * pi.y); float sunMixFactor = 1.0 - (sunPosition / 2.0 + 0.5); vec3 ambientCool = pow(vec3(0.302, 0.451, 0.471), vec3(gamma.x)) * max(0.5, sunMixFactor); vec3 ambientWarm = pow(vec3(0.765, 0.573, 0.400), vec3(gamma.x)) * max(0.5, sunMixFactor); vec3 skyLight = mix(ambientCool, ambientWarm, sunMixFactor); vec3 groundLight = mix(ambientWarm, ambientCool, sunMixFactor); vec3 worldNormal = normalize((trans_view_to_world * vec4(normal, 0.0)).xyz); vec3 ambientLight = mix ( groundLight , skyLight , 0.5 * (1.0 + dot(worldNormal, vec3(0, 0, 1))) ); vec3 ambient = ambientLight.rgb * diffuseColor.rgb * ssao; vec3 emission = p3d_Material.emission.rgb * max(0.1, pow(sunPosition, 0.4)); out0.a = diffuseColor.a; out0.rgb = ambient.rgb + diffuse.rgb + rimLight.rgb + emission.rgb; if (isWater.x == 1) { out0.a = 0.0; } out1.a = diffuseColor.a; out1.rgb = specular.rgb; if (isParticle.x == 1) { out1.rgb = vec3(0.0); } }
3d-game-shaders-for-beginners/demonstration/shaders/fragment/base.frag/0
{ "file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/base.frag", "repo_id": "3d-game-shaders-for-beginners", "token_count": 4179 }
0
/* (C) 2020 David Lettier lettier.com */ #version 150 uniform vec2 pi; uniform vec2 gamma; uniform sampler2D colorTexture; uniform sampler2D lookupTableTexture0; uniform sampler2D lookupTableTexture1; uniform vec2 sunPosition; uniform vec2 enabled; out vec4 fragColor; void main() { vec2 texSize = textureSize(colorTexture, 0).xy; vec4 color = texture(colorTexture, gl_FragCoord.xy / texSize); if (enabled.x != 1) { fragColor = color; return; } color.rgb = pow(color.rgb, vec3(gamma.y)); float u = floor(color.b * 15.0) / 15.0 * 240.0; u = (floor(color.r * 15.0) / 15.0 * 15.0) + u; u /= 255.0; float v = 1.0 - (floor(color.g * 15.0) / 15.0); vec3 left0 = texture(lookupTableTexture0, vec2(u, v)).rgb; vec3 left1 = texture(lookupTableTexture1, vec2(u, v)).rgb; u = ceil(color.b * 15.0) / 15.0 * 240.0; u = (ceil(color.r * 15.0) / 15.0 * 15.0) + u; u /= 255.0; v = 1.0 - (ceil(color.g * 15.0) / 15.0); vec3 right0 = texture(lookupTableTexture0, vec2(u, v)).rgb; vec3 right1 = texture(lookupTableTexture1, vec2(u, v)).rgb; float sunPosition = sin(sunPosition.x * pi.y); sunPosition = 0.5 * (sunPosition + 1); vec3 left = mix(left0, left1, sunPosition); vec3 right = mix(right0, right1, sunPosition); color.r = mix(left.r, right.r, fract(color.r * 15.0)); color.g = mix(left.g, right.g, fract(color.g * 15.0)); color.b = mix(left.b, right.b, fract(color.b * 15.0)); color.rgb = pow(color.rgb, vec3(gamma.x)); fragColor = color; }
3d-game-shaders-for-beginners/demonstration/shaders/fragment/lookup-table.frag/0
{ "file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/lookup-table.frag", "repo_id": "3d-game-shaders-for-beginners", "token_count": 662 }
1
/* (C) 2019 David Lettier lettier.com */ #version 150 uniform sampler2D colorTexture; uniform vec2 enabled; out vec4 fragColor; void main() { float amount = 0.3; vec2 texSize = textureSize(colorTexture, 0).xy; vec2 fragCoord = gl_FragCoord.xy; vec2 texCoord = fragCoord / texSize; if (enabled.x != 1) { fragColor = texture(colorTexture, texCoord); return; } float neighbor = amount * -1.0; float center = amount * 4.0 + 1.0; vec3 color = texture(colorTexture, (fragCoord + vec2( 0, 1)) / texSize).rgb * neighbor + texture(colorTexture, (fragCoord + vec2(-1, 0)) / texSize).rgb * neighbor + texture(colorTexture, (fragCoord + vec2( 0, 0)) / texSize).rgb * center + texture(colorTexture, (fragCoord + vec2( 1, 0)) / texSize).rgb * neighbor + texture(colorTexture, (fragCoord + vec2( 0, -1)) / texSize).rgb * neighbor ; fragColor = vec4(color, texture(colorTexture, texCoord).a); }
3d-game-shaders-for-beginners/demonstration/shaders/fragment/sharpen.frag/0
{ "file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/sharpen.frag", "repo_id": "3d-game-shaders-for-beginners", "token_count": 411 }
2
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang=""> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" /> <meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:title" content="Chromatic Aberration | 3D Game Shaders For Beginners" /> <meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:title" content="Chromatic Aberration | 3D Game Shaders For Beginners" /> <meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:card" content="summary_large_image" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <meta name="author" content="David Lettier" /> <title>Chromatic Aberration | 3D Game Shaders For Beginners</title> <style> code{white-space: pre-wrap;} span.smallcaps{font-variant: small-caps;} span.underline{text-decoration: underline;} div.column{display: inline-block; vertical-align: top; width: 50%;} </style> <style> code.sourceCode > span { display: inline-block; line-height: 1.25; } code.sourceCode > span { color: inherit; text-decoration: inherit; } code.sourceCode > span:empty { height: 1.2em; } .sourceCode { overflow: visible; } code.sourceCode { white-space: pre; position: relative; } div.sourceCode { margin: 1em 0; } pre.sourceCode { margin: 0; } @media screen { div.sourceCode { overflow: auto; } } @media print { code.sourceCode { white-space: pre-wrap; } code.sourceCode > span { text-indent: -5em; padding-left: 5em; } } pre.numberSource code { counter-reset: source-line 0; } pre.numberSource code > span { position: relative; left: -4em; counter-increment: source-line; } pre.numberSource code > span > a:first-child::before { content: counter(source-line); position: relative; left: -1em; text-align: right; vertical-align: baseline; border: none; display: inline-block; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; padding: 0 4px; width: 4em; background-color: #232629; color: #7a7c7d; } pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; } div.sourceCode { color: #cfcfc2; background-color: #232629; } @media screen { code.sourceCode > span > a:first-child::before { text-decoration: underline; } } code span. { color: #cfcfc2; } /* Normal */ code span.al { color: #95da4c; } /* Alert */ code span.an { color: #3f8058; } /* Annotation */ code span.at { color: #2980b9; } /* Attribute */ code span.bn { color: #f67400; } /* BaseN */ code span.bu { color: #7f8c8d; } /* BuiltIn */ code span.cf { color: #fdbc4b; } /* ControlFlow */ code span.ch { color: #3daee9; } /* Char */ code span.cn { color: #27aeae; } /* Constant */ code span.co { color: #7a7c7d; } /* Comment */ code span.cv { color: #7f8c8d; } /* CommentVar */ code span.do { color: #a43340; } /* Documentation */ code span.dt { color: #2980b9; } /* DataType */ code span.dv { color: #f67400; } /* DecVal */ code span.er { color: #da4453; } /* Error */ code span.ex { color: #0099ff; } /* Extension */ code span.fl { color: #f67400; } /* Float */ code span.fu { color: #8e44ad; } /* Function */ code span.im { color: #27ae60; } /* Import */ code span.in { color: #c45b00; } /* Information */ code span.kw { color: #cfcfc2; } /* Keyword */ code span.op { color: #cfcfc2; } /* Operator */ code span.ot { color: #27ae60; } /* Other */ code span.pp { color: #27ae60; } /* Preprocessor */ code span.re { color: #2980b9; } /* RegionMarker */ code span.sc { color: #3daee9; } /* SpecialChar */ code span.ss { color: #da4453; } /* SpecialString */ code span.st { color: #f44f4f; } /* String */ code span.va { color: #27aeae; } /* Variable */ code span.vs { color: #da4453; } /* VerbatimString */ code span.wa { color: #da4453; } /* Warning */ </style> <!--[if lt IE 9]> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script> <![endif]--> <link rel="stylesheet" href="style.css" /> </head> <body> <p><a href="motion-blur.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="screen-space-reflection.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> <h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1> <h2 id="chromatic-aberration">Chromatic Aberration</h2> <p align="center"> <img src="https://i.imgur.com/bawgERm.gif" alt="Chromatic Aberration" title="Chromatic Aberration"> </p> <p>Chromatic aberration is a screen space technique that simulates lens distortion. Use it to give your scene a cinematic, lo-fi analog feel or to emphasize a chaotic event.</p> <h3 id="texture">Texture</h3> <div class="sourceCode" id="cb1"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb1-1"><a href="#cb1-1"></a>uniform sampler2D colorTexture;</span> <span id="cb1-2"><a href="#cb1-2"></a></span> <span id="cb1-3"><a href="#cb1-3"></a><span class="co">// ...</span></span></code></pre></div> <p>The input texture needed is the scene's colors captured into a framebuffer texture.</p> <h3 id="parameters">Parameters</h3> <p align="center"> <img src="https://i.imgur.com/fNpMaPL.gif" alt="Chromatic Aberration" title="Chromatic Aberration"> </p> <div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1"></a> <span class="co">// ...</span></span> <span id="cb2-2"><a href="#cb2-2"></a></span> <span id="cb2-3"><a href="#cb2-3"></a> <span class="dt">float</span> redOffset = <span class="fl">0.009</span>;</span> <span id="cb2-4"><a href="#cb2-4"></a> <span class="dt">float</span> greenOffset = <span class="fl">0.006</span>;</span> <span id="cb2-5"><a href="#cb2-5"></a> <span class="dt">float</span> blueOffset = -<span class="fl">0.006</span>;</span> <span id="cb2-6"><a href="#cb2-6"></a></span> <span id="cb2-7"><a href="#cb2-7"></a> <span class="co">// ...</span></span></code></pre></div> <p>The adjustable parameters for this technique are the red, green, and blue offsets. Feel free to play around with these to get the particular color fringe you're looking for. These particular offsets produce a yellowish orange and blue fringe.</p> <h3 id="direction">Direction</h3> <div class="sourceCode" id="cb3"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb3-1"><a href="#cb3-1"></a><span class="co">// ...</span></span> <span id="cb3-2"><a href="#cb3-2"></a></span> <span id="cb3-3"><a href="#cb3-3"></a>uniform vec2 mouseFocusPoint;</span> <span id="cb3-4"><a href="#cb3-4"></a></span> <span id="cb3-5"><a href="#cb3-5"></a> <span class="co">// ...</span></span> <span id="cb3-6"><a href="#cb3-6"></a></span> <span id="cb3-7"><a href="#cb3-7"></a> vec2 texSize = textureSize(colorTexture, <span class="dv">0</span>).xy;</span> <span id="cb3-8"><a href="#cb3-8"></a> vec2 texCoord = gl_FragCoord.xy / texSize;</span> <span id="cb3-9"><a href="#cb3-9"></a></span> <span id="cb3-10"><a href="#cb3-10"></a> vec2 direction = texCoord - mouseFocusPoint;</span> <span id="cb3-11"><a href="#cb3-11"></a></span> <span id="cb3-12"><a href="#cb3-12"></a> <span class="co">// ...</span></span></code></pre></div> <p>The offsets can occur horizontally, vertically, or radially. One approach is to radiate out from the <a href="depth-of-field.html">depth of field</a> focal point. As the scene gets more out of focus, the chromatic aberration increases.</p> <h3 id="samples">Samples</h3> <div class="sourceCode" id="cb4"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb4-1"><a href="#cb4-1"></a><span class="co">// ...</span></span> <span id="cb4-2"><a href="#cb4-2"></a></span> <span id="cb4-3"><a href="#cb4-3"></a>out vec4 fragColor;</span> <span id="cb4-4"><a href="#cb4-4"></a></span> <span id="cb4-5"><a href="#cb4-5"></a> <span class="co">// ...</span></span> <span id="cb4-6"><a href="#cb4-6"></a></span> <span id="cb4-7"><a href="#cb4-7"></a> fragColor.r = texture(colorTexture, texCoord + (direction * vec2(redOffset ))).r;</span> <span id="cb4-8"><a href="#cb4-8"></a> fragColor.g = texture(colorTexture, texCoord + (direction * vec2(greenOffset))).g;</span> <span id="cb4-9"><a href="#cb4-9"></a> fragColor.ba = texture(colorTexture, texCoord + (direction * vec2(blueOffset ))).ba;</span> <span id="cb4-10"><a href="#cb4-10"></a>}</span></code></pre></div> <p>With the direction and offsets, make three samples of the scene's colors—one for the red, green, and blue channels. These will be the final fragment color.</p> <h3 id="source">Source</h3> <ul> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/src/main.cxx" target="_blank" rel="noopener noreferrer">main.cxx</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/vertex/basic.vert" target="_blank" rel="noopener noreferrer">basic.vert</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/chromatic-aberration.frag" target="_blank" rel="noopener noreferrer">chromatic-aberration.frag</a></li> </ul> <h2 id="copyright">Copyright</h2> <p>(C) 2021 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p> <p><a href="motion-blur.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="screen-space-reflection.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> </body> </html>
3d-game-shaders-for-beginners/docs/chromatic-aberration.html/0
{ "file_path": "3d-game-shaders-for-beginners/docs/chromatic-aberration.html", "repo_id": "3d-game-shaders-for-beginners", "token_count": 4400 }
3
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang=""> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" /> <meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:title" content="Normal Mapping | 3D Game Shaders For Beginners" /> <meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:title" content="Normal Mapping | 3D Game Shaders For Beginners" /> <meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:card" content="summary_large_image" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <meta name="author" content="David Lettier" /> <title>Normal Mapping | 3D Game Shaders For Beginners</title> <style> code{white-space: pre-wrap;} span.smallcaps{font-variant: small-caps;} span.underline{text-decoration: underline;} div.column{display: inline-block; vertical-align: top; width: 50%;} </style> <style> code.sourceCode > span { display: inline-block; line-height: 1.25; } code.sourceCode > span { color: inherit; text-decoration: inherit; } code.sourceCode > span:empty { height: 1.2em; } .sourceCode { overflow: visible; } code.sourceCode { white-space: pre; position: relative; } div.sourceCode { margin: 1em 0; } pre.sourceCode { margin: 0; } @media screen { div.sourceCode { overflow: auto; } } @media print { code.sourceCode { white-space: pre-wrap; } code.sourceCode > span { text-indent: -5em; padding-left: 5em; } } pre.numberSource code { counter-reset: source-line 0; } pre.numberSource code > span { position: relative; left: -4em; counter-increment: source-line; } pre.numberSource code > span > a:first-child::before { content: counter(source-line); position: relative; left: -1em; text-align: right; vertical-align: baseline; border: none; display: inline-block; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; padding: 0 4px; width: 4em; background-color: #232629; color: #7a7c7d; } pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; } div.sourceCode { color: #cfcfc2; background-color: #232629; } @media screen { code.sourceCode > span > a:first-child::before { text-decoration: underline; } } code span. { color: #cfcfc2; } /* Normal */ code span.al { color: #95da4c; } /* Alert */ code span.an { color: #3f8058; } /* Annotation */ code span.at { color: #2980b9; } /* Attribute */ code span.bn { color: #f67400; } /* BaseN */ code span.bu { color: #7f8c8d; } /* BuiltIn */ code span.cf { color: #fdbc4b; } /* ControlFlow */ code span.ch { color: #3daee9; } /* Char */ code span.cn { color: #27aeae; } /* Constant */ code span.co { color: #7a7c7d; } /* Comment */ code span.cv { color: #7f8c8d; } /* CommentVar */ code span.do { color: #a43340; } /* Documentation */ code span.dt { color: #2980b9; } /* DataType */ code span.dv { color: #f67400; } /* DecVal */ code span.er { color: #da4453; } /* Error */ code span.ex { color: #0099ff; } /* Extension */ code span.fl { color: #f67400; } /* Float */ code span.fu { color: #8e44ad; } /* Function */ code span.im { color: #27ae60; } /* Import */ code span.in { color: #c45b00; } /* Information */ code span.kw { color: #cfcfc2; } /* Keyword */ code span.op { color: #cfcfc2; } /* Operator */ code span.ot { color: #27ae60; } /* Other */ code span.pp { color: #27ae60; } /* Preprocessor */ code span.re { color: #2980b9; } /* RegionMarker */ code span.sc { color: #3daee9; } /* SpecialChar */ code span.ss { color: #da4453; } /* SpecialString */ code span.st { color: #f44f4f; } /* String */ code span.va { color: #27aeae; } /* Variable */ code span.vs { color: #da4453; } /* VerbatimString */ code span.wa { color: #da4453; } /* Warning */ </style> <!--[if lt IE 9]> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script> <![endif]--> <link rel="stylesheet" href="style.css" /> </head> <body> <p><a href="cel-shading.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="deferred-rendering.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> <h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1> <h2 id="normal-mapping">Normal Mapping</h2> <p align="center"> <img src="https://i.imgur.com/M4eHo9I.gif" alt="Normal Mapping" title="Normal Mapping"> </p> <p>Normal mapping allows you to add surface details without adding any geometry. Typically, in a modeling program like Blender, you create a high poly and a low poly version of your mesh. You take the vertex normals from the high poly mesh and bake them into a texture. This texture is the normal map. Then inside the fragment shader, you replace the low poly mesh's vertex normals with the high poly mesh's normals you baked into the normal map. Now when you light your mesh, it will appear to have more polygons than it really has. This will keep your FPS high while at the same time retain most of the details from the high poly version.</p> <p align="center"> <img src="https://i.imgur.com/nSY9AW4.gif" alt="From high to low poly with normal mapping." title="From high to low poly with normal mapping."> </p> <p>Here you see the progression from the high poly model to the low poly model to the low poly model with the normal map applied.</p> <p align="center"> <img src="https://i.imgur.com/jvkRPE7.gif" alt="Normal Map Illusion" title="Normal Map Illusion"> </p> <p>Keep in mind though, normal mapping is only an illusion. After a certain angle, the surface will look flat again.</p> <h3 id="vertex">Vertex</h3> <div class="sourceCode" id="cb1"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb1-1"><a href="#cb1-1"></a><span class="co">// ...</span></span> <span id="cb1-2"><a href="#cb1-2"></a></span> <span id="cb1-3"><a href="#cb1-3"></a>uniform mat3 p3d_NormalMatrix;</span> <span id="cb1-4"><a href="#cb1-4"></a></span> <span id="cb1-5"><a href="#cb1-5"></a><span class="co">// ...</span></span> <span id="cb1-6"><a href="#cb1-6"></a></span> <span id="cb1-7"><a href="#cb1-7"></a>in vec3 p3d_Normal;</span> <span id="cb1-8"><a href="#cb1-8"></a></span> <span id="cb1-9"><a href="#cb1-9"></a><span class="co">// ...</span></span> <span id="cb1-10"><a href="#cb1-10"></a></span> <span id="cb1-11"><a href="#cb1-11"></a>in vec3 p3d_Binormal;</span> <span id="cb1-12"><a href="#cb1-12"></a>in vec3 p3d_Tangent;</span> <span id="cb1-13"><a href="#cb1-13"></a></span> <span id="cb1-14"><a href="#cb1-14"></a> <span class="co">// ...</span></span> <span id="cb1-15"><a href="#cb1-15"></a></span> <span id="cb1-16"><a href="#cb1-16"></a> vertexNormal = normalize(p3d_NormalMatrix * p3d_Normal);</span> <span id="cb1-17"><a href="#cb1-17"></a> binormal = normalize(p3d_NormalMatrix * p3d_Binormal);</span> <span id="cb1-18"><a href="#cb1-18"></a> tangent = normalize(p3d_NormalMatrix * p3d_Tangent);</span> <span id="cb1-19"><a href="#cb1-19"></a></span> <span id="cb1-20"><a href="#cb1-20"></a> <span class="co">// ...</span></span></code></pre></div> <p>Starting in the vertex shader, you'll need to output to the fragment shader the normal vector, binormal vector, and the tangent vector. These vectors are used, in the fragment shader, to transform the normal map normal from tangent space to view space.</p> <p><code>p3d_NormalMatrix</code> transforms the vertex normal, binormal, and tangent vectors to view space. Remember that in view space, all of the coordinates are relative to the camera's position.</p> <blockquote> [p3d_NormalMatrix] is the upper 3x3 of the inverse transpose of the ModelViewMatrix. It is used to transform the normal vector into view-space coordinates. <br> <br> <footer> <a href="http://www.panda3d.org/manual/?title=List_of_GLSL_Shader_Inputs">Source</a> </footer> </blockquote> <div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1"></a><span class="co">// ...</span></span> <span id="cb2-2"><a href="#cb2-2"></a></span> <span id="cb2-3"><a href="#cb2-3"></a>in vec2 p3d_MultiTexCoord0;</span> <span id="cb2-4"><a href="#cb2-4"></a></span> <span id="cb2-5"><a href="#cb2-5"></a><span class="co">// ...</span></span> <span id="cb2-6"><a href="#cb2-6"></a></span> <span id="cb2-7"><a href="#cb2-7"></a>out vec2 normalCoord;</span> <span id="cb2-8"><a href="#cb2-8"></a></span> <span id="cb2-9"><a href="#cb2-9"></a> <span class="co">// ...</span></span> <span id="cb2-10"><a href="#cb2-10"></a></span> <span id="cb2-11"><a href="#cb2-11"></a> normalCoord = p3d_MultiTexCoord0;</span> <span id="cb2-12"><a href="#cb2-12"></a></span> <span id="cb2-13"><a href="#cb2-13"></a> <span class="co">// ...</span></span></code></pre></div> <p align="center"> <img src="https://i.imgur.com/tLIA6Hu.gif" alt="Normal Maps" title="Normal Maps"> </p> <p>You'll also need to output, to the fragment shader, the UV coordinates for the normal map.</p> <h3 id="fragment">Fragment</h3> <p>Recall that the vertex normal was used to calculate the lighting. However, the normal map provides us with different normals to use when calculating the lighting. In the fragment shader, you need to swap out the vertex normals for the normals found in the normal map.</p> <div class="sourceCode" id="cb3"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb3-1"><a href="#cb3-1"></a><span class="co">// ...</span></span> <span id="cb3-2"><a href="#cb3-2"></a></span> <span id="cb3-3"><a href="#cb3-3"></a>uniform sampler2D p3d_Texture1;</span> <span id="cb3-4"><a href="#cb3-4"></a></span> <span id="cb3-5"><a href="#cb3-5"></a><span class="co">// ...</span></span> <span id="cb3-6"><a href="#cb3-6"></a></span> <span id="cb3-7"><a href="#cb3-7"></a>in vec2 normalCoord;</span> <span id="cb3-8"><a href="#cb3-8"></a></span> <span id="cb3-9"><a href="#cb3-9"></a> <span class="co">// ...</span></span> <span id="cb3-10"><a href="#cb3-10"></a></span> <span id="cb3-11"><a href="#cb3-11"></a> <span class="co">/* Find */</span></span> <span id="cb3-12"><a href="#cb3-12"></a> vec4 normalTex = texture(p3d_Texture1, normalCoord);</span> <span id="cb3-13"><a href="#cb3-13"></a></span> <span id="cb3-14"><a href="#cb3-14"></a> <span class="co">// ...</span></span></code></pre></div> <p>Using the normal map coordinates the vertex shader sent, pull out the normal from the normal map.</p> <div class="sourceCode" id="cb4"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb4-1"><a href="#cb4-1"></a> <span class="co">// ...</span></span> <span id="cb4-2"><a href="#cb4-2"></a></span> <span id="cb4-3"><a href="#cb4-3"></a> vec3 normal;</span> <span id="cb4-4"><a href="#cb4-4"></a></span> <span id="cb4-5"><a href="#cb4-5"></a> <span class="co">// ...</span></span> <span id="cb4-6"><a href="#cb4-6"></a></span> <span id="cb4-7"><a href="#cb4-7"></a> <span class="co">/* Unpack */</span></span> <span id="cb4-8"><a href="#cb4-8"></a> normal =</span> <span id="cb4-9"><a href="#cb4-9"></a> normalize</span> <span id="cb4-10"><a href="#cb4-10"></a> ( normalTex.rgb</span> <span id="cb4-11"><a href="#cb4-11"></a> * <span class="fl">2.0</span></span> <span id="cb4-12"><a href="#cb4-12"></a> - <span class="fl">1.0</span></span> <span id="cb4-13"><a href="#cb4-13"></a> );</span> <span id="cb4-14"><a href="#cb4-14"></a></span> <span id="cb4-15"><a href="#cb4-15"></a> <span class="co">// ...</span></span></code></pre></div> <p>Earlier I showed how the normals are mapped to colors to create the normal map. Now this process needs to be reversed so you can get back the original normals that were baked into the map.</p> <div class="sourceCode" id="cb5"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb5-1"><a href="#cb5-1"></a>(r, g, b) =</span> <span id="cb5-2"><a href="#cb5-2"></a> ( r * <span class="dv">2</span> - <span class="dv">1</span></span> <span id="cb5-3"><a href="#cb5-3"></a> , g * <span class="dv">2</span> - <span class="dv">1</span></span> <span id="cb5-4"><a href="#cb5-4"></a> , b * <span class="dv">2</span> - <span class="dv">1</span></span> <span id="cb5-5"><a href="#cb5-5"></a> ) =</span> <span id="cb5-6"><a href="#cb5-6"></a> (x, y, z)</span></code></pre></div> <p>Here's the process for unpacking the normals from the normal map.</p> <div class="sourceCode" id="cb6"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb6-1"><a href="#cb6-1"></a> <span class="co">// ...</span></span> <span id="cb6-2"><a href="#cb6-2"></a></span> <span id="cb6-3"><a href="#cb6-3"></a> <span class="co">/* Transform */</span></span> <span id="cb6-4"><a href="#cb6-4"></a> normal =</span> <span id="cb6-5"><a href="#cb6-5"></a> normalize</span> <span id="cb6-6"><a href="#cb6-6"></a> ( mat3</span> <span id="cb6-7"><a href="#cb6-7"></a> ( tangent</span> <span id="cb6-8"><a href="#cb6-8"></a> , binormal</span> <span id="cb6-9"><a href="#cb6-9"></a> , vertexNormal</span> <span id="cb6-10"><a href="#cb6-10"></a> )</span> <span id="cb6-11"><a href="#cb6-11"></a> * normal</span> <span id="cb6-12"><a href="#cb6-12"></a> );</span> <span id="cb6-13"><a href="#cb6-13"></a></span> <span id="cb6-14"><a href="#cb6-14"></a> <span class="co">// ...</span></span></code></pre></div> <p>The normals you get back from the normal map are typically in tangent space. They could be in another space, however. For example, Blender allows you to bake the normals in tangent, object, world, or camera space.</p> <p align="center"> <img src="https://i.imgur.com/EzHJPd4.gif" alt="Replacing the vertex normals with the normal map normals." title="Replacing the vertex normals with the normal map normals."> </p> <p>To take the normal map normal from tangent space to view pace, construct a three by three matrix using the tangent, binormal, and vertex normal vectors. Multiply the normal by this matrix and be sure to normalize it.</p> <p>At this point, you're done. The rest of the lighting calculations are the same.</p> <h3 id="source">Source</h3> <ul> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/src/main.cxx" target="_blank" rel="noopener noreferrer">main.cxx</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/vertex/base.vert" target="_blank" rel="noopener noreferrer">base.vert</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/base.frag" target="_blank" rel="noopener noreferrer">base.frag</a></li> </ul> <h2 id="copyright">Copyright</h2> <p>(C) 2019 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p> <p><a href="cel-shading.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="deferred-rendering.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> </body> </html>
3d-game-shaders-for-beginners/docs/normal-mapping.html/0
{ "file_path": "3d-game-shaders-for-beginners/docs/normal-mapping.html", "repo_id": "3d-game-shaders-for-beginners", "token_count": 6581 }
4
[:arrow_backward:](blur.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](ssao.md) # 3D Game Shaders For Beginners ## Bloom <p align="center"> <img src="https://i.imgur.com/UxKRz2r.gif" alt="Bloom" title="Bloom"> </p> Adding bloom to a scene can really sell the illusion of the lighting model. Light emitting objects are more believable and specular highlights get an extra dose of shimmer. ```c //... int size = 5; float separation = 3; float threshold = 0.4; float amount = 1; // ... ``` These parameters control the look and feel. `size` determines how blurred the effect is. `separation` spreads out the blur. `threshold` controls which fragments are illuminated. And the last parameter, `amount`, controls how much bloom is outputted. ```c // ... vec2 texSize = textureSize(colorTexture, 0).xy; float value = 0.0; float count = 0.0; vec4 result = vec4(0); vec4 color = vec4(0); for (int i = -size; i <= size; ++i) { for (int j = -size; j <= size; ++j) { // ... } } // ... ``` The technique starts by looping through a kernel/matrix/window centered over the current fragment. This is similar to the window used for [outlining](outlining.md). The size of the window is `size * 2 + 1` by `size * 2 + 1`. So for example, with a `size` setting of two, the window uses `(2 * 2 + 1)^2 = 25` samples per fragment. ```c // ... color = texture ( colorTexture , ( gl_FragCoord.xy + (vec2(i, j) * separation) ) / texSize ); value = max(color.r, max(color.g, color.b)); if (value < threshold) { color = vec4(0); } result += color; count += 1.0; // ... ``` For each iteration, it retrieves the color from the input texture and turns the red, green, and blue values into a greyscale value. If this greyscale value is less than the threshold, it discards this color by making it solid black. After evaluating the sample's greyscale value, it adds its RGB values to `result`. ```c // ... result /= count; fragColor = mix(vec4(0), result, amount); // ... ``` After it's done summing up the samples, it divides the sum of the color samples by the number of samples taken. The result is the average color of itself and its neighbors. By doing this for every fragment, you end up with a blurred image. This form of blurring is known as a [box blur](blur.md#box-blur). <p align="center"> <img src="https://i.imgur.com/m4yedrM.gif" alt="Bloom progresssion." title="Bloom progresssion."> </p> Here you see the progression of the bloom algorithm. ### Source - [main.cxx](../demonstration/src/main.cxx) - [basic.vert](../demonstration/shaders/vertex/basic.vert) - [bloom.frag](../demonstration/shaders/fragment/outline.frag) ## Copyright (C) 2019 David Lettier <br> [lettier.com](https://www.lettier.com) [:arrow_backward:](blur.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](ssao.md)
3d-game-shaders-for-beginners/sections/bloom.md/0
{ "file_path": "3d-game-shaders-for-beginners/sections/bloom.md", "repo_id": "3d-game-shaders-for-beginners", "token_count": 1145 }
5
[:arrow_backward:](film-grain.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](gamma-correction.md) # 3D Game Shaders For Beginners ## Lookup Table (LUT) <p align="center"> <img src="https://i.imgur.com/WrPzVlW.gif" alt="LUT" title="LUT"> </p> The lookup table or LUT shader allows you to transform the colors of your game using an image editor like the [GIMP](https://www.gimp.org/). From color grading to turning day into night, the LUT shader is a handy tool for tweaking the look of your game. <p align="center"> <img src="https://i.imgur.com/NPdJNGj.png" alt="Neutral LUT" title="Neutral LUT"> </p> Before you can get started, you'll need to find a neutral LUT image. Neutral meaning that it leaves the fragment colors unchanged. The LUT needs to be 256 pixels wide by 16 pixels tall and contain 16 blocks with each block being 16 by 16 pixels. The LUT is mapped out into 16 blocks. Each block has a different level of blue. As you move across the blocks, from left to right, the amount of blue increases. You can see the amount of blue in each block's upper-left corner. Within each block, the amount of red increases as you move from left to right and the amount of green increases as you move from top to bottom. The upper-left corner of the first block is black since every RGB channel is zero. The lower-right corner of the last block is white since every RGB channel is one. <p align="center"> <img src="https://i.imgur.com/KyxPm1r.png" alt="LUT And Screenshot" title="LUT And Screenshot"> </p> With the neutral LUT in hand, take a screenshot of your game and open it in your image editor. Add the neutral LUT as a new layer and merge it with the screenshot. As you manipulate the colors of the screenshot, the LUT will be altered in the same way. When you're done editing, select only the LUT and save it as a new image. You now have your new lookup table and can begin writing your shader. ```c // ... vec2 texSize = textureSize(colorTexture, 0).xy; vec4 color = texture(colorTexture, gl_FragCoord.xy / texSize); // ... ``` The LUT shader is a screen space technique. Therefore, sample the scene's color at the current fragment or screen position. ```c // ... float u = floor(color.b * 15.0) / 15.0 * 240.0; u = (floor(color.r * 15.0) / 15.0 * 15.0) + u; u /= 255.0; float v = ceil(color.g * 15.0); v /= 15.0; v = 1.0 - v; // ... ``` In order to transform the current fragment's color, using the LUT, you'll need to map the color to two UV coordinates on the lookup table texture. The first mapping (shown up above) is to the nearest left or lower bound block location and the second mapping (shown below) is to the nearest right or upper bound block mapping. At the end, you'll combine these two mappings to create the final color transformation. <p align="center"> <img src="https://i.imgur.com/j2JmyQ2.png" alt="RGB Channel Mapping" title="RGB Channel Mapping"> </p> Each of the red, green, and blue channels maps to one of 16 possibilities in the LUT. The blue channel maps to one of the 16 upper-left block corners. After the blue channel maps to a block, the red channel maps to one of the 16 horizontal pixel positions within the block and the green channel maps to one of the 16 vertical pixel positions within the block. These three mappings will determine the UV coordinate you'll need to sample a color from the LUT. ```c // ... u /= 255.0; v /= 15.0; v = 1.0 - v; // ... ``` To calculate the final U coordinate, divide it by 255 since the LUT is 256 pixels wide and U ranges from zero to one. To calculate the final V coordinate, divide it by 15 since the LUT is 16 pixels tall and V ranges from zero to one. You'll also need to subtract the normalized V coordinate from one since V ranges from zero at the bottom to one at the top while the green channel ranges from zero at the top to 15 at the bottom. ```c // ... vec3 left = texture(lookupTableTexture, vec2(u, v)).rgb; // ... ``` Using the UV coordinates, sample a color from the lookup table. This is the nearest left block color. ```c // ... u = ceil(color.b * 15.0) / 15.0 * 240.0; u = (ceil(color.r * 15.0) / 15.0 * 15.0) + u; u /= 255.0; v = 1.0 - (ceil(color.g * 15.0) / 15.0); vec3 right = texture(lookupTableTexture, vec2(u, v)).rgb; // ... ``` Now you'll need to calculate the UV coordinates for the nearest right block color. Notice how `ceil` or ceiling is being used now instead of `floor`. <p align="center"> <img src="https://i.imgur.com/uciq7Um.png" alt="Mixing" title="Mixing"> </p> ```c // ... color.r = mix(left.r, right.r, fract(color.r * 15.0)); color.g = mix(left.g, right.g, fract(color.g * 15.0)); color.b = mix(left.b, right.b, fract(color.b * 15.0)); // ... ``` Not every channel will map perfectly to one of its 16 possibilities. For example, `0.5` doesn't map perfectly. At the lower bound (`floor`), it maps to `0.4666666666666667` and at the upper bound (`ceil`), it maps to `0.5333333333333333`. Compare that with `0.4` which maps to `0.4` at the lower bound and `0.4` at the upper bound. For those channels which do not map perfectly, you'll need to mix the left and right sides based on where the channel falls between its lower and upper bound. For `0.5`, it falls directly between them making the final color a mixture of half left and half right. However, for `0.132` the mixture will be 98% right and 2% left since the fractional part of `0.123` times `15.0` is `0.98`. ```c // ... fragColor = color; // ... ``` Set the fragment color to the final mix and you're done. ### Source - [main.cxx](../demonstration/src/main.cxx) - [basic.vert](../demonstration/shaders/vertex/basic.vert) - [lookup-table.frag](../demonstration/shaders/fragment/lookup-table.frag) ## Copyright (C) 2020 David Lettier <br> [lettier.com](https://www.lettier.com) [:arrow_backward:](film-grain.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](gamma-correction.md)
3d-game-shaders-for-beginners/sections/lookup-table.md/0
{ "file_path": "3d-game-shaders-for-beginners/sections/lookup-table.md", "repo_id": "3d-game-shaders-for-beginners", "token_count": 2018 }
6
--- # clang-format documentation # http://clang.llvm.org/docs/ClangFormat.html # http://clang.llvm.org/docs/ClangFormatStyleOptions.html # Preexisting formats: # LLVM # Google # Chromium # Mozilla # WebKit Language: Cpp BasedOnStyle: Mozilla AccessModifierOffset: -4 AlignAfterOpenBracket: Align AlignTrailingComments: false AllowShortBlocksOnASingleLine: false AllowShortFunctionsOnASingleLine: Inline AllowShortIfStatementsOnASingleLine: true AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None BinPackArguments: false BinPackParameters: true BreakBeforeBraces: Custom BraceWrapping: AfterClass: true AfterControlStatement: false AfterEnum: true AfterFunction: true AfterNamespace: true AfterObjCDeclaration: false AfterStruct: true AfterUnion: true BeforeCatch: true BeforeElse: true IndentBraces: false ContinuationIndentWidth: 4 ConstructorInitializerIndentWidth: 4 ConstructorInitializerAllOnOneLineOrOnePerLine: true ColumnLimit: 0 Cpp11BracedListStyle: false IndentWidth: 4 IndentCaseLabels: false # KeepEmptyLinesAtTheStartOfBlocks: false MaxEmptyLinesToKeep: 1 NamespaceIndentation: Inner ReflowComments: false PenaltyBreakBeforeFirstCallParameter: 100000 PenaltyBreakComment: 100000 SortIncludes: false SpaceAfterTemplateKeyword: true # Standard: Cpp11 # Broken UseTab: Never ...
AirSim/.clang-format/0
{ "file_path": "AirSim/.clang-format", "repo_id": "AirSim", "token_count": 458 }
7
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef air_RpcLibServerBase_hpp #define air_RpcLibServerBase_hpp #include "common/Common.hpp" #include "api/ApiServerBase.hpp" #include "api/ApiProvider.hpp" namespace msr { namespace airlib { class RpcLibServerBase : public ApiServerBase { public: RpcLibServerBase(ApiProvider* api_provider, const std::string& server_address, uint16_t port = RpcLibPort); virtual ~RpcLibServerBase() override; virtual void start(bool block, std::size_t thread_count) override; virtual void stop() override; class ApiNotSupported : public std::runtime_error { public: ApiNotSupported(const std::string& message) : std::runtime_error(message) { } }; protected: void* getServer() const; virtual VehicleApiBase* getVehicleApi(const std::string& vehicle_name) { auto* api = api_provider_->getVehicleApi(vehicle_name); if (api) return api; else throw ApiNotSupported("Vehicle API for '" + vehicle_name + "' is not available. This could either because this is simulation-only API or this vehicle does not exist"); } virtual VehicleSimApiBase* getVehicleSimApi(const std::string& vehicle_name) { auto* api = api_provider_->getVehicleSimApi(vehicle_name); if (api) return api; else throw ApiNotSupported("Vehicle Sim-API for '" + vehicle_name + "' is not available. This could either because this is not a simulation or this vehicle does not exist"); } virtual WorldSimApiBase* getWorldSimApi() { auto* api = api_provider_->getWorldSimApi(); if (api) return api; else throw ApiNotSupported("World-Sim API " "' is not available. This could be because this is not a simulation"); } private: ApiProvider* api_provider_; struct impl; std::unique_ptr<impl> pimpl_; }; } } //namespace #endif
AirSim/AirLib/include/api/RpcLibServerBase.hpp/0
{ "file_path": "AirSim/AirLib/include/api/RpcLibServerBase.hpp", "repo_id": "AirSim", "token_count": 1086 }
8
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef air_GeodeticConverter_hpp #define air_GeodeticConverter_hpp #include <cmath> #include "VectorMath.hpp" namespace msr { namespace airlib { class GeodeticConverter { public: GeodeticConverter(double home_latitude = 0, double home_longitude = 0, float home_altitude = 0) { setHome(home_latitude, home_longitude, home_altitude); } GeodeticConverter(const GeoPoint& home_geopoint) { setHome(home_geopoint); } void setHome(double home_latitude, double home_longitude, float home_altitude) { home_latitude_ = home_latitude; home_longitude_ = home_longitude; home_altitude_ = home_altitude; // Save NED origin home_latitude_rad_ = deg2Rad(home_latitude); home_longitude_rad_ = deg2Rad(home_longitude); // Compute ECEF of NED origin geodetic2Ecef(home_latitude_, home_longitude_, home_altitude_, &home_ecef_x_, &home_ecef_y_, &home_ecef_z_); // Compute ECEF to NED and NED to ECEF matrices ecef_to_ned_matrix_ = nRe(home_latitude_rad_, home_longitude_rad_); ned_to_ecef_matrix_ = ecef_to_ned_matrix_.inverse(); } void setHome(const GeoPoint& home_geopoint) { setHome(home_geopoint.latitude, home_geopoint.longitude, home_geopoint.altitude); } void getHome(double* latitude, double* longitude, float* altitude) { *latitude = home_latitude_; *longitude = home_longitude_; *altitude = home_altitude_; } void geodetic2Ecef(const double latitude, const double longitude, const double altitude, double* x, double* y, double* z) { // Convert geodetic coordinates to ECEF. // http://code.google.com/p/pysatel/source/browse/trunk/coord.py?r=22 double lat_rad = deg2Rad(latitude); double lon_rad = deg2Rad(longitude); double xi = sqrt(1 - kFirstEccentricitySquared * sin(lat_rad) * sin(lat_rad)); *x = (kSemimajorAxis / xi + altitude) * cos(lat_rad) * cos(lon_rad); *y = (kSemimajorAxis / xi + altitude) * cos(lat_rad) * sin(lon_rad); *z = (kSemimajorAxis / xi * (1 - kFirstEccentricitySquared) + altitude) * sin(lat_rad); } void ecef2Geodetic(const double x, const double y, const double z, double* latitude, double* longitude, float* altitude) { // Convert ECEF coordinates to geodetic coordinates. // J. Zhu, "Conversion of Earth-centered Earth-fixed coordinates // to geodetic coordinates," IEEE Transactions on Aerospace and // Electronic Systems, vol. 30, pp. 957-961, 1994. double r = sqrt(x * x + y * y); double Esq = kSemimajorAxis * kSemimajorAxis - kSemiminorAxis * kSemiminorAxis; double F = 54 * kSemiminorAxis * kSemiminorAxis * z * z; double G = r * r + (1 - kFirstEccentricitySquared) * z * z - kFirstEccentricitySquared * Esq; double C = (kFirstEccentricitySquared * kFirstEccentricitySquared * F * r * r) / pow(G, 3); double S = cbrt(1 + C + sqrt(C * C + 2 * C)); double P = F / (3 * pow((S + 1 / S + 1), 2) * G * G); double Q = sqrt(1 + 2 * kFirstEccentricitySquared * kFirstEccentricitySquared * P); double r_0 = -(P * kFirstEccentricitySquared * r) / (1 + Q) + sqrt( 0.5 * kSemimajorAxis * kSemimajorAxis * (1 + 1.0 / Q) - P * (1 - kFirstEccentricitySquared) * z * z / (Q * (1 + Q)) - 0.5 * P * r * r); double U = sqrt(pow((r - kFirstEccentricitySquared * r_0), 2) + z * z); double V = sqrt( pow((r - kFirstEccentricitySquared * r_0), 2) + (1 - kFirstEccentricitySquared) * z * z); double Z_0 = kSemiminorAxis * kSemiminorAxis * z / (kSemimajorAxis * V); *altitude = static_cast<float>(U * (1 - kSemiminorAxis * kSemiminorAxis / (kSemimajorAxis * V))); *latitude = rad2Deg(atan((z + kSecondEccentricitySquared * Z_0) / r)); *longitude = rad2Deg(atan2(y, x)); } void ecef2Ned(const double x, const double y, const double z, double* north, double* east, double* down) { // Converts ECEF coordinate position into local-tangent-plane NED. // Coordinates relative to given ECEF coordinate frame. Vector3d vect, ret; vect(0) = x - home_ecef_x_; vect(1) = y - home_ecef_y_; vect(2) = z - home_ecef_z_; ret = ecef_to_ned_matrix_ * vect; *north = ret(0); *east = ret(1); *down = -ret(2); } void ned2Ecef(const double north, const double east, const float down, double* x, double* y, double* z) { // NED (north/east/down) to ECEF coordinates Vector3d ned, ret; ned(0) = north; ned(1) = east; ned(2) = -down; ret = ned_to_ecef_matrix_ * ned; *x = ret(0) + home_ecef_x_; *y = ret(1) + home_ecef_y_; *z = ret(2) + home_ecef_z_; } void geodetic2Ned(const double latitude, const double longitude, const float altitude, double* north, double* east, double* down) { // Geodetic position to local NED frame double x, y, z; geodetic2Ecef(latitude, longitude, altitude, &x, &y, &z); ecef2Ned(x, y, z, north, east, down); } void ned2Geodetic(const double north, const double east, const float down, double* latitude, double* longitude, float* altitude) { // Local NED position to geodetic coordinates double x, y, z; ned2Ecef(north, east, down, &x, &y, &z); ecef2Geodetic(x, y, z, latitude, longitude, altitude); } void ned2Geodetic(const Vector3r& ned_pos, GeoPoint& geopoint) { ned2Geodetic(ned_pos[0], ned_pos[1], ned_pos[2], &geopoint.latitude, &geopoint.longitude, &geopoint.altitude); } void geodetic2Enu(const double latitude, const double longitude, const double altitude, double* east, double* north, double* up) { // Geodetic position to local ENU frame double x, y, z; geodetic2Ecef(latitude, longitude, altitude, &x, &y, &z); double aux_north, aux_east, aux_down; ecef2Ned(x, y, z, &aux_north, &aux_east, &aux_down); *east = aux_east; *north = aux_north; *up = -aux_down; } void enu2Geodetic(const double east, const double north, const float up, double* latitude, double* longitude, float* altitude) { // Local ENU position to geodetic coordinates const double aux_north = north; const double aux_east = east; const float aux_down = -up; double x, y, z; ned2Ecef(aux_north, aux_east, aux_down, &x, &y, &z); ecef2Geodetic(x, y, z, latitude, longitude, altitude); } private: typedef msr::airlib::VectorMathf VectorMath; typedef VectorMath::Vector3d Vector3d; typedef VectorMath::Matrix3x3d Matrix3x3d; // Geodetic system parameters static constexpr double kSemimajorAxis = 6378137; static constexpr double kSemiminorAxis = 6356752.3142; static constexpr double kFirstEccentricitySquared = 6.69437999014 * 0.001; static constexpr double kSecondEccentricitySquared = 6.73949674228 * 0.001; static constexpr double kFlattening = 1 / 298.257223563; inline Matrix3x3d nRe(const double lat_radians, const double lon_radians) { const double sLat = sin(lat_radians); const double sLon = sin(lon_radians); const double cLat = cos(lat_radians); const double cLon = cos(lon_radians); Matrix3x3d ret; ret(0, 0) = -sLat * cLon; ret(0, 1) = -sLat * sLon; ret(0, 2) = cLat; ret(1, 0) = -sLon; ret(1, 1) = cLon; ret(1, 2) = 0.0; ret(2, 0) = cLat * cLon; ret(2, 1) = cLat * sLon; ret(2, 2) = sLat; return ret; } inline double rad2Deg(const double radians) { return (radians / M_PI) * 180.0; } inline double deg2Rad(const double degrees) { return (degrees / 180.0) * M_PI; } double home_latitude_rad_, home_latitude_; double home_longitude_rad_, home_longitude_; float home_altitude_; double home_ecef_x_; double home_ecef_y_; double home_ecef_z_; Matrix3x3d ecef_to_ned_matrix_; Matrix3x3d ned_to_ecef_matrix_; }; // class GeodeticConverter } } #endif // GEODETIC_CONVERTER_H_
AirSim/AirLib/include/common/GeodeticConverter.hpp/0
{ "file_path": "AirSim/AirLib/include/common/GeodeticConverter.hpp", "repo_id": "AirSim", "token_count": 4830 }
9
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef CommonUtils_EnumFlags_hpp #define CommonUtils_EnumFlags_hpp namespace common_utils { template <typename TEnum, typename TUnderlying = typename std::underlying_type<TEnum>::type> class EnumFlags { protected: TUnderlying flags_; public: EnumFlags() : flags_(0) { } EnumFlags(TEnum singleFlag) : flags_(static_cast<TUnderlying>(singleFlag)) { } EnumFlags(TUnderlying flags) : flags_(flags) { } EnumFlags(const EnumFlags& original) : flags_(original.flags_) { } EnumFlags& operator|=(TEnum add_value) { flags_ |= static_cast<TUnderlying>(add_value); return *this; } EnumFlags& operator|=(EnumFlags add_value) { flags_ |= add_value.flags_; return *this; } EnumFlags operator|(TEnum add_value) const { EnumFlags result(*this); result |= add_value; return result; } EnumFlags operator|(EnumFlags add_value) const { EnumFlags result(*this); result |= add_value.flags_; return result; } EnumFlags& operator&=(TEnum mask_value) { flags_ &= static_cast<TUnderlying>(mask_value); return *this; } EnumFlags& operator&=(EnumFlags mask_value) { flags_ &= mask_value.flags_; return *this; } EnumFlags operator&(TEnum mask_value) const { EnumFlags result(*this); result &= mask_value; return result; } EnumFlags operator&(EnumFlags mask_value) const { EnumFlags result(*this); result &= mask_value.flags_; return result; } EnumFlags operator~() const { EnumFlags result(*this); result.flags_ = ~result.flags_; return result; } EnumFlags& operator^=(TEnum mask_value) { flags_ ^= mask_value; return *this; } EnumFlags& operator^=(EnumFlags mask_value) { flags_ ^= mask_value.flags_; return *this; } EnumFlags operator^(TEnum mask_value) const { EnumFlags result(*this); result.flags_ ^= mask_value; return result; } EnumFlags operator^(EnumFlags mask_value) const { EnumFlags result(*this); result.flags_ ^= mask_value.flags_; return result; } //EnumFlags& operator ~=(TEnum mask_value) //{ // flags_ ~= static_cast<TUnderlying>(mask_value); // return *this; //} //EnumFlags& operator ~=(EnumFlags mask_value) //{ // flags_ ~= mask_value.flags_; // return *this; //} //equality operators bool operator==(const EnumFlags& rhs) const { return flags_ == rhs.flags_; } inline bool operator!=(const EnumFlags& rhs) const { return !(*this == rhs); } //type conversion operator bool() const { return flags_ != 0; } operator TUnderlying() const { return flags_; } TEnum toEnum() const { return static_cast<TEnum>(flags_); } }; } //namespace #endif
AirSim/AirLib/include/common/common_utils/EnumFlags.hpp/0
{ "file_path": "AirSim/AirLib/include/common/common_utils/EnumFlags.hpp", "repo_id": "AirSim", "token_count": 1476 }
10
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. //there is no #pragma once in this header //following is required to support Unreal Build System #if (defined _WIN32 || defined _WIN64) && (defined UE_GAME || defined UE_EDITOR) #include "CoreTypes.h" #include "Windows/PreWindowsApi.h" #include "Windows/AllowWindowsPlatformTypes.h" #include "Windows/AllowWindowsPlatformAtomics.h" //remove warnings for VC++ #pragma warning(push) #pragma warning(disable : 4191 6000 28251) #pragma warning(disable : 4996) //warning C4996: This function or variable may be unsafe. Consider using xxx instead. #pragma warning(disable : 4005) //warning C4005: 'TEXT': macro redefinition #endif
AirSim/AirLib/include/common/common_utils/WindowsApisCommonPre.hpp/0
{ "file_path": "AirSim/AirLib/include/common/common_utils/WindowsApisCommonPre.hpp", "repo_id": "AirSim", "token_count": 213 }
11
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef airsim_core_PhysicsVehicleWorld_hpp #define airsim_core_PhysicsVehicleWorld_hpp #include "common/UpdatableContainer.hpp" #include "common/Common.hpp" #include "PhysicsBody.hpp" #include "PhysicsEngineBase.hpp" #include "World.hpp" #include "common/StateReporterWrapper.hpp" namespace msr { namespace airlib { class PhysicsWorld : UpdatableObject { public: PhysicsWorld(std::unique_ptr<PhysicsEngineBase> physics_engine, const std::vector<UpdatableObject*>& bodies, uint64_t update_period_nanos = 3000000LL, bool state_reporter_enabled = false, bool start_async_updator = true) : world_(std::move(physics_engine)) { setName("PhysicsWorld"); enableStateReport(state_reporter_enabled); update_period_nanos_ = update_period_nanos; initializeWorld(bodies, start_async_updator); } void lock() { world_.lock(); } void unlock() { world_.unlock(); } void reset() { lock(); world_.reset(); unlock(); } void addBody(UpdatableObject* body) { lock(); world_.insert(body); unlock(); } uint64_t getUpdatePeriodNanos() const { return update_period_nanos_; } void startAsyncUpdator() { world_.startAsyncUpdator(update_period_nanos_); } void stopAsyncUpdator() { world_.stopAsyncUpdator(); } void enableStateReport(bool is_enabled) { reporter_.setEnable(is_enabled); } void updateStateReport() { if (reporter_.canReport()) { reporter_.clearReport(); world_.reportState(*reporter_.getReporter()); } } std::string getDebugReport() { return reporter_.getOutput(); } void pause(bool is_paused) { world_.pause(is_paused); } bool isPaused() const { return world_.isPaused(); } void continueForTime(double seconds) { world_.continueForTime(seconds); } void continueForFrames(uint32_t frames) { world_.continueForFrames(frames); } void setFrameNumber(uint32_t frameNumber) { world_.setFrameNumber(frameNumber); } void resetImplementation() override {} private: void initializeWorld(const std::vector<UpdatableObject*>& bodies, bool start_async_updator) { reporter_.initialize(false); world_.insert(&reporter_); for (size_t bi = 0; bi < bodies.size(); bi++) world_.insert(bodies.at(bi)); world_.reset(); if (start_async_updator) world_.startAsyncUpdator(update_period_nanos_); } private: std::vector<UpdatableObject*> bodies_; StateReporterWrapper reporter_; World world_; uint64_t update_period_nanos_; }; } } //namespace #endif
AirSim/AirLib/include/physics/PhysicsWorld.hpp/0
{ "file_path": "AirSim/AirLib/include/physics/PhysicsWorld.hpp", "repo_id": "AirSim", "token_count": 1674 }
12
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_GpsBase_hpp #define msr_airlib_GpsBase_hpp #include "sensors/SensorBase.hpp" #include "common/CommonStructs.hpp" namespace msr { namespace airlib { class GpsBase : public SensorBase { public: GpsBase(const std::string& sensor_name = "") : SensorBase(sensor_name) { } public: //types //TODO: cleanup GPS structures that are not needed struct GpsPoint { public: double latitude, longitude; float height, altitude; int health; GpsPoint() { } GpsPoint(double latitude_val, double longitude_val, float altitude_val, int health_val = -1, float height_val = std::numeric_limits<float>::quiet_NaN()) { latitude = latitude_val; longitude = longitude_val; height = height_val, altitude = altitude_val; health = health_val; } string to_string() { return Utils::stringf("latitude=%f, longitude=%f, altitude=%f, height=%f, health=%d", latitude, longitude, altitude, height, health); } }; enum NavSatStatusType : char { STATUS_NO_FIX = 80, //unable to fix position STATUS_FIX = 0, //unaugmented fix STATUS_SBAS_FIX = 1, //with satellite-based augmentation STATUS_GBAS_FIX = 2 //with ground-based augmentation }; enum NavSatStatusServiceType : unsigned short int { SERVICE_GPS = 1, SERVICE_GLONASS = 2, SERVICE_COMPASS = 4, //includes BeiDou. SERVICE_GALILEO = 8 }; struct NavSatStatus { NavSatStatusType status; NavSatStatusServiceType service; }; enum PositionCovarianceType : unsigned char { COVARIANCE_TYPE_UNKNOWN = 0, COVARIANCE_TYPE_APPROXIMATED = 1, COVARIANCE_TYPE_DIAGONAL_KNOWN = 2, COVARIANCE_TYPE_KNOWN = 3 }; enum GnssFixType : unsigned char { GNSS_FIX_NO_FIX = 0, GNSS_FIX_TIME_ONLY = 1, GNSS_FIX_2D_FIX = 2, GNSS_FIX_3D_FIX = 3 }; struct GnssReport { GeoPoint geo_point; real_T eph, epv; //GPS HDOP/VDOP horizontal/vertical dilution of position (unitless), 0-100% Vector3r velocity; GnssFixType fix_type; uint64_t time_utc = 0; }; struct NavSatFix { GeoPoint geo_point; double position_covariance[9] = {}; NavSatStatus status; PositionCovarianceType position_covariance_type; }; struct Output { //same as ROS message TTimePoint time_stamp; GnssReport gnss; bool is_valid = false; }; public: virtual void reportState(StateReporter& reporter) override { //call base UpdatableObject::reportState(reporter); reporter.writeValue("GPS-Loc", output_.gnss.geo_point); reporter.writeValue("GPS-Vel", output_.gnss.velocity); reporter.writeValue("GPS-Eph", output_.gnss.eph); reporter.writeValue("GPS-Epv", output_.gnss.epv); } const Output& getOutput() const { return output_; } protected: void setOutput(const Output& output) { output_ = output; } private: Output output_; }; } } //namespace #endif
AirSim/AirLib/include/sensors/gps/GpsBase.hpp/0
{ "file_path": "AirSim/AirLib/include/sensors/gps/GpsBase.hpp", "repo_id": "AirSim", "token_count": 1931 }
13
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef air_CarRpcLibServer_hpp #define air_CarRpcLibServer_hpp #ifndef AIRLIB_NO_RPC #include "common/Common.hpp" #include <functional> #include "api/RpcLibServerBase.hpp" #include "vehicles/car/api/CarApiBase.hpp" namespace msr { namespace airlib { class CarRpcLibServer : public RpcLibServerBase { public: CarRpcLibServer(ApiProvider* api_provider, string server_address, uint16_t port = RpcLibPort); virtual ~CarRpcLibServer(); protected: virtual CarApiBase* getVehicleApi(const std::string& vehicle_name) override { return static_cast<CarApiBase*>(RpcLibServerBase::getVehicleApi(vehicle_name)); } }; #endif } } //namespace #endif
AirSim/AirLib/include/vehicles/car/api/CarRpcLibServer.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/car/api/CarRpcLibServer.hpp", "repo_id": "AirSim", "token_count": 325 }
14
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_vehicles_ArduCopterSolo_hpp #define msr_airlib_vehicles_ArduCopterSolo_hpp #include "vehicles/multirotor/firmwares/mavlink/ArduCopterSoloApi.hpp" namespace msr { namespace airlib { class ArduCopterSoloParams : public MultiRotorParams { public: ArduCopterSoloParams(const AirSimSettings::MavLinkVehicleSetting& vehicle_settings, std::shared_ptr<const SensorFactory> sensor_factory) : sensor_factory_(sensor_factory) { connection_info_ = getConnectionInfo(vehicle_settings); } virtual ~ArduCopterSoloParams() = default; virtual std::unique_ptr<MultirotorApiBase> createMultirotorApi() override { unique_ptr<MultirotorApiBase> api(new ArduCopterSoloApi()); auto api_ptr = static_cast<ArduCopterSoloApi*>(api.get()); api_ptr->initialize(connection_info_, &getSensors(), true); return api; } virtual void setupParams() override { // TODO consider whether we want to make us of the 'connection_info_.model' field (perhaps to indicate different sensor configs, say? not sure...) auto& params = getParams(); setupSolo(params); } private: void setupSolo(Params& params) { //set up arm lengths //dimensions are for F450 frame: http://artofcircuits.com/product/quadcopter-frame-hj450-with-power-distribution params.rotor_count = 4; // This is in meters (3DR spec indicates that motor-to-motor is 18.1 inches, so we're just dividing that by 2, which looks about right in real life) std::vector<real_T> arm_lengths(params.rotor_count, 0.22987f); // Takeoff mass, in kilograms (this is from the 3DR spec with no camera) //params.mass = 1.5f; // And this is what works currently - TODO sort out why ArduPilot isn't providing sufficient rotor power for default Solo weight - presumably some param setting? params.mass = 0.8f; // Mass in kg - can't find a 3DR spec on this, so we'll guess they're the same 55g as the DJI F450's motors real_T motor_assembly_weight = 0.055f; real_T box_mass = params.mass - params.rotor_count * motor_assembly_weight; // using rotor_param default, but if you want to change any of the rotor_params, call calculateMaxThrust() to recompute the max_thrust // given new thrust coefficients, motor max_rpm and propeller diameter. params.rotor_params.calculateMaxThrust(); // Dimensions of core body box or abdomen, in meters (not including arms). KM measures the Solo at 9.5" x 4.5" x 3" params.body_box.x() = 0.2413f; params.body_box.y() = 0.1143f; params.body_box.z() = 0.0762f; // Meters up from center of box mass - KM measures at about 3" real_T rotor_z = 0.0762f; //computer rotor poses initializeRotorQuadX(params.rotor_poses, params.rotor_count, arm_lengths.data(), rotor_z); //compute inertia matrix computeInertiaMatrix(params.inertia, params.body_box, params.rotor_poses, box_mass, motor_assembly_weight); } static const AirSimSettings::MavLinkConnectionInfo getConnectionInfo(const AirSimSettings::MavLinkVehicleSetting& vehicle_setting) { AirSimSettings::MavLinkConnectionInfo result = vehicle_setting.connection_info; return result; } protected: virtual const SensorFactory* getSensorFactory() const override { return sensor_factory_.get(); } private: AirSimSettings::MavLinkConnectionInfo connection_info_; std::shared_ptr<const SensorFactory> sensor_factory_; }; } } //namespace #endif
AirSim/AirLib/include/vehicles/multirotor/firmwares/mavlink/ArduCopterSoloParams.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/mavlink/ArduCopterSoloParams.hpp", "repo_id": "AirSim", "token_count": 1646 }
15
#pragma once #include <cstdint> #include "interfaces/ICommLink.hpp" #include "interfaces/IGoal.hpp" #include "interfaces/IOffboardApi.hpp" #include "interfaces/IUpdatable.hpp" #include "interfaces/CommonStructs.hpp" #include "RemoteControl.hpp" #include "Params.hpp" namespace simple_flight { class OffboardApi : public IUpdatable , public IOffboardApi { public: OffboardApi(const Params* params, const IBoardClock* clock, const IBoardInputPins* board_inputs, IStateEstimator* state_estimator, ICommLink* comm_link) : params_(params), rc_(params, clock, board_inputs, &vehicle_state_, state_estimator, comm_link), state_estimator_(state_estimator), comm_link_(comm_link), clock_(clock), landed_(true) { } virtual void reset() override { IUpdatable::reset(); vehicle_state_.setState(params_->default_vehicle_state, state_estimator_->getGeoPoint()); rc_.reset(); has_api_control_ = false; landed_ = true; takenoff_ = false; goal_timestamp_ = clock_->millis(); updateGoalFromRc(); } virtual void update() override { IUpdatable::update(); rc_.update(); if (!has_api_control_) updateGoalFromRc(); else { if (takenoff_ && (clock_->millis() - goal_timestamp_ > params_->api_goal_timeout)) { if (!is_api_timedout_) { comm_link_->log("API call was not received, entering hover mode for safety"); goal_mode_ = GoalMode::getPositionMode(); goal_ = Axis4r::xyzToAxis4(state_estimator_->getPosition(), true); is_api_timedout_ = true; } //do not update goal_timestamp_ } } //else leave the goal set by IOffboardApi API detectLanding(); detectTakingOff(); } /**************** IOffboardApi ********************/ virtual const Axis4r& getGoalValue() const override { return goal_; } virtual const GoalMode& getGoalMode() const override { return goal_mode_; } virtual bool canRequestApiControl(std::string& message) override { if (rc_.allowApiControl()) return true; else { message = "Remote Control switch position disallows API control"; comm_link_->log(message, ICommLink::kLogLevelError); return false; } } virtual bool hasApiControl() override { return has_api_control_; } virtual bool requestApiControl(std::string& message) override { if (canRequestApiControl(message)) { has_api_control_ = true; //initial value from RC for smooth transition updateGoalFromRc(); comm_link_->log("requestApiControl was successful", ICommLink::kLogLevelInfo); return true; } else { comm_link_->log("requestApiControl failed", ICommLink::kLogLevelError); return false; } } virtual void releaseApiControl() override { has_api_control_ = false; comm_link_->log("releaseApiControl was successful", ICommLink::kLogLevelInfo); } virtual bool setGoalAndMode(const Axis4r* goal, const GoalMode* goal_mode, std::string& message) override { if (has_api_control_) { if (goal != nullptr) goal_ = *goal; if (goal_mode != nullptr) goal_mode_ = *goal_mode; goal_timestamp_ = clock_->millis(); is_api_timedout_ = false; return true; } else { message = "requestApiControl() must be called before using API control"; comm_link_->log(message, ICommLink::kLogLevelError); return false; } } virtual bool arm(std::string& message) override { if (has_api_control_) { if (vehicle_state_.getState() == VehicleStateType::Armed) { message = "Vehicle is already armed"; comm_link_->log(message, ICommLink::kLogLevelInfo); return true; } else if ((vehicle_state_.getState() == VehicleStateType::Inactive || vehicle_state_.getState() == VehicleStateType::Disarmed || vehicle_state_.getState() == VehicleStateType::BeingDisarmed)) { vehicle_state_.setState(VehicleStateType::Armed, state_estimator_->getHomeGeoPoint()); goal_ = Axis4r(0, 0, 0, params_->rc.min_angling_throttle); goal_mode_ = GoalMode::getAllRateMode(); message = "Vehicle is armed"; comm_link_->log(message, ICommLink::kLogLevelInfo); return true; } else { message = "Vehicle cannot be armed because it is not in Inactive, Disarmed or BeingDisarmed state"; comm_link_->log(message, ICommLink::kLogLevelError); return false; } } else { message = "Vehicle cannot be armed via API because API has not been given control"; comm_link_->log(message, ICommLink::kLogLevelError); return false; } } virtual bool disarm(std::string& message) override { if (has_api_control_ && (vehicle_state_.getState() == VehicleStateType::Active || vehicle_state_.getState() == VehicleStateType::Armed || vehicle_state_.getState() == VehicleStateType::BeingArmed)) { vehicle_state_.setState(VehicleStateType::Disarmed); goal_ = Axis4r(0, 0, 0, 0); goal_mode_ = GoalMode::getAllRateMode(); message = "Vehicle is disarmed"; comm_link_->log(message, ICommLink::kLogLevelInfo); return true; } else { message = "Vehicle cannot be disarmed because it is not in Active, Armed or BeingArmed state"; comm_link_->log(message, ICommLink::kLogLevelError); return false; } } virtual VehicleStateType getVehicleState() const override { return vehicle_state_.getState(); } virtual const IStateEstimator& getStateEstimator() override { return *state_estimator_; } virtual GeoPoint getHomeGeoPoint() const override { return state_estimator_->getHomeGeoPoint(); } virtual GeoPoint getGeoPoint() const override { return state_estimator_->getGeoPoint(); } virtual bool getLandedState() const override { return landed_; } private: void updateGoalFromRc() { goal_ = rc_.getGoalValue(); goal_mode_ = rc_.getGoalMode(); } void detectLanding() { // if we are not trying to move by setting motor outputs if (takenoff_) { //if (!isGreaterThanArmedThrottle(goal_.throttle())) { float checkThrottle = rc_.getMotorOutput(); if (!isGreaterThanArmedThrottle(checkThrottle)) { // and we are not currently moving (based on current velocities) auto angular = state_estimator_->getAngularVelocity(); auto velocity = state_estimator_->getLinearVelocity(); if (isAlmostZero(angular.roll()) && isAlmostZero(angular.pitch()) && isAlmostZero(angular.yaw()) && isAlmostZero(velocity.x()) && isAlmostZero(velocity.y()) && isAlmostZero(velocity.z())) { // then we must be landed... landed_ = true; takenoff_ = false; } } } } void detectTakingOff() { // if we are not trying to move by setting motor outputs if (!takenoff_) { float checkThrottle = rc_.getMotorOutput(); //TODO: better handling of landed & takenoff states if (isGreaterThanArmedThrottle(checkThrottle) && std::abs(state_estimator_->getLinearVelocity().z()) > 0.01f) { takenoff_ = true; landed_ = false; } } } bool isAlmostZero(float v) { return std::abs(v) < kMovementTolerance; } bool isGreaterThanArmedThrottle(float throttle) { return throttle > params_->min_armed_throttle(); } private: const TReal kMovementTolerance = (TReal)0.08; const Params* params_; RemoteControl rc_; IStateEstimator* state_estimator_; ICommLink* comm_link_; const IBoardClock* clock_; VehicleState vehicle_state_; Axis4r goal_; GoalMode goal_mode_; uint64_t goal_timestamp_; bool has_api_control_; bool is_api_timedout_; bool landed_, takenoff_; }; } //namespace
AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/OffboardApi.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/OffboardApi.hpp", "repo_id": "AirSim", "token_count": 4025 }
16
#pragma once #include "IUpdatable.hpp" #include <cstdint> namespace simple_flight { class ICommLink : public IUpdatable { public: static constexpr int kLogLevelInfo = 0; static constexpr int kLogLevelWarn = 1; static constexpr int kLogLevelError = 2; virtual void log(const std::string& message, int32_t log_level = ICommLink::kLogLevelInfo) = 0; }; } //namespace
AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/interfaces/ICommLink.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/interfaces/ICommLink.hpp", "repo_id": "AirSim", "token_count": 141 }
17
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. //in header only mode, control library is not available #ifndef AIRLIB_HEADER_ONLY //RPC code requires C++14. If build system like Unreal doesn't support it then use compiled binaries #ifndef AIRLIB_NO_RPC //if using Unreal Build system then include precompiled header file first #include "vehicles/multirotor/api/MultirotorRpcLibClient.hpp" #include "common/Common.hpp" #include <thread> STRICT_MODE_OFF #ifndef RPCLIB_MSGPACK #define RPCLIB_MSGPACK clmdep_msgpack #endif // !RPCLIB_MSGPACK #ifdef nil #undef nil #endif // nil #include "common/common_utils/WindowsApisCommonPre.hpp" #undef FLOAT #undef check #include "rpc/client.h" //TODO: HACK: UE4 defines macro with stupid names like "check" that conflicts with msgpack library #ifndef check #define check(expr) (static_cast<void>((expr))) #endif #include "common/common_utils/WindowsApisCommonPost.hpp" #include "vehicles/multirotor/api/MultirotorRpcLibAdaptors.hpp" STRICT_MODE_ON #ifdef _MSC_VER __pragma(warning(disable : 4239)) #endif namespace msr { namespace airlib { typedef msr::airlib_rpclib::MultirotorRpcLibAdaptors MultirotorRpcLibAdaptors; struct MultirotorRpcLibClient::impl { public: std::future<RPCLIB_MSGPACK::object_handle> last_future; }; MultirotorRpcLibClient::MultirotorRpcLibClient(const string& ip_address, uint16_t port, float timeout_sec) : RpcLibClientBase(ip_address, port, timeout_sec) { pimpl_.reset(new impl()); } MultirotorRpcLibClient::~MultirotorRpcLibClient() { } MultirotorRpcLibClient* MultirotorRpcLibClient::takeoffAsync(float timeout_sec, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("takeoff", timeout_sec, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::landAsync(float timeout_sec, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("land", timeout_sec, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::goHomeAsync(float timeout_sec, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("goHome", timeout_sec, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveByVelocityBodyFrameAsync(float vx, float vy, float vz, float duration, DrivetrainType drivetrain, const YawMode& yaw_mode, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveByVelocityBodyFrame", vx, vy, vz, duration, drivetrain, MultirotorRpcLibAdaptors::YawMode(yaw_mode), vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveByVelocityZBodyFrameAsync(float vx, float vy, float z, float duration, DrivetrainType drivetrain, const YawMode& yaw_mode, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveByVelocityZBodyFrame", vx, vy, z, duration, drivetrain, MultirotorRpcLibAdaptors::YawMode(yaw_mode), vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveByMotorPWMsAsync(float front_right_pwm, float rear_left_pwm, float front_left_pwm, float rear_right_pwm, float duration, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveByMotorPWMs", front_right_pwm, rear_left_pwm, front_left_pwm, rear_right_pwm, duration, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveByRollPitchYawZAsync(float roll, float pitch, float yaw, float z, float duration, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveByRollPitchYawZ", roll, pitch, yaw, z, duration, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveByRollPitchYawThrottleAsync(float roll, float pitch, float yaw, float throttle, float duration, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveByRollPitchYawThrottle", roll, pitch, yaw, throttle, duration, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveByRollPitchYawrateThrottleAsync(float roll, float pitch, float yaw_rate, float throttle, float duration, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveByRollPitchYawrateThrottle", roll, pitch, yaw_rate, throttle, duration, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveByRollPitchYawrateZAsync(float roll, float pitch, float yaw_rate, float z, float duration, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveByRollPitchYawrateZ", roll, pitch, yaw_rate, z, duration, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveByAngleRatesZAsync(float roll_rate, float pitch_rate, float yaw_rate, float z, float duration, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveByAngleRatesZ", roll_rate, pitch_rate, yaw_rate, z, duration, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveByAngleRatesThrottleAsync(float roll_rate, float pitch_rate, float yaw_rate, float throttle, float duration, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveByAngleRatesThrottle", roll_rate, pitch_rate, yaw_rate, throttle, duration, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveByVelocityAsync(float vx, float vy, float vz, float duration, DrivetrainType drivetrain, const YawMode& yaw_mode, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveByVelocity", vx, vy, vz, duration, drivetrain, MultirotorRpcLibAdaptors::YawMode(yaw_mode), vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveByVelocityZAsync(float vx, float vy, float z, float duration, DrivetrainType drivetrain, const YawMode& yaw_mode, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveByVelocityZ", vx, vy, z, duration, drivetrain, MultirotorRpcLibAdaptors::YawMode(yaw_mode), vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveOnPathAsync(const vector<Vector3r>& path, float velocity, float duration, DrivetrainType drivetrain, const YawMode& yaw_mode, float lookahead, float adaptive_lookahead, const std::string& vehicle_name) { vector<MultirotorRpcLibAdaptors::Vector3r> conv_path; MultirotorRpcLibAdaptors::from(path, conv_path); pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveOnPath", conv_path, velocity, duration, drivetrain, MultirotorRpcLibAdaptors::YawMode(yaw_mode), lookahead, adaptive_lookahead, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveToGPSAsync(float latitude, float longitude, float altitude, float velocity, float timeout_sec, DrivetrainType drivetrain, const YawMode& yaw_mode, float lookahead, float adaptive_lookahead, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("movetoGPS", latitude, longitude, altitude, velocity, timeout_sec, drivetrain, MultirotorRpcLibAdaptors::YawMode(yaw_mode), lookahead, adaptive_lookahead, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveToPositionAsync(float x, float y, float z, float velocity, float timeout_sec, DrivetrainType drivetrain, const YawMode& yaw_mode, float lookahead, float adaptive_lookahead, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveToPosition", x, y, z, velocity, timeout_sec, drivetrain, MultirotorRpcLibAdaptors::YawMode(yaw_mode), lookahead, adaptive_lookahead, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveToZAsync(float z, float velocity, float timeout_sec, const YawMode& yaw_mode, float lookahead, float adaptive_lookahead, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveToZ", z, velocity, timeout_sec, MultirotorRpcLibAdaptors::YawMode(yaw_mode), lookahead, adaptive_lookahead, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::moveByManualAsync(float vx_max, float vy_max, float z_min, float duration, DrivetrainType drivetrain, const YawMode& yaw_mode, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("moveByManual", vx_max, vy_max, z_min, duration, drivetrain, MultirotorRpcLibAdaptors::YawMode(yaw_mode), vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::rotateToYawAsync(float yaw, float timeout_sec, float margin, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("rotateToYaw", yaw, timeout_sec, margin, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::rotateByYawRateAsync(float yaw_rate, float duration, const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("rotateByYawRate", yaw_rate, duration, vehicle_name); return this; } MultirotorRpcLibClient* MultirotorRpcLibClient::hoverAsync(const std::string& vehicle_name) { pimpl_->last_future = static_cast<rpc::client*>(getClient())->async_call("hover", vehicle_name); return this; } void MultirotorRpcLibClient::setAngleLevelControllerGains(const vector<float>& kp, const vector<float>& ki, const vector<float>& kd, const std::string& vehicle_name) { static_cast<rpc::client*>(getClient())->call("setAngleLevelControllerGains", kp, ki, kd, vehicle_name); } void MultirotorRpcLibClient::setAngleRateControllerGains(const vector<float>& kp, const vector<float>& ki, const vector<float>& kd, const std::string& vehicle_name) { static_cast<rpc::client*>(getClient())->call("setAngleRateControllerGains", kp, ki, kd, vehicle_name); } void MultirotorRpcLibClient::setVelocityControllerGains(const vector<float>& kp, const vector<float>& ki, const vector<float>& kd, const std::string& vehicle_name) { static_cast<rpc::client*>(getClient())->call("setVelocityControllerGains", kp, ki, kd, vehicle_name); } void MultirotorRpcLibClient::setPositionControllerGains(const vector<float>& kp, const vector<float>& ki, const vector<float>& kd, const std::string& vehicle_name) { static_cast<rpc::client*>(getClient())->call("setPositionControllerGains", kp, ki, kd, vehicle_name); } bool MultirotorRpcLibClient::setSafety(SafetyEval::SafetyViolationType enable_reasons, float obs_clearance, SafetyEval::ObsAvoidanceStrategy obs_startegy, float obs_avoidance_vel, const Vector3r& origin, float xy_length, float max_z, float min_z, const std::string& vehicle_name) { return static_cast<rpc::client*>(getClient())->call("setSafety", static_cast<uint>(enable_reasons), obs_clearance, obs_startegy, obs_avoidance_vel, MultirotorRpcLibAdaptors::Vector3r(origin), xy_length, max_z, min_z, vehicle_name).as<bool>(); } //status getters // Rotor state getter RotorStates MultirotorRpcLibClient::getRotorStates(const std::string& vehicle_name) { return static_cast<rpc::client*>(getClient())->call("getRotorStates", vehicle_name).as<MultirotorRpcLibAdaptors::RotorStates>().to(); } // Multirotor state getter MultirotorState MultirotorRpcLibClient::getMultirotorState(const std::string& vehicle_name) { return static_cast<rpc::client*>(getClient())->call("getMultirotorState", vehicle_name).as<MultirotorRpcLibAdaptors::MultirotorState>().to(); } void MultirotorRpcLibClient::moveByRC(const RCData& rc_data, const std::string& vehicle_name) { static_cast<rpc::client*>(getClient())->call("moveByRC", MultirotorRpcLibAdaptors::RCData(rc_data), vehicle_name); } //return value of last task. It should be true if task completed without //cancellation or timeout MultirotorRpcLibClient* MultirotorRpcLibClient::waitOnLastTask(bool* task_result, float timeout_sec) { bool result; if (std::isnan(timeout_sec) || timeout_sec == Utils::max<float>()) result = pimpl_->last_future.get().as<bool>(); else { auto future_status = pimpl_->last_future.wait_for(std::chrono::duration<double>(timeout_sec)); if (future_status == std::future_status::ready) result = pimpl_->last_future.get().as<bool>(); else result = false; } if (task_result) *task_result = result; return this; } } } //namespace #endif #endif
AirSim/AirLib/src/vehicles/multirotor/api/MultirotorRpcLibClient.cpp/0
{ "file_path": "AirSim/AirLib/src/vehicles/multirotor/api/MultirotorRpcLibClient.cpp", "repo_id": "AirSim", "token_count": 6553 }
18
<?xml version="1.0"?> <Solution> <AnalysisConfiguration> <AnalysisToolName Source="Default"/> <AnalysisToolPathName Source="Default"/> <Configuration Source="Default"/> <AnalysisMethod Source="Default"/> <PrecompiledHeaders Source="Default"/> <ConfigFile Source="Default"/> <PolicyFile Source="Default"/> <AdditionalParameters Source="Default"/> <ProjectLntPostProcessor Enable="0" FileName=""/> <AnalysisPostProcessor Enable="0" FileName=""/> <Reports> <Location Source="Default"/> </Reports> </AnalysisConfiguration> <Projects> <Project Name="AirLib" UseAutoGeneratedProjectLntFile="1" Analyse="1"> <AnalysisConfiguration> <AnalysisMethod Source="Default"/> <PrecompiledHeaders Source="Default"/> <ConfigFile Source="Default"/> <PolicyFile Source="Default"/> <AdditionalParameters Source="Default"/> </AnalysisConfiguration> <Files/> </Project> <Project Name="AirLibUnitTests" UseAutoGeneratedProjectLntFile="1" Analyse="0"> <AnalysisConfiguration> <AnalysisMethod Source="Default"/> <PrecompiledHeaders Source="Default"/> <ConfigFile Source="Default"/> <PolicyFile Source="Default"/> <AdditionalParameters Source="Default"/> </AnalysisConfiguration> <Files/> </Project> <Project Name="DroneServer" UseAutoGeneratedProjectLntFile="1" Analyse="0"> <AnalysisConfiguration> <AnalysisMethod Source="Default"/> <PrecompiledHeaders Source="Default"/> <ConfigFile Source="Default"/> <PolicyFile Source="Default"/> <AdditionalParameters Source="Default"/> </AnalysisConfiguration> <Files/> </Project> <Project Name="DroneShell" UseAutoGeneratedProjectLntFile="1" Analyse="0"> <AnalysisConfiguration> <AnalysisMethod Source="Default"/> <PrecompiledHeaders Source="Default"/> <ConfigFile Source="Default"/> <PolicyFile Source="Default"/> <AdditionalParameters Source="Default"/> </AnalysisConfiguration> <Files/> </Project> <Project Name="Examples" UseAutoGeneratedProjectLntFile="1" Analyse="0"> <AnalysisConfiguration> <AnalysisMethod Source="Default"/> <PrecompiledHeaders Source="Default"/> <ConfigFile Source="Default"/> <PolicyFile Source="Default"/> <AdditionalParameters Source="Default"/> </AnalysisConfiguration> <Files/> </Project> <Project Name="HelloCar" UseAutoGeneratedProjectLntFile="1" Analyse="0"> <AnalysisConfiguration> <AnalysisMethod Source="Default"/> <PrecompiledHeaders Source="Default"/> <ConfigFile Source="Default"/> <PolicyFile Source="Default"/> <AdditionalParameters Source="Default"/> </AnalysisConfiguration> <Files/> </Project> <Project Name="HelloDrone" UseAutoGeneratedProjectLntFile="1" Analyse="0"> <AnalysisConfiguration> <AnalysisMethod Source="Default"/> <PrecompiledHeaders Source="Default"/> <ConfigFile Source="Default"/> <PolicyFile Source="Default"/> <AdditionalParameters Source="Default"/> </AnalysisConfiguration> <Files/> </Project> <Project Name="MavLinkCom" UseAutoGeneratedProjectLntFile="1" Analyse="0"> <AnalysisConfiguration> <AnalysisMethod Source="Default"/> <PrecompiledHeaders Source="Default"/> <ConfigFile Source="Default"/> <PolicyFile Source="Default"/> <AdditionalParameters Source="Default"/> </AnalysisConfiguration> <Files/> </Project> <Project Name="MavLinkTest" UseAutoGeneratedProjectLntFile="1" Analyse="0"> <AnalysisConfiguration> <AnalysisMethod Source="Default"/> <PrecompiledHeaders Source="Default"/> <ConfigFile Source="Default"/> <PolicyFile Source="Default"/> <AdditionalParameters Source="Default"/> </AnalysisConfiguration> <Files/> </Project> <Project Name="UnrealPluginFiles" UseAutoGeneratedProjectLntFile="1" Analyse="0"> <AnalysisConfiguration> <AnalysisMethod Source="Default"/> <PrecompiledHeaders Source="Default"/> <ConfigFile Source="Default"/> <PolicyFile Source="Default"/> <AdditionalParameters Source="Default"/> </AnalysisConfiguration> <Files/> </Project> </Projects> </Solution>
AirSim/AirSim.sln.vlconfig/0
{ "file_path": "AirSim/AirSim.sln.vlconfig", "repo_id": "AirSim", "token_count": 1374 }
19
/* * Copyright (C) 2012 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. * */ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include <gazebo/transport/transport.hh> #include <gazebo/msgs/msgs.hh> #include <gazebo/gazebo_client.hh> #include "common/common_utils/StrictMode.hpp" STRICT_MODE_OFF #ifndef RPCLIB_MSGPACK #define RPCLIB_MSGPACK clmdep_msgpack #endif // !RPCLIB_MSGPACK #include "rpc/rpc_error.h" STRICT_MODE_ON #include "vehicles/multirotor/api/MultirotorRpcLibClient.hpp" #include <chrono> #include <iostream> constexpr int NWIDTH = 7; static constexpr int MESSAGE_THROTTLE = 100; using namespace msr::airlib; msr::airlib::MultirotorRpcLibClient client; void cbLocalPose(ConstPosesStampedPtr& msg) { std::cout << std::fixed; std::cout << std::setprecision(3); static int count = 0; for (int i = 0; i < msg->pose_size(); i++) { auto x = msg->pose(i).position().x(); auto y = msg->pose(i).position().y(); auto z = msg->pose(i).position().z(); auto ow = msg->pose(i).orientation().w(); auto ox = msg->pose(i).orientation().x(); auto oy = msg->pose(i).orientation().y(); auto oz = msg->pose(i).orientation().z(); if (count % MESSAGE_THROTTLE == 0) { std::cout << "local (" << std::setw(2) << i << ") "; std::cout << std::left << std::setw(32) << msg->pose(i).name(); std::cout << " x: " << std::right << std::setw(NWIDTH) << x; std::cout << " y: " << std::right << std::setw(NWIDTH) << y; std::cout << " z: " << std::right << std::setw(NWIDTH) << z; std::cout << " ow: " << std::right << std::setw(NWIDTH) << ow; std::cout << " ox: " << std::right << std::setw(NWIDTH) << ox; std::cout << " oy: " << std::right << std::setw(NWIDTH) << oy; std::cout << " oz: " << std::right << std::setw(NWIDTH) << oz; std::cout << std::endl; } if (i == 0) { msr::airlib::Vector3r p(x, -y, -z); msr::airlib::Quaternionr o(ow, ox, -oy, -oz); client.simSetVehiclePose(Pose(p, o), true); } } if (count % MESSAGE_THROTTLE == 0) { std::cout << std::endl; } ++count; } void cbGlobalPose(ConstPosesStampedPtr& msg) { std::cout << std::fixed; std::cout << std::setprecision(4); static int count = 0; if (count % MESSAGE_THROTTLE) { ++count; return; } ++count; for (int i = 0; i < msg->pose_size(); i++) { std::cout << "global (" << i << ") "; std::cout << std::left << std::setw(32) << msg->pose(i).name(); std::cout << " x: " << std::right << std::setfill(' ') << std::setw(NWIDTH) << msg->pose(i).position().x(); std::cout << " y: " << std::right << std::setfill(' ') << std::setw(NWIDTH) << msg->pose(i).position().y(); std::cout << " z: " << std::right << std::setfill(' ') << std::setw(NWIDTH) << msg->pose(i).position().z(); std::cout << " ow: " << std::right << std::setfill(' ') << std::setw(NWIDTH) << msg->pose(i).orientation().w(); std::cout << " ox: " << std::right << std::setfill(' ') << std::setw(NWIDTH) << msg->pose(i).orientation().x(); std::cout << " oy: " << std::right << std::setfill(' ') << std::setw(NWIDTH) << msg->pose(i).orientation().y(); std::cout << " oz: " << std::right << std::setfill(' ') << std::setw(NWIDTH) << msg->pose(i).orientation().z(); std::cout << std::endl; } std::cout << std::endl; } int main(int _argc, char** _argv) { client.confirmConnection(); // Load gazebo gazebo::client::setup(_argc, _argv); // Create our node for communication gazebo::transport::NodePtr node(new gazebo::transport::Node()); node->Init(); // Listen to Gazebo topics gazebo::transport::SubscriberPtr sub_pose1 = node->Subscribe("~/pose/local/info", cbLocalPose); gazebo::transport::SubscriberPtr sub_pose2 = node->Subscribe("~/pose/info", cbGlobalPose); while (true) gazebo::common::Time::MSleep(10); // Make sure to shut everything down. gazebo::client::shutdown(); }
AirSim/GazeboDrone/src/main.cpp/0
{ "file_path": "AirSim/GazeboDrone/src/main.cpp", "repo_id": "AirSim", "token_count": 2050 }
20
<UserControl x:Class="LogViewer.Controls.AppSettings" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:LogViewer.Controls" mc:Ignorable="d" BorderBrush="white" BorderThickness="1" d:DesignHeight="300" d:DesignWidth="300"> <Grid Background="{StaticResource ControlBackgroundBrush}"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid Grid.Row="0" Background="#007ACC"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Button Style="{StaticResource BackButtonStyle}" VerticalAlignment="Top" HorizontalAlignment="Left" Click="OnCloseClicked" Margin="0,4,0,0"></Button> <Label FontSize="18" Grid.Column="1" VerticalAlignment="Center">Settings</Label> </Grid> <Grid Grid.Row="1" Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Label >Theme:</Label> <ComboBox x:Name="ThemeSelection" Grid.Row="1"> </ComboBox> </Grid> </Grid> </UserControl>
AirSim/LogViewer/LogViewer/Controls/AppSettings.xaml/0
{ "file_path": "AirSim/LogViewer/LogViewer/Controls/AppSettings.xaml", "repo_id": "AirSim", "token_count": 851 }
21
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace LogViewer.Controls { /// <summary> /// Captures and eats MouseWheel events so that a nested ListBox does not /// prevent an outer scrollable control from scrolling. /// </summary> public sealed class PassthroughMouseWheelBehavior { public static bool GetPassthroughMouseWheel(UIElement e) { return (bool)e.GetValue(PassthroughMouseWheelProperty); } public static void SetPassthroughMouseWheel(UIElement e, bool value) { e.SetValue(PassthroughMouseWheelProperty, value); } public static readonly DependencyProperty PassthroughMouseWheelProperty = DependencyProperty.RegisterAttached("PassthroughMouseWhee", typeof(bool), typeof(PassthroughMouseWheelBehavior), new UIPropertyMetadata(false, OnPassthroughMouseWheelChanged)); static void OnPassthroughMouseWheelChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e) { var item = depObj as UIElement; if (item == null) return; if (e.NewValue is bool == false) return; if ((bool)e.NewValue) { item.PreviewMouseWheel += OnPreviewMouseWheel; } else { item.PreviewMouseWheel -= OnPreviewMouseWheel; } } static void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e) { e.Handled = true; var e2 = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta) { RoutedEvent = UIElement.MouseWheelEvent }; var gv = sender as UIElement; if (gv != null) gv.RaiseEvent(e2); } } }
AirSim/LogViewer/LogViewer/Controls/PassthroughMouseWheelBehavior.cs/0
{ "file_path": "AirSim/LogViewer/LogViewer/Controls/PassthroughMouseWheelBehavior.cs", "repo_id": "AirSim", "token_count": 844 }
22
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; namespace LogViewer.Model { class KmlDataLog : IDataLog { DateTime startTime; DateTime endTime; XNamespace kmlns = XNamespace.Get("http://www.opengis.net/kml/2.2"); XNamespace gxns = XNamespace.Get("http://www.google.com/kml/ext/2.2"); LogItemSchema schema; List<Flight> flights = new List<Flight>(); List<LogEntry> log = new List<LogEntry>(); public KmlDataLog() { startTime = DateTime.Now; endTime = startTime; } public void Load(XDocument doc) { var root = doc.Root; if (root.Name.LocalName != "kml" || root.Name.Namespace != kmlns) { throw new Exception("Doesn't appear to be KML file, expecting XML namespace '" + kmlns + "'"); } Dictionary<string, XElement> styles = new Dictionary<string, XElement>(); var document = root.Element(kmlns + "Document"); if (document != null) { foreach (XElement style in document.Elements(kmlns + "Style")) { string id = (string)style.Attribute("id"); if (!string.IsNullOrEmpty(id)) { styles[id] = style; } } foreach (XElement placemark in document.Elements(kmlns + "Placemark")) { string name = (string)document.Element(kmlns + "name"); string styleUrl = (string)document.Element(kmlns + "styleUrl"); bool started = false; DateTime current = DateTime.Now; DateTime startTime = current; DateTime endTime = startTime; // "Track" data is one style of KML that we can load GPS data from foreach (XElement track in placemark.Elements(gxns + "Track")) { foreach (XElement child in track.Elements()) { switch(child.Name.LocalName) { case "altitudeMode": // absolute? break; case "interpolate": // 0? break; case "when": var time = DateTime.Parse((string)child); if (!started) { startTime = time; started = true; } current = time; endTime = time; break; case "coord": AddGpsData(current, startTime, (string)child, ' ', "OrderLatLong"); break; } } } // "LineString" is another format. foreach (XElement ls in placemark.Elements(kmlns + "LineString")) { if (!started) { started = true; } XElement coordinates = ls.Element(kmlns + "coordinates"); foreach (string line in ((string)coordinates).Split('\n')) { // fake time, since this format has no time. current = current + TimeSpan.FromMilliseconds(1); endTime = current; AddGpsData(current, startTime, line, ',', "OrderLongLat"); } } if (started) { this.flights.Add(new Flight() { Duration = endTime - startTime, Log = this, Name = name, StartTime = startTime }); } } } } private void AddGpsData(DateTime current, DateTime startTime, string row, char separator, string order) { string[] parts = row.Split(separator); if (parts.Length == 3) { double lat, lng, alt; double.TryParse(parts[0], out lat); double.TryParse(parts[1], out lng); double.TryParse(parts[2], out alt); if (order == "OrderLongLat") { // switch them. double temp = lng; lng = lat; lat = temp; } var gps = new LogEntry() { Name = "GPS", Timestamp = (ulong)current.Ticks }; gps.SetField("TimeMS", (UInt32)((current - startTime).Milliseconds)); gps.SetField("Lat", lat); gps.SetField("Lng", lng); gps.SetField("Alt", alt); log.Add(gps); } } public TimeSpan Duration { get { return endTime - startTime; } } private void Schematize(LogItemSchema schema, IEnumerable<LogField> items) { foreach (var item in items) { // is this a new item we haven't seen before? if (!schema.HasChild(item.Name)) { var typeName = item.Name; if (item is LogEntry) { // recurrse down the structure var s = new LogItemSchema() { Name = item.Name, Type = typeName }; schema.AddChild(s); Schematize(s, ((LogEntry)item).GetFields()); } else { // leaf node typeName = item.Value.GetType().Name; var leaf = new LogItemSchema() { Name = item.Name, Type = typeName }; schema.AddChild(leaf); } } } } public LogItemSchema Schema { get { if (this.schema == null) { this.schema = new LogItemSchema() { Name = "KmlLog", Type = "Root" }; Schematize(this.schema, this.log); } return this.schema; } } public DateTime StartTime { get { return this.startTime; } } public IEnumerable<DataValue> GetDataValues(LogItemSchema schema, DateTime startTime, TimeSpan duration) { if (this.log != null && schema.Parent != null) { foreach (LogEntry entry in GetRows(schema.Parent.Name, startTime, duration)) { var dv = entry.GetDataValue(schema.Name); if (dv != null) { yield return dv; } } } } public IEnumerable<Flight> GetFlights() { return this.flights; } public IEnumerable<LogEntry> GetRows(string typeName, DateTime startTime, TimeSpan duration) { foreach (var row in this.log) { if (string.Compare(row.Name, typeName, StringComparison.OrdinalIgnoreCase) == 0 && (duration == TimeSpan.MaxValue || row.Timestamp >= (ulong)startTime.Ticks && row.Timestamp < (ulong)(startTime + duration).Ticks)) { yield return row; } } } public DateTime GetTime(ulong timeMs) { TimeSpan ms = TimeSpan.FromMilliseconds(timeMs); return this.startTime + ms; } public IEnumerable<DataValue> LiveQuery(LogItemSchema schema, CancellationToken token) { throw new NotImplementedException(); } } }
AirSim/LogViewer/LogViewer/Model/KmlDataLog.cs/0
{ "file_path": "AirSim/LogViewer/LogViewer/Model/KmlDataLog.cs", "repo_id": "AirSim", "token_count": 5339 }
23
// Copyright (c) 2010 Microsoft Corporation. All rights reserved. // // // Use of this source code is subject to the terms of the Microsoft // license agreement under which you licensed this source code. // If you did not accept the terms of the license agreement, // you are not authorized to use this source code. // For the terms of the license, please see the license agreement // signed by you and Microsoft. // THE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES. // using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Xml.Serialization; namespace Microsoft.Storage { /// <summary> /// Isolated storage file helper class /// </summary> /// <typeparam name="T">Data type to serialize/deserialize</typeparam> public class IsolatedStorage<T> { Dictionary<string, int> locks = new Dictionary<string, int>(); public IsolatedStorage() { } class FileLock : IDisposable { Dictionary<string, int> locks; string key ; public FileLock(Dictionary<string, int> locks, string path) { this.locks = locks; this.key = path; } public void Dispose() { lock (this.locks) { this.locks.Remove(this.key); } } } private IDisposable EnterLock(string path) { lock (locks) { int value = 0; if (locks.TryGetValue(path, out value)) { throw new Exception(string.Format("Re-entrant access to file: {0}", path)); } else { locks[path] = 1; } return new FileLock(locks, path); } } /// <summary> /// Loads data from a file asynchronously. /// </summary> /// <param name="folder">The folder to get the file from</param> /// <param name="fileName">Name of the file to read.</param> /// <returns>Deserialized data object</returns> public async Task<T> LoadFromFileAsync(string folder, string fileName) { T loadedFile = default(T); string fullPath = Path.Combine(folder, fileName); using (var l = EnterLock(fullPath)) { try { if (fullPath != null) { Debug.WriteLine("Loading file: {0}", fullPath); await Task.Run(() => { using (Stream myFileStream = File.OpenRead(fullPath)) { // Call the Deserialize method and cast to the object type. loadedFile = LoadFromStream(myFileStream); } }); } } catch { // silently rebuild data file if it got corrupted. } } return loadedFile; } public T LoadFromStream(Stream s) { // Call the Deserialize method and cast to the object type. XmlSerializer mySerializer = new XmlSerializer(typeof(T)); return (T)mySerializer.Deserialize(s); } /// <summary> /// Saves data to a file. /// </summary> /// <param name="fileName">Name of the file to write to</param> /// <param name="data">The data to save</param> public async Task SaveToFileAsync(string folder, string fileName, T data) { string path = System.IO.Path.Combine(folder, fileName); using (var l = EnterLock(path)) { try { await Task.Run(() => { using (var stream = File.Create(path)) { XmlSerializer mySerializer = new XmlSerializer(typeof(T)); mySerializer.Serialize(stream, data); } }); } catch (Exception ex) { Debug.WriteLine("### SaveToFileAsync failed: {0}", ex.Message); } } } } }
AirSim/LogViewer/LogViewer/Utilities/IsolatedStorage.cs/0
{ "file_path": "AirSim/LogViewer/LogViewer/Utilities/IsolatedStorage.cs", "repo_id": "AirSim", "token_count": 2423 }
24
using System; using Microsoft.Networking.Mavlink; using System.Threading.Tasks; using System.Threading; using System.Management; using System.Collections.Generic; using System.Text; namespace Microsoft.Networking { public class SerialPort : IPort { System.IO.Ports.SerialPort port; public void Connect(string portName, int baudRate) { Close(); port = new System.IO.Ports.SerialPort(); port.PortName = portName; port.BaudRate = baudRate; port.Open(); // initialize mavlink. port.Write("sh /etc/init.d/rc.usb\n"); } public string Name { get; set; } public string Id { get; set; } public void Write(byte[] buffer, int count) { port.Write(buffer, 0, count); } public void Write(string msg) { byte[] buffer = Encoding.UTF8.GetBytes(msg); Write(buffer, buffer.Length); } public int Read(byte[] buffer, int bytesToRead) { if (port == null) { return 0; } return port.Read(buffer, 0, bytesToRead); } public override string ToString() { return this.Name; } public static async Task<IEnumerable<SerialPort>> FindPorts() { List<SerialPort> ports = new List<Networking.SerialPort>(); await Task.Run(() => { ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_SerialPort"); // Win32_USBControllerDevice using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) { foreach (ManagementObject obj2 in searcher.Get()) { //DeviceID string id = obj2.Properties["DeviceID"].Value.ToString(); string name = obj2.Properties["Name"].Value.ToString(); ports.Add(new SerialPort() { Id = id, Name = name }); } } }); return ports; } public void Close() { if (port != null) { port.Close(); port = null; } } } }
AirSim/LogViewer/Networking/SerialPort.cs/0
{ "file_path": "AirSim/LogViewer/Networking/SerialPort.cs", "repo_id": "AirSim", "token_count": 1248 }
25
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="16.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), AirSim.props))\AirSim.props" /> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{9E9D74CE-235C-4A96-BFED-A3E9AC8D9039}</ProjectGuid> <Keyword>Win32Proj</Keyword> <RootNamespace>MavlinkMoCap</RootNamespace> <ProjectName>MavLinkMoCap</ProjectName> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v141</PlatformToolset> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v141</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v141</PlatformToolset> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v141</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="Shared"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;STATIC_RB_LINK;%(PreprocessorDefinitions)</PreprocessorDefinitions> <SDLCheck>false</SDLCheck> <AdditionalIncludeDirectories>../MavLinkCom;$(NPTRACKINGTOOLS_INC);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>$(NPTRACKINGTOOLS_LIB);</AdditionalLibraryDirectories> <AdditionalDependencies>NPTrackingTools.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> <PostBuildEvent> <Command>copy "$(NPTRACKINGTOOLS_LIB)\NPTrackingTools.dll" "$(OutDir)"</Command> </PostBuildEvent> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>_DEBUG;_CONSOLE;STATIC_RB_LINK;%(PreprocessorDefinitions)</PreprocessorDefinitions> <SDLCheck>false</SDLCheck> <AdditionalIncludeDirectories>../MavLinkCom;$(NPTRACKINGTOOLS_INC);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>$(NPTRACKINGTOOLS_LIB);</AdditionalLibraryDirectories> <AdditionalDependencies>NPTrackingToolsx64.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> <PostBuildEvent> <Command>copy "$(NPTRACKINGTOOLS_LIB)\NPTrackingToolsx64.dll" "$(OutDir)"</Command> </PostBuildEvent> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <PrecompiledHeader> </PrecompiledHeader> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;STATIC_RB_LINK;%(PreprocessorDefinitions)</PreprocessorDefinitions> <SDLCheck>false</SDLCheck> <AdditionalIncludeDirectories>../MavLinkCom;$(NPTRACKINGTOOLS_INC);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> </ClCompile> <Link> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>$(NPTRACKINGTOOLS_LIB);</AdditionalLibraryDirectories> <AdditionalDependencies>NPTrackingTools.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> <PostBuildEvent> <Command>copy "$(NPTRACKINGTOOLS_LIB)\NPTrackingTools.dll" "$(OutDir)"</Command> </PostBuildEvent> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <PrecompiledHeader> </PrecompiledHeader> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>NDEBUG;_CONSOLE;STATIC_RB_LINK;%(PreprocessorDefinitions)</PreprocessorDefinitions> <SDLCheck>false</SDLCheck> <AdditionalIncludeDirectories>../MavLinkCom;$(NPTRACKINGTOOLS_INC);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> </ClCompile> <Link> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>$(NPTRACKINGTOOLS_LIB);</AdditionalLibraryDirectories> <AdditionalDependencies>NPTrackingToolsx64.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> <PostBuildEvent> <Command>copy "$(NPTRACKINGTOOLS_LIB)\NPTrackingToolsx64.dll" "$(OutDir)"</Command> </PostBuildEvent> </ItemDefinitionGroup> <ItemGroup> <Text Include="ReadMe.txt" /> </ItemGroup> <ItemGroup> <ClInclude Include="stdafx.h" /> <ClInclude Include="targetver.h" /> </ItemGroup> <ItemGroup> <ClCompile Include="MavlinkMoCap.cpp" /> <ClCompile Include="stdafx.cpp" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\MavLinkCom.vcxproj"> <Project>{8510c7a4-bf63-41d2-94f6-d8731d137a5a}</Project> </ProjectReference> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
AirSim/MavLinkCom/MavLinkMoCap/MavLinkMoCap.vcxproj/0
{ "file_path": "AirSim/MavLinkCom/MavLinkMoCap/MavLinkMoCap.vcxproj", "repo_id": "AirSim", "token_count": 3470 }
26
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <string> #include <functional> #include "MavLinkFtpClient.hpp" typedef std::function<void()> TestHandler; class ImageServer; class UnitTests { public: void RunAll(std::string comPort, int boardRate); void SerialPx4Test(); void UdpPingTest(); void TcpPingTest(); void SendImageTest(); void FtpTest(); void JSonLogTest(); private: void RunTest(const std::string& name, TestHandler handler); void VerifyFile(mavlinkcom::MavLinkFtpClient& ftp, const std::string& dir, const std::string& name, bool exists, bool isdir); ImageServer* server_; std::string com_port_; int baud_rate_; };
AirSim/MavLinkCom/MavLinkTest/UnitTests.h/0
{ "file_path": "AirSim/MavLinkCom/MavLinkTest/UnitTests.h", "repo_id": "AirSim", "token_count": 264 }
27
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef commn_utils_sincos_hpp #define commn_utils_sincos_hpp #include <cmath> /* GCC seem to define sincos already. However there is a bug currently which causes compiler to optimise sequence of sin cos call in to sincos function which in above case would result in infinite recursion hence we define above only for VC++ for now. http://man7.org/linux/man-pages/man3/sincos.3.html https://android.googlesource.com/platform/bionic/+/master/libm/sincos.c */ #ifdef _MSC_VER //GNU/Linux compilers have these functions //inline here is forced and is hack. Ideally these definitions needs to be in cpp file. http://stackoverflow.com/a/6469881/207661 inline void sincos(double x, double* p_sin, double* p_cos) { *p_sin = sin(x); *p_cos = cos(x); } inline void sincosf(float x, float* p_sinf, float* p_cosf) { *p_sinf = sinf(x); *p_cosf = cosf(x); } inline void sincosl(long double x, long double* p_sinl, long double* p_cosl) { *p_sinl = sinl(x); *p_cosl = cosl(x); } #endif #endif
AirSim/MavLinkCom/common_utils/sincos.hpp/0
{ "file_path": "AirSim/MavLinkCom/common_utils/sincos.hpp", "repo_id": "AirSim", "token_count": 413 }
28
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef MavLinkCom_VehicleState_hpp #define MavLinkCom_VehicleState_hpp #include <vector> #include <string> namespace mavlinkcom { typedef struct _VehicleState { typedef unsigned long long uint64_t; typedef unsigned char uint8_t; struct GlobalPosition { float lat = 0, lon = 0, alt = 0; }; struct Vector3 { float x = 0, y = 0, z = 0; // in NED (north, east, down) coordinates }; struct LocalPose { Vector3 pos; // in NEU (north, east, down) coordinates float q[4] = { 0 }; //qauternion }; struct AttitudeState { float roll = 0, pitch = 0, yaw = 0, roll_rate = 0, yaw_rate = 0, pitch_rate = 0; uint64_t updated_on = 0; } attitude; struct GlobalState { GlobalPosition pos; Vector3 vel; int alt_ground = 0; float heading = 0; uint64_t updated_on = 0; } global_est; struct RCState { int16_t rc_channels_scaled[16] = { 0 }; unsigned char rc_channels_count = 0; unsigned char rc_signal_strength = 0; uint64_t updated_on = 0; } rc; struct ServoState { unsigned int servo_raw[8] = { 0 }; unsigned char servo_port = 0; uint64_t updated_on = 0; } servo; struct ControlState { float actuator_controls[16] = { 0 }; unsigned char actuator_mode = 0, actuator_nav_mode = 0; bool landed = 0; bool armed = false; bool offboard = false; uint64_t updated_on = 0; } controls; struct LocalState { Vector3 pos; // in NEU (north, east, up) coordinates (positive Z goes upwards). Vector3 lin_vel; Vector3 acc; uint64_t updated_on; } local_est; struct MocapState { LocalPose pose; uint64_t updated_on = 0; } mocap; struct AltitudeState { uint64_t updated_on = 0; float altitude_monotonic = 0, altitude_amsl = 0, altitude_terrain = 0; float altitude_local = 0, altitude_relative = 0, bottom_clearance = 0; } altitude; struct VfrHud { float true_airspeed = 0; // in m/s float groundspeed = 0; // in m/s float altitude = 0; // MSL altitude in meters float climb_rate = 0; // in m/s int16_t heading = 0; // in degrees w.r.t. north uint16_t throttle = 0; // in percent, 0 to 100 } vfrhud; struct HomeState { GlobalPosition global_pos; LocalPose local_pose; Vector3 approach; // in NEU (north, east, up) coordinates (positive Z goes upwards). bool is_set = false; } home; struct Stats { //mainly for debugging purposes int last_read_msg_id = 0; uint64_t last_read_msg_time = 0; int last_write_msg_id = 0; uint64_t last_write_msg_time = 0; std::string debug_msg; } stats; int mode = 0; // MAV_MODE_FLAG } VehicleState; } #endif
AirSim/MavLinkCom/include/VehicleState.hpp/0
{ "file_path": "AirSim/MavLinkCom/include/VehicleState.hpp", "repo_id": "AirSim", "token_count": 1375 }
29
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "MavLinkLog.hpp" #include "Utils.hpp" #include <chrono> using namespace mavlinkcom; using namespace mavlink_utils; #define MAVLINK_STX_MAVLINK1 0xFE // marker for old protocol #define MAVLINK_STX 253 // marker for mavlink 2 uint64_t MavLinkFileLog::getTimeStamp() { return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count(); } MavLinkFileLog::MavLinkFileLog() { ptr_ = nullptr; reading_ = false; writing_ = false; json_ = false; } MavLinkFileLog::~MavLinkFileLog() { close(); } bool MavLinkFileLog::isOpen() { return reading_ || writing_; } void MavLinkFileLog::openForReading(const std::string& filename) { close(); file_name_ = filename; ptr_ = fopen(filename.c_str(), "rb"); if (ptr_ == nullptr) { throw std::runtime_error(Utils::stringf("Could not open the file %s, error=%d", filename.c_str(), errno)); } fseek(ptr_, 0, SEEK_SET); reading_ = true; writing_ = false; } void MavLinkFileLog::openForWriting(const std::string& filename, bool json) { close(); json_ = json; file_name_ = filename; ptr_ = fopen(filename.c_str(), "wb"); if (ptr_ == nullptr) { throw std::runtime_error(Utils::stringf("Could not open the file %s, error=%d", filename.c_str(), errno)); } if (json) { fprintf(ptr_, "{ \"rows\": [\n"); } reading_ = false; writing_ = true; } void MavLinkFileLog::close() { FILE* temp = ptr_; if (json_ && ptr_ != nullptr) { fprintf(ptr_, " {}\n"); // so that trailing comma on last row isn't a problem. fprintf(ptr_, "]}\n"); } ptr_ = nullptr; if (temp != nullptr) { fclose(temp); } reading_ = false; writing_ = false; } uint64_t FlipEndianness(uint64_t v) { uint64_t result = 0; uint64_t shift = v; const int size = sizeof(uint64_t); for (int i = 0; i < size; i++) { uint64_t low = (shift & 0xff); result = (result << 8) + low; shift >>= 8; } return result; } void MavLinkFileLog::write(const mavlinkcom::MavLinkMessage& msg, uint64_t timestamp) { if (ptr_ != nullptr) { if (reading_) { throw std::runtime_error("Log file was opened for reading"); } if (json_) { MavLinkMessageBase* strongTypedMsg = MavLinkMessageBase::lookup(msg); if (strongTypedMsg != nullptr) { strongTypedMsg->timestamp = timestamp; std::string line = strongTypedMsg->toJSon(); { std::lock_guard<std::mutex> lock(log_lock_); fprintf(ptr_, " %s\n", line.c_str()); } delete strongTypedMsg; } } else { if (timestamp == 0) { timestamp = getTimeStamp(); } // for compatibility with QGroundControl we have to save the time field in big endian. // todo: mavlink2 support? timestamp = FlipEndianness(timestamp); uint8_t magic = msg.magic; if (magic != MAVLINK_STX_MAVLINK1) { // has to be one or the other! magic = MAVLINK_STX; } std::lock_guard<std::mutex> lock(log_lock_); fwrite(&timestamp, sizeof(uint64_t), 1, ptr_); fwrite(&magic, 1, 1, ptr_); fwrite(&msg.len, 1, 1, ptr_); fwrite(&msg.seq, 1, 1, ptr_); fwrite(&msg.sysid, 1, 1, ptr_); fwrite(&msg.compid, 1, 1, ptr_); if (magic == MAVLINK_STX_MAVLINK1) { uint8_t msgid = msg.msgid & 0xff; // truncate to mavlink 2 msgid fwrite(&msgid, 1, 1, ptr_); } else { // 24 bits. uint8_t msgid = msg.msgid & 0xFF; fwrite(&msgid, 1, 1, ptr_); msgid = (msg.msgid >> 8) & 0xFF; fwrite(&msgid, 1, 1, ptr_); msgid = (msg.msgid >> 16) & 0xFF; fwrite(&msgid, 1, 1, ptr_); } fwrite(&msg.payload64, 1, msg.len, ptr_); fwrite(&msg.checksum, sizeof(uint16_t), 1, ptr_); } } } bool MavLinkFileLog::read(mavlinkcom::MavLinkMessage& msg, uint64_t& timestamp) { if (ptr_ != nullptr) { if (writing_) { throw std::runtime_error("Log file was opened for writing"); } uint64_t time; size_t s = fread(&time, 1, sizeof(uint64_t), ptr_); if (s < sizeof(uint64_t)) { int hr = errno; return false; } timestamp = FlipEndianness(time); s = fread(&msg.magic, 1, 1, ptr_); if (s == 0) { return false; } s = fread(&msg.len, 1, 1, ptr_); if (s == 0) { return false; } s = fread(&msg.seq, 1, 1, ptr_); if (s == 0) { return false; } s = fread(&msg.sysid, 1, 1, ptr_); if (s == 0) { return false; } s = fread(&msg.compid, 1, 1, ptr_); if (s == 0) { return false; } if (msg.magic == MAVLINK_STX_MAVLINK1) { uint8_t msgid = 0; s = fread(&msgid, 1, 1, ptr_); msg.msgid = msgid; } else { // 24 bits. uint8_t msgid = 0; s = fread(&msgid, 1, 1, ptr_); msg.msgid = msgid; s = fread(&msgid, 1, 1, ptr_); msg.msgid |= (msgid << 8); s = fread(&msgid, 1, 1, ptr_); msg.msgid |= (msgid << 16); } if (s < 1) { return false; } s = fread(&msg.payload64, 1, msg.len, ptr_); if (s < msg.len) { return false; } s = fread(&msg.checksum, 1, sizeof(uint16_t), ptr_); if (s < sizeof(uint16_t)) { return false; } return true; } return false; }
AirSim/MavLinkCom/src/MavLinkLog.cpp/0
{ "file_path": "AirSim/MavLinkCom/src/MavLinkLog.cpp", "repo_id": "AirSim", "token_count": 3216 }
30
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef MavLinkCom_MavLinkNodeImpl_hpp #define MavLinkCom_MavLinkNodeImpl_hpp #include "MavLinkNode.hpp" #include "MavLinkConnection.hpp" using namespace mavlinkcom; namespace mavlinkcom_impl { class MavLinkNodeImpl { public: MavLinkNodeImpl(int localSystemId, int localComponentId); virtual ~MavLinkNodeImpl(); void connect(std::shared_ptr<MavLinkConnection> connection); void close(); // Send heartbeat to drone. You should not do this if some other node is // already doing it. void startHeartbeat(); std::vector<MavLinkParameter> getParamList(); // get the parameter value cached from last getParamList call. MavLinkParameter getCachedParameter(const std::string& name); // get up to date value of this parametr AsyncResult<MavLinkParameter> getParameter(const std::string& name); AsyncResult<bool> setParameter(MavLinkParameter p); AsyncResult<MavLinkAutopilotVersion> getCapabilities(); // get the connection std::shared_ptr<MavLinkConnection> getConnection() { return connection_; } std::shared_ptr<MavLinkConnection> ensureConnection() { if (connection_ == nullptr) { throw std::runtime_error("Cannot perform operation as there is no connection, did you forget to call connect() ?"); } return connection_; } int getLocalSystemId() { return local_system_id; } int getLocalComponentId() { return local_component_id; } int getTargetSystemId() { return ensureConnection()->getTargetSystemId(); } int getTargetComponentId() { return ensureConnection()->getTargetComponentId(); } void setMessageInterval(int msgId, int frequency); AsyncResult<MavLinkHeartbeat> waitForHeartbeat(); void sendOneHeartbeat(); // Encode and send the given message to the connected node void sendMessage(MavLinkMessageBase& msg); // Send an already encoded messge to connected node void sendMessage(MavLinkMessage& msg); // send a command to the remote node void sendCommand(MavLinkCommand& cmd); // send a command to the remote node and return async result that tells you whether ACK was received or not. AsyncResult<bool> sendCommandAndWaitForAck(MavLinkCommand& cmd); protected: // this is called for all messages received on the connection. virtual void handleMessage(std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& message); void assertNotPublishingThread(); private: void sendHeartbeat(); AsyncResult<MavLinkParameter> getParameterByIndex(int16_t index); bool inside_handle_message_; std::shared_ptr<MavLinkConnection> connection_; int subscription_ = 0; int local_system_id; int local_component_id; std::vector<MavLinkParameter> parameters_; //cached snapshot. MavLinkAutopilotVersion cap_; bool has_cap_ = false; bool req_cap_ = false; bool heartbeat_running_ = false; std::thread heartbeat_thread_; }; } #endif
AirSim/MavLinkCom/src/impl/MavLinkNodeImpl.hpp/0
{ "file_path": "AirSim/MavLinkCom/src/impl/MavLinkNodeImpl.hpp", "repo_id": "AirSim", "token_count": 1079 }
31
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef SERIAL_COM_SOCKETINIT_HPP #define SERIAL_COM_SOCKETINIT_HPP class SocketInit { static bool socket_initialized_; public: SocketInit(); }; #endif
AirSim/MavLinkCom/src/serial_com/SocketInit.hpp/0
{ "file_path": "AirSim/MavLinkCom/src/serial_com/SocketInit.hpp", "repo_id": "AirSim", "token_count": 90 }
32
from __future__ import print_function import msgpackrpc #install as admin: pip install msgpack-rpc-python import numpy as np #pip install numpy import math class MsgpackMixin: def __repr__(self): from pprint import pformat return "<" + type(self).__name__ + "> " + pformat(vars(self), indent=4, width=1) def to_msgpack(self, *args, **kwargs): return self.__dict__ @classmethod def from_msgpack(cls, encoded): obj = cls() #obj.__dict__ = {k.decode('utf-8'): (from_msgpack(v.__class__, v) if hasattr(v, "__dict__") else v) for k, v in encoded.items()} obj.__dict__ = { k : (v if not isinstance(v, dict) else getattr(getattr(obj, k).__class__, "from_msgpack")(v)) for k, v in encoded.items()} #return cls(**msgpack.unpack(encoded)) return obj class _ImageType(type): @property def Scene(cls): return 0 def DepthPlanar(cls): return 1 def DepthPerspective(cls): return 2 def DepthVis(cls): return 3 def DisparityNormalized(cls): return 4 def Segmentation(cls): return 5 def SurfaceNormals(cls): return 6 def Infrared(cls): return 7 def OpticalFlow(cls): return 8 def OpticalFlowVis(cls): return 9 def __getattr__(self, key): if key == 'DepthPlanner': print('\033[31m'+"DepthPlanner has been (correctly) renamed to DepthPlanar. Please use ImageType.DepthPlanar instead."+'\033[0m') raise AttributeError class ImageType(metaclass=_ImageType): Scene = 0 DepthPlanar = 1 DepthPerspective = 2 DepthVis = 3 DisparityNormalized = 4 Segmentation = 5 SurfaceNormals = 6 Infrared = 7 OpticalFlow = 8 OpticalFlowVis = 9 class DrivetrainType: MaxDegreeOfFreedom = 0 ForwardOnly = 1 class LandedState: Landed = 0 Flying = 1 class WeatherParameter: Rain = 0 Roadwetness = 1 Snow = 2 RoadSnow = 3 MapleLeaf = 4 RoadLeaf = 5 Dust = 6 Fog = 7 Enabled = 8 class Vector2r(MsgpackMixin): x_val = 0.0 y_val = 0.0 def __init__(self, x_val = 0.0, y_val = 0.0): self.x_val = x_val self.y_val = y_val class Vector3r(MsgpackMixin): x_val = 0.0 y_val = 0.0 z_val = 0.0 def __init__(self, x_val = 0.0, y_val = 0.0, z_val = 0.0): self.x_val = x_val self.y_val = y_val self.z_val = z_val @staticmethod def nanVector3r(): return Vector3r(np.nan, np.nan, np.nan) def containsNan(self): return (math.isnan(self.x_val) or math.isnan(self.y_val) or math.isnan(self.z_val)) def __add__(self, other): return Vector3r(self.x_val + other.x_val, self.y_val + other.y_val, self.z_val + other.z_val) def __sub__(self, other): return Vector3r(self.x_val - other.x_val, self.y_val - other.y_val, self.z_val - other.z_val) def __truediv__(self, other): if type(other) in [int, float] + np.sctypes['int'] + np.sctypes['uint'] + np.sctypes['float']: return Vector3r( self.x_val / other, self.y_val / other, self.z_val / other) else: raise TypeError('unsupported operand type(s) for /: %s and %s' % ( str(type(self)), str(type(other))) ) def __mul__(self, other): if type(other) in [int, float] + np.sctypes['int'] + np.sctypes['uint'] + np.sctypes['float']: return Vector3r(self.x_val*other, self.y_val*other, self.z_val*other) else: raise TypeError('unsupported operand type(s) for *: %s and %s' % ( str(type(self)), str(type(other))) ) def dot(self, other): if type(self) == type(other): return self.x_val*other.x_val + self.y_val*other.y_val + self.z_val*other.z_val else: raise TypeError('unsupported operand type(s) for \'dot\': %s and %s' % ( str(type(self)), str(type(other))) ) def cross(self, other): if type(self) == type(other): cross_product = np.cross(self.to_numpy_array(), other.to_numpy_array()) return Vector3r(cross_product[0], cross_product[1], cross_product[2]) else: raise TypeError('unsupported operand type(s) for \'cross\': %s and %s' % ( str(type(self)), str(type(other))) ) def get_length(self): return ( self.x_val**2 + self.y_val**2 + self.z_val**2 )**0.5 def distance_to(self, other): return ( (self.x_val-other.x_val)**2 + (self.y_val-other.y_val)**2 + (self.z_val-other.z_val)**2 )**0.5 def to_Quaternionr(self): return Quaternionr(self.x_val, self.y_val, self.z_val, 0) def to_numpy_array(self): return np.array([self.x_val, self.y_val, self.z_val], dtype=np.float32) def __iter__(self): return iter((self.x_val, self.y_val, self.z_val)) class Quaternionr(MsgpackMixin): w_val = 0.0 x_val = 0.0 y_val = 0.0 z_val = 0.0 def __init__(self, x_val = 0.0, y_val = 0.0, z_val = 0.0, w_val = 1.0): self.x_val = x_val self.y_val = y_val self.z_val = z_val self.w_val = w_val @staticmethod def nanQuaternionr(): return Quaternionr(np.nan, np.nan, np.nan, np.nan) def containsNan(self): return (math.isnan(self.w_val) or math.isnan(self.x_val) or math.isnan(self.y_val) or math.isnan(self.z_val)) def __add__(self, other): if type(self) == type(other): return Quaternionr( self.x_val+other.x_val, self.y_val+other.y_val, self.z_val+other.z_val, self.w_val+other.w_val ) else: raise TypeError('unsupported operand type(s) for +: %s and %s' % ( str(type(self)), str(type(other))) ) def __mul__(self, other): if type(self) == type(other): t, x, y, z = self.w_val, self.x_val, self.y_val, self.z_val a, b, c, d = other.w_val, other.x_val, other.y_val, other.z_val return Quaternionr( w_val = a*t - b*x - c*y - d*z, x_val = b*t + a*x + d*y - c*z, y_val = c*t + a*y + b*z - d*x, z_val = d*t + z*a + c*x - b*y) else: raise TypeError('unsupported operand type(s) for *: %s and %s' % ( str(type(self)), str(type(other))) ) def __truediv__(self, other): if type(other) == type(self): return self * other.inverse() elif type(other) in [int, float] + np.sctypes['int'] + np.sctypes['uint'] + np.sctypes['float']: return Quaternionr( self.x_val / other, self.y_val / other, self.z_val / other, self.w_val / other) else: raise TypeError('unsupported operand type(s) for /: %s and %s' % ( str(type(self)), str(type(other))) ) def dot(self, other): if type(self) == type(other): return self.x_val*other.x_val + self.y_val*other.y_val + self.z_val*other.z_val + self.w_val*other.w_val else: raise TypeError('unsupported operand type(s) for \'dot\': %s and %s' % ( str(type(self)), str(type(other))) ) def cross(self, other): if type(self) == type(other): return (self * other - other * self) / 2 else: raise TypeError('unsupported operand type(s) for \'cross\': %s and %s' % ( str(type(self)), str(type(other))) ) def outer_product(self, other): if type(self) == type(other): return ( self.inverse()*other - other.inverse()*self ) / 2 else: raise TypeError('unsupported operand type(s) for \'outer_product\': %s and %s' % ( str(type(self)), str(type(other))) ) def rotate(self, other): if type(self) == type(other): if other.get_length() == 1: return other * self * other.inverse() else: raise ValueError('length of the other Quaternionr must be 1') else: raise TypeError('unsupported operand type(s) for \'rotate\': %s and %s' % ( str(type(self)), str(type(other))) ) def conjugate(self): return Quaternionr(-self.x_val, -self.y_val, -self.z_val, self.w_val) def star(self): return self.conjugate() def inverse(self): return self.star() / self.dot(self) def sgn(self): return self/self.get_length() def get_length(self): return ( self.x_val**2 + self.y_val**2 + self.z_val**2 + self.w_val**2 )**0.5 def to_numpy_array(self): return np.array([self.x_val, self.y_val, self.z_val, self.w_val], dtype=np.float32) def __iter__(self): return iter((self.x_val, self.y_val, self.z_val, self.w_val)) class Pose(MsgpackMixin): position = Vector3r() orientation = Quaternionr() def __init__(self, position_val = None, orientation_val = None): position_val = position_val if position_val is not None else Vector3r() orientation_val = orientation_val if orientation_val is not None else Quaternionr() self.position = position_val self.orientation = orientation_val @staticmethod def nanPose(): return Pose(Vector3r.nanVector3r(), Quaternionr.nanQuaternionr()) def containsNan(self): return (self.position.containsNan() or self.orientation.containsNan()) def __iter__(self): return iter((self.position, self.orientation)) class CollisionInfo(MsgpackMixin): has_collided = False normal = Vector3r() impact_point = Vector3r() position = Vector3r() penetration_depth = 0.0 time_stamp = 0.0 object_name = "" object_id = -1 class GeoPoint(MsgpackMixin): latitude = 0.0 longitude = 0.0 altitude = 0.0 class YawMode(MsgpackMixin): is_rate = True yaw_or_rate = 0.0 def __init__(self, is_rate = True, yaw_or_rate = 0.0): self.is_rate = is_rate self.yaw_or_rate = yaw_or_rate class RCData(MsgpackMixin): timestamp = 0 pitch, roll, throttle, yaw = (0.0,)*4 #init 4 variable to 0.0 switch1, switch2, switch3, switch4 = (0,)*4 switch5, switch6, switch7, switch8 = (0,)*4 is_initialized = False is_valid = False def __init__(self, timestamp = 0, pitch = 0.0, roll = 0.0, throttle = 0.0, yaw = 0.0, switch1 = 0, switch2 = 0, switch3 = 0, switch4 = 0, switch5 = 0, switch6 = 0, switch7 = 0, switch8 = 0, is_initialized = False, is_valid = False): self.timestamp = timestamp self.pitch = pitch self.roll = roll self.throttle = throttle self.yaw = yaw self.switch1 = switch1 self.switch2 = switch2 self.switch3 = switch3 self.switch4 = switch4 self.switch5 = switch5 self.switch6 = switch6 self.switch7 = switch7 self.switch8 = switch8 self.is_initialized = is_initialized self.is_valid = is_valid class ImageRequest(MsgpackMixin): camera_name = '0' image_type = ImageType.Scene pixels_as_float = False compress = False def __init__(self, camera_name, image_type, pixels_as_float = False, compress = True): # todo: in future remove str(), it's only for compatibility to pre v1.2 self.camera_name = str(camera_name) self.image_type = image_type self.pixels_as_float = pixels_as_float self.compress = compress class ImageResponse(MsgpackMixin): image_data_uint8 = np.uint8(0) image_data_float = 0.0 camera_position = Vector3r() camera_orientation = Quaternionr() time_stamp = np.uint64(0) message = '' pixels_as_float = 0.0 compress = True width = 0 height = 0 image_type = ImageType.Scene class CarControls(MsgpackMixin): throttle = 0.0 steering = 0.0 brake = 0.0 handbrake = False is_manual_gear = False manual_gear = 0 gear_immediate = True def __init__(self, throttle = 0, steering = 0, brake = 0, handbrake = False, is_manual_gear = False, manual_gear = 0, gear_immediate = True): self.throttle = throttle self.steering = steering self.brake = brake self.handbrake = handbrake self.is_manual_gear = is_manual_gear self.manual_gear = manual_gear self.gear_immediate = gear_immediate def set_throttle(self, throttle_val, forward): if (forward): self.is_manual_gear = False self.manual_gear = 0 self.throttle = abs(throttle_val) else: self.is_manual_gear = False self.manual_gear = -1 self.throttle = - abs(throttle_val) class KinematicsState(MsgpackMixin): position = Vector3r() orientation = Quaternionr() linear_velocity = Vector3r() angular_velocity = Vector3r() linear_acceleration = Vector3r() angular_acceleration = Vector3r() class EnvironmentState(MsgpackMixin): position = Vector3r() geo_point = GeoPoint() gravity = Vector3r() air_pressure = 0.0 temperature = 0.0 air_density = 0.0 class CarState(MsgpackMixin): speed = 0.0 gear = 0 rpm = 0.0 maxrpm = 0.0 handbrake = False collision = CollisionInfo() kinematics_estimated = KinematicsState() timestamp = np.uint64(0) class MultirotorState(MsgpackMixin): collision = CollisionInfo() kinematics_estimated = KinematicsState() gps_location = GeoPoint() timestamp = np.uint64(0) landed_state = LandedState.Landed rc_data = RCData() ready = False ready_message = "" can_arm = False class RotorStates(MsgpackMixin): timestamp = np.uint64(0) rotors = [] class ProjectionMatrix(MsgpackMixin): matrix = [] class CameraInfo(MsgpackMixin): pose = Pose() fov = -1 proj_mat = ProjectionMatrix() class LidarData(MsgpackMixin): point_cloud = 0.0 time_stamp = np.uint64(0) pose = Pose() segmentation = 0 class ImuData(MsgpackMixin): time_stamp = np.uint64(0) orientation = Quaternionr() angular_velocity = Vector3r() linear_acceleration = Vector3r() class BarometerData(MsgpackMixin): time_stamp = np.uint64(0) altitude = Quaternionr() pressure = Vector3r() qnh = Vector3r() class MagnetometerData(MsgpackMixin): time_stamp = np.uint64(0) magnetic_field_body = Vector3r() magnetic_field_covariance = 0.0 class GnssFixType(MsgpackMixin): GNSS_FIX_NO_FIX = 0 GNSS_FIX_TIME_ONLY = 1 GNSS_FIX_2D_FIX = 2 GNSS_FIX_3D_FIX = 3 class GnssReport(MsgpackMixin): geo_point = GeoPoint() eph = 0.0 epv = 0.0 velocity = Vector3r() fix_type = GnssFixType() time_utc = np.uint64(0) class GpsData(MsgpackMixin): time_stamp = np.uint64(0) gnss = GnssReport() is_valid = False class DistanceSensorData(MsgpackMixin): time_stamp = np.uint64(0) distance = 0.0 min_distance = 0.0 max_distance = 0.0 relative_pose = Pose() class Box2D(MsgpackMixin): min = Vector2r() max = Vector2r() class Box3D(MsgpackMixin): min = Vector3r() max = Vector3r() class DetectionInfo(MsgpackMixin): name = '' geo_point = GeoPoint() box2D = Box2D() box3D = Box3D() relative_pose = Pose() class PIDGains(): """ Struct to store values of PID gains. Used to transmit controller gain values while instantiating AngleLevel/AngleRate/Velocity/PositionControllerGains objects. Attributes: kP (float): Proportional gain kI (float): Integrator gain kD (float): Derivative gain """ def __init__(self, kp, ki, kd): self.kp = kp self.ki = ki self.kd = kd def to_list(self): return [self.kp, self.ki, self.kd] class AngleRateControllerGains(): """ Struct to contain controller gains used by angle level PID controller Attributes: roll_gains (PIDGains): kP, kI, kD for roll axis pitch_gains (PIDGains): kP, kI, kD for pitch axis yaw_gains (PIDGains): kP, kI, kD for yaw axis """ def __init__(self, roll_gains = PIDGains(0.25, 0, 0), pitch_gains = PIDGains(0.25, 0, 0), yaw_gains = PIDGains(0.25, 0, 0)): self.roll_gains = roll_gains self.pitch_gains = pitch_gains self.yaw_gains = yaw_gains def to_lists(self): return [self.roll_gains.kp, self.pitch_gains.kp, self.yaw_gains.kp], [self.roll_gains.ki, self.pitch_gains.ki, self.yaw_gains.ki], [self.roll_gains.kd, self.pitch_gains.kd, self.yaw_gains.kd] class AngleLevelControllerGains(): """ Struct to contain controller gains used by angle rate PID controller Attributes: roll_gains (PIDGains): kP, kI, kD for roll axis pitch_gains (PIDGains): kP, kI, kD for pitch axis yaw_gains (PIDGains): kP, kI, kD for yaw axis """ def __init__(self, roll_gains = PIDGains(2.5, 0, 0), pitch_gains = PIDGains(2.5, 0, 0), yaw_gains = PIDGains(2.5, 0, 0)): self.roll_gains = roll_gains self.pitch_gains = pitch_gains self.yaw_gains = yaw_gains def to_lists(self): return [self.roll_gains.kp, self.pitch_gains.kp, self.yaw_gains.kp], [self.roll_gains.ki, self.pitch_gains.ki, self.yaw_gains.ki], [self.roll_gains.kd, self.pitch_gains.kd, self.yaw_gains.kd] class VelocityControllerGains(): """ Struct to contain controller gains used by velocity PID controller Attributes: x_gains (PIDGains): kP, kI, kD for X axis y_gains (PIDGains): kP, kI, kD for Y axis z_gains (PIDGains): kP, kI, kD for Z axis """ def __init__(self, x_gains = PIDGains(0.2, 0, 0), y_gains = PIDGains(0.2, 0, 0), z_gains = PIDGains(2.0, 2.0, 0)): self.x_gains = x_gains self.y_gains = y_gains self.z_gains = z_gains def to_lists(self): return [self.x_gains.kp, self.y_gains.kp, self.z_gains.kp], [self.x_gains.ki, self.y_gains.ki, self.z_gains.ki], [self.x_gains.kd, self.y_gains.kd, self.z_gains.kd] class PositionControllerGains(): """ Struct to contain controller gains used by position PID controller Attributes: x_gains (PIDGains): kP, kI, kD for X axis y_gains (PIDGains): kP, kI, kD for Y axis z_gains (PIDGains): kP, kI, kD for Z axis """ def __init__(self, x_gains = PIDGains(0.25, 0, 0), y_gains = PIDGains(0.25, 0, 0), z_gains = PIDGains(0.25, 0, 0)): self.x_gains = x_gains self.y_gains = y_gains self.z_gains = z_gains def to_lists(self): return [self.x_gains.kp, self.y_gains.kp, self.z_gains.kp], [self.x_gains.ki, self.y_gains.ki, self.z_gains.ki], [self.x_gains.kd, self.y_gains.kd, self.z_gains.kd] class MeshPositionVertexBuffersResponse(MsgpackMixin): position = Vector3r() orientation = Quaternionr() vertices = 0.0 indices = 0.0 name = ''
AirSim/PythonClient/airsim/types.py/0
{ "file_path": "AirSim/PythonClient/airsim/types.py", "repo_id": "AirSim", "token_count": 8825 }
33
# Import this module to automatically setup path to local airsim module # This module first tries to see if airsim module is installed via pip # If it does then we don't do anything else # Else we look up grand-parent folder to see if it has airsim folder # and if it does then we add that in sys.path import os,sys,inspect,logging #this class simply tries to see if airsim class SetupPath: @staticmethod def getDirLevels(path): path_norm = os.path.normpath(path) return len(path_norm.split(os.sep)) @staticmethod def getCurrentPath(): cur_filepath = os.path.abspath(inspect.getfile(inspect.currentframe())) return os.path.dirname(cur_filepath) @staticmethod def getGrandParentDir(): cur_path = SetupPath.getCurrentPath() if SetupPath.getDirLevels(cur_path) >= 2: return os.path.dirname(os.path.dirname(cur_path)) return '' @staticmethod def getParentDir(): cur_path = SetupPath.getCurrentPath() if SetupPath.getDirLevels(cur_path) >= 1: return os.path.dirname(cur_path) return '' @staticmethod def addAirSimModulePath(): # if airsim module is installed then don't do anything else #import pkgutil #airsim_loader = pkgutil.find_loader('airsim') #if airsim_loader is not None: # return parent = SetupPath.getParentDir() if parent != '': airsim_path = os.path.join(parent, 'airsim') client_path = os.path.join(airsim_path, 'client.py') if os.path.exists(client_path): sys.path.insert(0, parent) else: logging.warning("airsim module not found in parent folder. Using installed package (pip install airsim).") SetupPath.addAirSimModulePath()
AirSim/PythonClient/car/setup_path.py/0
{ "file_path": "AirSim/PythonClient/car/setup_path.py", "repo_id": "AirSim", "token_count": 741 }
34
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
2
Edit dataset card