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
from keras.preprocessing import image import numpy as np import keras.backend as K import os import cv2 import PIL from PIL import Image from PIL import ImageChops import cv2 class DriveDataGenerator(image.ImageDataGenerator): def __init__(self, featurewise_center=False, samplewise_center=False, featurewise_std_normalization=False, samplewise_std_normalization=False, zca_whitening=False, zca_epsilon=1e-6, rotation_range=0., width_shift_range=0., height_shift_range=0., shear_range=0., zoom_range=0., channel_shift_range=0., fill_mode='nearest', cval=0., horizontal_flip=False, vertical_flip=False, rescale=None, preprocessing_function=None, data_format=None, brighten_range=0): super(DriveDataGenerator, self).__init__(featurewise_center, samplewise_center, featurewise_std_normalization, samplewise_std_normalization, zca_whitening, zca_epsilon, rotation_range, width_shift_range, height_shift_range, shear_range, zoom_range, channel_shift_range, fill_mode, cval, horizontal_flip, vertical_flip, rescale, preprocessing_function, data_format) self.brighten_range = brighten_range def flow(self, x_images, x_prev_states = None, y=None, batch_size=32, shuffle=True, seed=None, save_to_dir=None, save_prefix='', save_format='png', zero_drop_percentage=0.5, roi=None): return DriveIterator( x_images, x_prev_states, y, self, batch_size=batch_size, shuffle=shuffle, seed=seed, data_format=self.data_format, save_to_dir=save_to_dir, save_prefix=save_prefix, save_format=save_format, zero_drop_percentage=zero_drop_percentage, roi=roi) def random_transform_with_states(self, x, seed=None): """Randomly augment a single image tensor. # Arguments x: 3D tensor, single image. seed: random seed. # Returns A tuple. 0 -> randomly transformed version of the input (same shape). 1 -> true if image was horizontally flipped, false otherwise """ img_row_axis = self.row_axis img_col_axis = self.col_axis img_channel_axis = self.channel_axis is_image_horizontally_flipped = False # use composition of homographies # to generate final transform that needs to be applied if self.rotation_range: theta = np.pi / 180 * np.random.uniform(-self.rotation_range, self.rotation_range) else: theta = 0 if self.height_shift_range: tx = np.random.uniform(-self.height_shift_range, self.height_shift_range) * x.shape[img_row_axis] else: tx = 0 if self.width_shift_range: ty = np.random.uniform(-self.width_shift_range, self.width_shift_range) * x.shape[img_col_axis] else: ty = 0 if self.shear_range: shear = np.random.uniform(-self.shear_range, self.shear_range) else: shear = 0 if self.zoom_range[0] == 1 and self.zoom_range[1] == 1: zx, zy = 1, 1 else: zx, zy = np.random.uniform(self.zoom_range[0], self.zoom_range[1], 2) transform_matrix = None if theta != 0: rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1]]) transform_matrix = rotation_matrix if tx != 0 or ty != 0: shift_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]]) transform_matrix = shift_matrix if transform_matrix is None else np.dot(transform_matrix, shift_matrix) if shear != 0: shear_matrix = np.array([[1, -np.sin(shear), 0], [0, np.cos(shear), 0], [0, 0, 1]]) transform_matrix = shear_matrix if transform_matrix is None else np.dot(transform_matrix, shear_matrix) if zx != 1 or zy != 1: zoom_matrix = np.array([[zx, 0, 0], [0, zy, 0], [0, 0, 1]]) transform_matrix = zoom_matrix if transform_matrix is None else np.dot(transform_matrix, zoom_matrix) if transform_matrix is not None: h, w = x.shape[img_row_axis], x.shape[img_col_axis] transform_matrix = image.transform_matrix_offset_center(transform_matrix, h, w) x = image.apply_transform(x, transform_matrix, img_channel_axis, fill_mode=self.fill_mode, cval=self.cval) if self.channel_shift_range != 0: x = image.random_channel_shift(x, self.channel_shift_range, img_channel_axis) if self.horizontal_flip: if np.random.random() < 0.5: x = image.flip_axis(x, img_col_axis) is_image_horizontally_flipped = True if self.vertical_flip: if np.random.random() < 0.5: x = image.flip_axis(x, img_row_axis) if self.brighten_range != 0: random_bright = np.random.uniform(low = 1.0-self.brighten_range, high=1.0+self.brighten_range) img = cv2.cvtColor(x, cv2.COLOR_RGB2HSV) img[:, :, 2] = np.clip(img[:, :, 2] * random_bright, 0, 255) x = cv2.cvtColor(img, cv2.COLOR_HSV2RGB) return (x, is_image_horizontally_flipped) class DriveIterator(image.Iterator): """Iterator yielding data from a Numpy array. # Arguments x: Numpy array of input data. y: Numpy array of targets data. image_data_generator: Instance of `ImageDataGenerator` to use for random transformations and normalization. batch_size: Integer, size of a batch. shuffle: Boolean, whether to shuffle the data between epochs. seed: Random seed for data shuffling. data_format: String, one of `channels_first`, `channels_last`. save_to_dir: Optional directory where to save the pictures being yielded, in a viewable format. This is useful for visualizing the random transformations being applied, for debugging purposes. save_prefix: String prefix to use for saving sample images (if `save_to_dir` is set). save_format: Format to use for saving sample images (if `save_to_dir` is set). """ def __init__(self, x_images, x_prev_states, y, image_data_generator, batch_size=32, shuffle=False, seed=None, data_format=None, save_to_dir=None, save_prefix='', save_format='png', zero_drop_percentage = 0.5, roi = None): if y is not None and len(x_images) != len(y): raise ValueError('X (images tensor) and y (labels) ' 'should have the same length. ' 'Found: X.shape = %s, y.shape = %s' % (np.asarray(x_images).shape, np.asarray(y).shape)) if data_format is None: data_format = K.image_data_format() self.x_images = x_images self.zero_drop_percentage = zero_drop_percentage self.roi = roi if self.x_images.ndim != 4: raise ValueError('Input data in `NumpyArrayIterator` ' 'should ave rank 4. You passed an array ' 'with shape', self.x_images.shape) channels_axis = 3 if data_format == 'channels_last' else 1 if self.x_images.shape[channels_axis] not in {1, 3, 4}: raise ValueError('NumpyArrayIterator is set to use the ' 'data format convention "' + data_format + '" ' '(channels on axis ' + str(channels_axis) + '), i.e. expected ' 'either 1, 3 or 4 channels on axis ' + str(channels_axis) + '. ' 'However, it was passed an array with shape ' + str(self.x_images.shape) + ' (' + str(self.x_images.shape[channels_axis]) + ' channels).') if x_prev_states is not None: self.x_prev_states = x_prev_states else: self.x_prev_states = None if y is not None: self.y = y else: self.y = None self.image_data_generator = image_data_generator self.data_format = data_format self.save_to_dir = save_to_dir self.save_prefix = save_prefix self.save_format = save_format self.batch_size = batch_size super(DriveIterator, self).__init__(x_images.shape[0], batch_size, shuffle, seed) def next(self): """For python 2.x. # Returns The next batch. """ # Keeps under lock only the mechanism which advances # the indexing of each batch. with self.lock: index_array = next(self.index_generator) # The transformation of images is not under thread lock # so it can be done in parallel return self.__get_indexes(index_array) def __get_indexes(self, index_array): index_array = sorted(index_array) if self.x_prev_states is not None: batch_x_images = np.zeros(tuple([self.batch_size]+ list(self.x_images.shape)[1:]), dtype=K.floatx()) batch_x_prev_states = np.zeros(tuple([self.batch_size]+list(self.x_prev_states.shape)[1:]), dtype=K.floatx()) else: batch_x_images = np.zeros(tuple([self.batch_size] + list(self.x_images.shape)[1:]), dtype=K.floatx()) if self.roi is not None: batch_x_images = batch_x_images[:, self.roi[0]:self.roi[1], self.roi[2]:self.roi[3], :] used_indexes = [] is_horiz_flipped = [] for i, j in enumerate(index_array): x_images = self.x_images[j] if self.roi is not None: x_images = x_images[self.roi[0]:self.roi[1], self.roi[2]:self.roi[3], :] transformed = self.image_data_generator.random_transform_with_states(x_images.astype(K.floatx())) x_images = transformed[0] is_horiz_flipped.append(transformed[1]) x_images = self.image_data_generator.standardize(x_images) batch_x_images[i] = x_images if self.x_prev_states is not None: x_prev_states = self.x_prev_states[j] if (transformed[1]): x_prev_states[0] *= -1.0 batch_x_prev_states[i] = x_prev_states used_indexes.append(j) if self.x_prev_states is not None: batch_x = [np.asarray(batch_x_images)] else: batch_x = np.asarray(batch_x_images) if self.save_to_dir: for i in range(0, self.batch_size, 1): hash = np.random.randint(1e4) img = image.array_to_img(batch_x_images[i], self.data_format, scale=True) fname = '{prefix}_{index}_{hash}.{format}'.format(prefix=self.save_prefix, index=1, hash=hash, format=self.save_format) img.save(os.path.join(self.save_to_dir, fname)) batch_y = self.y[list(sorted(used_indexes))] idx = [] num_of_close_samples = 0 num_of_non_close_samples = 0 for i in range(0, len(is_horiz_flipped), 1): if batch_y.shape[1] == 1: if (is_horiz_flipped[i]): batch_y[i] *= -1 if (np.isclose(batch_y[i], 0.5, rtol=0.005, atol=0.005)): num_of_close_samples += 1 if (np.random.uniform(low=0, high=1) > self.zero_drop_percentage): idx.append(True) else: idx.append(False) else: num_of_non_close_samples += 1 idx.append(True) else: if (batch_y[i][int(len(batch_y[i])/2)] == 1): if (np.random.uniform(low=0, high=1) > self.zero_drop_percentage): idx.append(True) else: idx.append(False) else: idx.append(True) if (is_horiz_flipped[i]): batch_y[i] = batch_y[i][::-1] batch_y = batch_y[idx] batch_x[0] = batch_x[0][idx] return batch_x, batch_y def _get_batches_of_transformed_samples(self, index_array): return self.__get_indexes(index_array)
AirSim/PythonClient/imitation_learning/Generator.py/0
{ "file_path": "AirSim/PythonClient/imitation_learning/Generator.py", "repo_id": "AirSim", "token_count": 7647 }
35
import setup_path import airsim import numpy as np import os import tempfile import pprint import cv2 # connect to the AirSim simulator client = airsim.MultirotorClient() client.confirmConnection() client.enableApiControl(True) state = client.getMultirotorState() s = pprint.pformat(state) print("state: %s" % s) imu_data = client.getImuData() s = pprint.pformat(imu_data) print("imu_data: %s" % s) barometer_data = client.getBarometerData() s = pprint.pformat(barometer_data) print("barometer_data: %s" % s) magnetometer_data = client.getMagnetometerData() s = pprint.pformat(magnetometer_data) print("magnetometer_data: %s" % s) gps_data = client.getGpsData() s = pprint.pformat(gps_data) print("gps_data: %s" % s) airsim.wait_key('Press any key to takeoff') print("Taking off...") client.armDisarm(True) client.takeoffAsync().join() state = client.getMultirotorState() print("state: %s" % pprint.pformat(state)) airsim.wait_key('Press any key to move vehicle to (-10, 10, -10) at 5 m/s') client.moveToPositionAsync(-10, 10, -10, 5).join() client.hoverAsync().join() state = client.getMultirotorState() print("state: %s" % pprint.pformat(state)) airsim.wait_key('Press any key to take images') # get camera images from the car responses = client.simGetImages([ airsim.ImageRequest("0", airsim.ImageType.DepthVis), #depth visualization image airsim.ImageRequest("1", airsim.ImageType.DepthPerspective, True), #depth in perspective projection airsim.ImageRequest("1", airsim.ImageType.Scene), #scene vision image in png format airsim.ImageRequest("1", airsim.ImageType.Scene, False, False)]) #scene vision image in uncompressed RGBA array print('Retrieved images: %d' % len(responses)) tmp_dir = os.path.join(tempfile.gettempdir(), "airsim_drone") print ("Saving images to %s" % tmp_dir) try: os.makedirs(tmp_dir) except OSError: if not os.path.isdir(tmp_dir): raise for idx, response in enumerate(responses): filename = os.path.join(tmp_dir, str(idx)) if response.pixels_as_float: print("Type %d, size %d" % (response.image_type, len(response.image_data_float))) airsim.write_pfm(os.path.normpath(filename + '.pfm'), airsim.get_pfm_array(response)) elif response.compress: #png format print("Type %d, size %d" % (response.image_type, len(response.image_data_uint8))) airsim.write_file(os.path.normpath(filename + '.png'), response.image_data_uint8) else: #uncompressed array print("Type %d, size %d" % (response.image_type, len(response.image_data_uint8))) img1d = np.fromstring(response.image_data_uint8, dtype=np.uint8) # get numpy array img_rgb = img1d.reshape(response.height, response.width, 3) # reshape array to 4 channel image array H X W X 3 cv2.imwrite(os.path.normpath(filename + '.png'), img_rgb) # write to png airsim.wait_key('Press any key to reset to original state') client.reset() client.armDisarm(False) # that's enough fun for now. let's quit cleanly client.enableApiControl(False)
AirSim/PythonClient/multirotor/hello_drone.py/0
{ "file_path": "AirSim/PythonClient/multirotor/hello_drone.py", "repo_id": "AirSim", "token_count": 1131 }
36
import setup_path import airsim import time client = airsim.MultirotorClient() client.confirmConnection() client.enableApiControl(True) client.armDisarm(True) client.simEnableWeather(True) print("Setting fog to 25%") client.simSetWeatherParameter(airsim.WeatherParameter.Fog, 0.25) # Takeoff or hover landed = client.getMultirotorState().landed_state if landed == airsim.LandedState.Landed: print("taking off...") client.takeoffAsync().join() else: print("already flying...") client.hoverAsync().join() time.sleep(5) print("Setting fog to 50%") client.simSetWeatherParameter(airsim.WeatherParameter.Fog, 0.5) time.sleep(5) print("Resetting fog to 0%") client.simSetWeatherParameter(airsim.WeatherParameter.Fog, 0)
AirSim/PythonClient/multirotor/set_fog.py/0
{ "file_path": "AirSim/PythonClient/multirotor/set_fog.py", "repo_id": "AirSim", "token_count": 253 }
37
import setup_path import airsim import numpy as np import math import time from argparse import ArgumentParser import gym from gym import spaces from airgym.envs.airsim_env import AirSimEnv class AirSimDroneEnv(AirSimEnv): def __init__(self, ip_address, step_length, image_shape): super().__init__(image_shape) self.step_length = step_length self.image_shape = image_shape self.state = { "position": np.zeros(3), "collision": False, "prev_position": np.zeros(3), } self.drone = airsim.MultirotorClient(ip=ip_address) self.action_space = spaces.Discrete(7) self._setup_flight() self.image_request = airsim.ImageRequest( 3, airsim.ImageType.DepthPerspective, True, False ) def __del__(self): self.drone.reset() def _setup_flight(self): self.drone.reset() self.drone.enableApiControl(True) self.drone.armDisarm(True) # Set home position and velocity self.drone.moveToPositionAsync(-0.55265, -31.9786, -19.0225, 10).join() self.drone.moveByVelocityAsync(1, -0.67, -0.8, 5).join() def transform_obs(self, responses): img1d = np.array(responses[0].image_data_float, dtype=np.float) img1d = 255 / np.maximum(np.ones(img1d.size), img1d) img2d = np.reshape(img1d, (responses[0].height, responses[0].width)) from PIL import Image image = Image.fromarray(img2d) im_final = np.array(image.resize((84, 84)).convert("L")) return im_final.reshape([84, 84, 1]) def _get_obs(self): responses = self.drone.simGetImages([self.image_request]) image = self.transform_obs(responses) self.drone_state = self.drone.getMultirotorState() self.state["prev_position"] = self.state["position"] self.state["position"] = self.drone_state.kinematics_estimated.position self.state["velocity"] = self.drone_state.kinematics_estimated.linear_velocity collision = self.drone.simGetCollisionInfo().has_collided self.state["collision"] = collision return image def _do_action(self, action): quad_offset = self.interpret_action(action) quad_vel = self.drone.getMultirotorState().kinematics_estimated.linear_velocity self.drone.moveByVelocityAsync( quad_vel.x_val + quad_offset[0], quad_vel.y_val + quad_offset[1], quad_vel.z_val + quad_offset[2], 5, ).join() def _compute_reward(self): thresh_dist = 7 beta = 1 z = -10 pts = [ np.array([-0.55265, -31.9786, -19.0225]), np.array([48.59735, -63.3286, -60.07256]), np.array([193.5974, -55.0786, -46.32256]), np.array([369.2474, 35.32137, -62.5725]), np.array([541.3474, 143.6714, -32.07256]), ] quad_pt = np.array( list( ( self.state["position"].x_val, self.state["position"].y_val, self.state["position"].z_val, ) ) ) if self.state["collision"]: reward = -100 else: dist = 10000000 for i in range(0, len(pts) - 1): dist = min( dist, np.linalg.norm(np.cross((quad_pt - pts[i]), (quad_pt - pts[i + 1]))) / np.linalg.norm(pts[i] - pts[i + 1]), ) if dist > thresh_dist: reward = -10 else: reward_dist = math.exp(-beta * dist) - 0.5 reward_speed = ( np.linalg.norm( [ self.state["velocity"].x_val, self.state["velocity"].y_val, self.state["velocity"].z_val, ] ) - 0.5 ) reward = reward_dist + reward_speed done = 0 if reward <= -10: done = 1 return reward, done def step(self, action): self._do_action(action) obs = self._get_obs() reward, done = self._compute_reward() return obs, reward, done, self.state def reset(self): self._setup_flight() return self._get_obs() def interpret_action(self, action): if action == 0: quad_offset = (self.step_length, 0, 0) elif action == 1: quad_offset = (0, self.step_length, 0) elif action == 2: quad_offset = (0, 0, self.step_length) elif action == 3: quad_offset = (-self.step_length, 0, 0) elif action == 4: quad_offset = (0, -self.step_length, 0) elif action == 5: quad_offset = (0, 0, -self.step_length) else: quad_offset = (0, 0, 0) return quad_offset
AirSim/PythonClient/reinforcement_learning/airgym/envs/drone_env.py/0
{ "file_path": "AirSim/PythonClient/reinforcement_learning/airgym/envs/drone_env.py", "repo_id": "AirSim", "token_count": 2660 }
38
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // by Sudipta Sinha // adapted for AirSim by Matthias Mueller #include "StateStereo.h" #include "sgmstereo.h" #include <stdio.h> /* printf */ #include <ctime> /* clock_t, clock, CLOCKS_PER_SEC */ CStateStereo::CStateStereo() { } CStateStereo::~CStateStereo() { } void CStateStereo::Initialize(SGMOptions& params, int m, int n) { inputFrameWidth = n; inputFrameHeight = m; outputDir = params.outputDir; minDisp = params.minDisparity; maxDisp = params.maxDisparity; ndisps = maxDisp - minDisp; confThreshold = params.sgmConfidenceThreshold; // ensure that disparity range is a multiple of 8 int rem = ndisps % 8; int dv = ndisps / 8; if (rem != 0) { ndisps = 8 * (dv + 1); maxDisp = ndisps + minDisp; } if (params.maxImageDimensionWidth == -1 || inputFrameWidth <= params.maxImageDimensionWidth) { downSampleFactor = 1.0f; processingFrameWidth = inputFrameWidth; processingFrameHeight = inputFrameHeight; } else { downSampleFactor = params.maxImageDimensionWidth / (1.0f * inputFrameWidth); processingFrameWidth = params.maxImageDimensionWidth; processingFrameHeight = (int)(downSampleFactor * inputFrameHeight + 0.5f); } printf("process at %d x %d resolution, ndisps = %d\n", processingFrameWidth, processingFrameHeight, ndisps); dispMap = new float[processingFrameWidth * processingFrameHeight]; confMap = new unsigned char[processingFrameWidth * processingFrameHeight]; sgmStereo = new SGMStereo(processingFrameWidth, processingFrameHeight, -maxDisp, -minDisp, params.numDirections, params.sgmConfidenceThreshold, params.doSubPixRefinement, params.smoothness, params.penalty1, params.penalty2, params.alpha, params.doSequential); } void CStateStereo::CleanUp() { if (sgmStereo != NULL) { sgmStereo->free(); } } void CStateStereo::ProcessFrameAirSim(int frameCounter, float& dtime, const std::vector<uint8_t>& left_image, const std::vector<uint8_t>& right_image) { unsigned char *iL, *iR; // sgm stereo if (processingFrameWidth != inputFrameWidth || processingFrameHeight != inputFrameHeight) { printf("[ERROR]: Frame resolution = (%d x %d) is not equal to initialization ...\n", processingFrameWidth, processingFrameHeight); } int nP = processingFrameWidth * processingFrameHeight; iL = new unsigned char[nP]; iR = new unsigned char[nP]; int channels = (int)left_image.size() / nP; for (int i = 0; i < nP; i++) { { int idx = channels * i; iL[i] = (left_image[idx] + left_image[idx + 1] + left_image[idx + 2]) / 3; iR[i] = (right_image[idx] + right_image[idx + 1] + right_image[idx + 2]) / 3; } } std::clock_t start; start = std::clock(); sgmStereo->Run(iL, iR, dispMap, confMap); float duration = (std::clock() - start) / (float)CLOCKS_PER_SEC; dtime += duration; printf("Frame %06d: %5.1f ms, Average fps: %lf\n", frameCounter, duration * 1000, 1.0 / (dtime / double(frameCounter + 1))); delete[] iL; delete[] iR; } float CStateStereo::GetLeftDisparity(float x, float y) { int ix = (int)(x * processingFrameWidth + 0.5f); int iy = (int)(y * processingFrameHeight + 0.5f); ix = __max(ix, 0); ix = __min(ix, processingFrameWidth - 1); iy = __max(iy, 0); iy = __min(iy, processingFrameHeight - 1); int off = iy * processingFrameWidth + ix; float d = dispMap[off]; unsigned char c = confMap[off]; if (fabs(d) < ndisps && c >= confThreshold) { return 1.0f - (float)(fabs(d) / ndisps); } else return -1.0f; }
AirSim/SGM/src/stereoPipeline/StateStereo.cpp/0
{ "file_path": "AirSim/SGM/src/stereoPipeline/StateStereo.cpp", "repo_id": "AirSim", "token_count": 1492 }
39
#pragma once #include "common/common_utils/UniqueValueMap.hpp" #include "common/Common.hpp" #include "common/common_utils/Signal.hpp" #include "physics/Kinematics.hpp" #include "common/AirSimSettings.hpp" #include "common/CommonStructs.hpp" #include "api/VehicleSimApiBase.hpp" #include "UnityImageCapture.h" #include "UnityPawn.h" #include "NedTransform.h" class PawnSimApi : public msr::airlib::VehicleSimApiBase { private: typedef msr::airlib::AirSimSettings AirSimSettings; typedef msr::airlib::Kinematics Kinematics; typedef msr::airlib::Environment Environment; public: typedef msr::airlib::GeoPoint GeoPoint; typedef msr::airlib::Vector3r Vector3r; typedef msr::airlib::Pose Pose; typedef msr::airlib::Quaternionr Quaternionr; typedef msr::airlib::CollisionInfo CollisionInfo; typedef msr::airlib::VectorMath VectorMath; typedef msr::airlib::real_T real_T; typedef msr::airlib::Utils Utils; typedef msr::airlib::AirSimSettings::VehicleSetting VehicleSetting; typedef msr::airlib::ImageCaptureBase ImageCaptureBase; public: struct Params { UnityPawn* pawn; const NedTransform* global_transform; msr::airlib::GeoPoint home_geopoint; std::string vehicle_name; Params() { } Params(UnityPawn* pawn_val, const NedTransform* global_transform_val, const msr::airlib::GeoPoint home_geopoint_val, std::string vehicle_name_val) { pawn = pawn_val; global_transform = global_transform_val; home_geopoint = home_geopoint_val; vehicle_name = vehicle_name_val; } }; private: bool canTeleportWhileMove() const; void allowPassthroughToggleInput(); void setStartPosition(const AirSimVector& position, const AirSimQuaternion& rotator); void updateKinematics(float dt); protected: AirSimPose GetInitialPose(); msr::airlib::Kinematics* getKinematics(); msr::airlib::Environment* getEnvironment(); public: virtual void initialize() override; PawnSimApi(const Params& params); virtual void resetImplementation() override; virtual void update() override; virtual const UnityImageCapture* getImageCapture() const override; virtual Pose getPose() const override; virtual void setPose(const Pose& pose, bool ignore_collision) override; virtual CollisionInfo getCollisionInfo() const override; virtual CollisionInfo getCollisionInfoAndReset() override; virtual int getRemoteControlID() const override; virtual msr::airlib::RCData getRCData() const override; virtual std::string getVehicleName() const override { return params_.vehicle_name; } virtual void toggleTrace() override; virtual void setTraceLine(const std::vector<float>& color_rgba, float thickness) override; virtual void updateRenderedState(float dt) override; virtual void updateRendering(float dt) override; virtual const msr::airlib::Kinematics::State* getGroundTruthKinematics() const override; virtual void setKinematics(const Kinematics::State& state, bool ignore_collision) override; virtual const msr::airlib::Environment* getGroundTruthEnvironment() const override; virtual std::string getRecordFileLine(bool is_header_line) const override; virtual void reportState(msr::airlib::StateReporter& reporter) override; void OnCollision(msr::airlib::CollisionInfo collisionInfo); const NedTransform& getNedTransform() const; virtual void pawnTick(float dt); virtual bool testLineOfSightToPoint(const msr::airlib::GeoPoint& point) const override; private: Params params_; msr::airlib::GeoPoint home_geo_point_; std::map<std::string, int> vehiclesInfo_; NedTransform ned_transform_; std::unique_ptr<UnityImageCapture> image_capture_; std::string log_line_; mutable msr::airlib::RCData rc_data_; struct State { AirSimVector start_location; AirSimQuaternion start_rotation; bool tracing_enabled; bool collisions_enabled; bool passthrough_enabled; bool was_last_move_teleport; CollisionInfo collision_info; AirSimVector mesh_origin; }; State state_, initial_state_; std::unique_ptr<msr::airlib::Kinematics> kinematics_; std::unique_ptr<msr::airlib::Environment> environment_; };
AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/PawnSimApi.h/0
{ "file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/PawnSimApi.h", "repo_id": "AirSim", "token_count": 1632 }
40
#pragma once #include "Vehicles/Multirotor/MultirotorPawnEvents.h" #include "AirSimStructs.hpp" namespace UnityUtilities { static AirSimUnity::RotorInfo Convert_to_UnityRotorInfo(const MultirotorPawnEvents::RotorActuatorInfo& rotor_info) { AirSimUnity::RotorInfo unityRotorInfo; unityRotorInfo.rotor_control_filtered = rotor_info.rotor_control_filtered; unityRotorInfo.rotor_direction = rotor_info.rotor_direction; unityRotorInfo.rotor_speed = rotor_info.rotor_speed; unityRotorInfo.rotor_thrust = rotor_info.rotor_thrust; return unityRotorInfo; } static msr::airlib::Vector3r Convert_to_Vector3r(const AirSimUnity::AirSimVector& airSimVector) { msr::airlib::Vector3r result(airSimVector.x, airSimVector.y, airSimVector.z); return result; } static AirSimUnity::AirSimVector Convert_to_AirSimVector(const msr::airlib::Vector3r vec) { AirSimUnity::AirSimVector result(vec.x(), vec.y(), vec.z()); return result; } static msr::airlib::CollisionInfo Convert_to_AirSimCollisioinInfo(const AirSimUnity::AirSimCollisionInfo& collision_info) { msr::airlib::CollisionInfo collisionInfo; collisionInfo.collision_count = collision_info.collision_count; collisionInfo.has_collided = collision_info.has_collided; collisionInfo.impact_point = Convert_to_Vector3r(collision_info.impact_point); collisionInfo.normal = Convert_to_Vector3r(collision_info.normal); collisionInfo.object_id = collision_info.object_id; collisionInfo.object_name = collision_info.object_name; collisionInfo.penetration_depth = collision_info.penetration_depth; collisionInfo.position = Convert_to_Vector3r(collision_info.position); collisionInfo.time_stamp = collision_info.time_stamp; return collisionInfo; } static AirSimUnity::AirSimImageRequest Convert_to_UnityRequest(const msr::airlib::ImageCaptureBase::ImageRequest& request) { AirSimUnity::AirSimImageRequest airsim_request; airsim_request.camera_name = const_cast<char*>(request.camera_name.c_str()); airsim_request.compress = request.compress; airsim_request.image_type = request.image_type; airsim_request.pixels_as_float = request.pixels_as_float; return airsim_request; } static void Convert_to_AirsimResponse(const AirSimUnity::AirSimImageResponse& src, msr::airlib::ImageCaptureBase::ImageResponse& dest, std::string cameraName) { //TODO, we need to get this cameraName from the source itself rather than having it as a seperate parameter which ultemately get it from Request. dest.camera_name = cameraName; dest.camera_position.x() = src.camera_position.x; dest.camera_position.y() = src.camera_position.y; dest.camera_position.z() = src.camera_position.z; dest.camera_orientation.x() = src.camera_orientation.x; dest.camera_orientation.y() = src.camera_orientation.y; dest.camera_orientation.z() = src.camera_orientation.z; dest.camera_orientation.w() = src.camera_orientation.w; dest.time_stamp = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); if (src.image_uint_len == 0 && src.image_float_len) { dest.message = "no image capture"; } else { dest.message = "success"; } dest.pixels_as_float = src.pixels_as_float; dest.compress = src.compress; dest.width = src.width; dest.height = src.height; dest.image_type = src.image_type; dest.image_data_float.clear(); dest.image_data_uint8.clear(); for (int i = 0; i < src.image_uint_len; i++) { dest.image_data_uint8.push_back(static_cast<unsigned char>(src.image_data_uint[i])); } for (int i = 0; i < src.image_float_len; i++) { dest.image_data_float.push_back(src.image_data_float[i]); } } static msr::airlib::Pose Convert_to_Pose(const AirSimUnity::AirSimPose& airSimPose) { msr::airlib::Pose pose = msr::airlib::Pose(); pose.position.x() = airSimPose.position.x; pose.position.y() = airSimPose.position.y; pose.position.z() = airSimPose.position.z; pose.orientation.x() = airSimPose.orientation.x; pose.orientation.y() = airSimPose.orientation.y; pose.orientation.z() = airSimPose.orientation.z; pose.orientation.w() = airSimPose.orientation.w; return pose; } static AirSimUnity::AirSimPose Convert_to_AirSimPose(const msr::airlib::Pose& pose) { AirSimUnity::AirSimPose airSimPose = AirSimUnity::AirSimPose(); airSimPose.position.x = pose.position.x(); airSimPose.position.y = pose.position.y(); airSimPose.position.z = pose.position.z(); airSimPose.orientation.x = pose.orientation.x(); airSimPose.orientation.y = pose.orientation.y(); airSimPose.orientation.z = pose.orientation.z(); airSimPose.orientation.w = pose.orientation.w(); return airSimPose; } }
AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/UnityUtilities.hpp/0
{ "file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/UnityUtilities.hpp", "repo_id": "AirSim", "token_count": 1821 }
41
#pragma once #include "FlyingPawn.h" #include "../../SimMode/SimModeWorldBase.h" class SimModeWorldMultiRotor : public SimModeWorldBase { protected: virtual void setupClockSpeed() override; virtual std::unique_ptr<msr::airlib::ApiServerBase> createApiServer() const override; virtual bool isVehicleTypeSupported(const std::string& vehicle_type) const override; virtual std::unique_ptr<PawnSimApi> createVehicleSimApi( const PawnSimApi::Params& pawn_sim_api_params) const override; virtual msr::airlib::VehicleApiBase* getVehicleApi(const PawnSimApi::Params& pawn_sim_api_params, const PawnSimApi* sim_api) const override; public: SimModeWorldMultiRotor(int port_number); virtual void BeginPlay() override; virtual void EndPlay() override; void Tick(float DeltaSeconds) override; UnityPawn* GetVehiclePawn(const std::string& vehicle_name) override; private: typedef FlyingPawn TVehiclePawn; };
AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/Vehicles/Multirotor/SimModeWorldMultiRotor.h/0
{ "file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/Vehicles/Multirotor/SimModeWorldMultiRotor.h", "repo_id": "AirSim", "token_count": 384 }
42
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!21 &2100000 Material: serializedVersion: 6 m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInternal: {fileID: 0} m_Name: Propeller m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} m_ShaderKeywords: ADAM_CUSTOM_META _EMISSION m_LightmapFlags: 1 m_EnableInstancingVariants: 0 m_DoubleSidedGI: 0 m_CustomRenderQueue: -1 stringTagMap: {} disabledShaderPasses: [] m_SavedProperties: serializedVersion: 3 m_TexEnvs: - _BumpMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailMask: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailNormalMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _EmissionMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _SpecGlossMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _TransmissionThicknessMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Floats: - _BumpScale: 1 - _CullMode: 2 - _Cutoff: 0.5 - _DetailMode: 0 - _DetailNormalMapScale: 1 - _DstBlend: 0 - _GlossMapScale: 1 - _Glossiness: 0.928 - _GlossyReflections: 1 - _HasTransmission: 1 - _LightProbeScale: 1 - _MetaDiffuseScale: 1 - _MetaEmissionScale: 1 - _MetaMetallicSoup: 0 - _MetaSpecularScale: 1 - _MetaUseCustom: 1 - _Metallic: 0 - _Mode: 0 - _OcclusionStrength: 1 - _Parallax: 0.02 - _ReflectionProbeBoost: 1 - _SmoothnessTextureChannel: 0 - _SpecularHighlights: 1 - _SrcBlend: 1 - _Translucency: 0 - _TransmissionThicknessScale: 1 - _UVDetailMask: 0 - _UVSec: 0 - _VertexOcclusionPower: 1 - _ZWrite: 1 m_Colors: - _Color: {r: 0.9117647, g: 0.5358217, b: 0.3687284, a: 1} - _EmissionColor: {r: 0.46226418, g: 0.006541462, b: 0.006541462, a: 1} - _MetaDiffuseAdd: {r: 0, g: 0, b: 0, a: 1} - _MetaDiffuseTint: {r: 1, g: 1, b: 1, a: 1} - _MetaEmissionAdd: {r: 0, g: 0, b: 0, a: 1} - _MetaEmissionTint: {r: 1, g: 1, b: 1, a: 1} - _MetaSpecularAdd: {r: 0, g: 0, b: 0, a: 1} - _MetaSpecularTint: {r: 1, g: 1, b: 1, a: 1} - _SpecColor: {r: 0.20000574, g: 0.20000574, b: 0.20000574, a: 1}
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Materials/Propeller.mat/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Materials/Propeller.mat", "repo_id": "AirSim", "token_count": 1667 }
43
fileFormatVersion: 2 guid: b565de1eeeb33764b9c78ef5dccaa49d PrefabImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/AirSimGlobal.prefab.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/AirSimGlobal.prefab.meta", "repo_id": "AirSim", "token_count": 65 }
44
fileFormatVersion: 2 guid: e5e6638224ed5ae4d84af2ed2e0e5040 NativeFormatImporter: externalObjects: {} mainObjectFileID: 100100000 userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/WindowCameras.prefab.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/WindowCameras.prefab.meta", "repo_id": "AirSim", "token_count": 77 }
45
fileFormatVersion: 2 guid: 5000f719e528a6c43b300960e61c21d8 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/InitializeAirSim.cs.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/InitializeAirSim.cs.meta", "repo_id": "AirSim", "token_count": 94 }
46
using System.IO; using System; using System.Collections.Generic; using System.Threading; using UnityEngine; namespace AirSimUnity { /* * Utility class to save images to Documents\AirSim folder. * The Images are queued in the main thread while the file saving is done in background thread. * Creates the folder to hold images and it's corresponding data in a text file. * The folder creation and data capturing is similar to Unreal AirSim. */ public class DataRecorder { private const string FLOAT_FORMAT = "0.0000"; public struct ImageData { public CarStructs.CarData carData; public AirSimPose pose; public byte[] image; } private Thread encoderThread; private Queue<ImageData> imagesQueue; private StreamWriter dataWriter; private bool isDrone; private readonly string docsLocation; private string folderLocation; private string fileName; private string imagesLocation; private bool isCapturingImagesRunning; private int count = 0; public DataRecorder() { isDrone = true; count = 0; docsLocation = IsLinux ? "/Documents/AirSim/" : "/AirSim/"; docsLocation = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + docsLocation; } public void IsDrone(bool isDrone) { this.isDrone = isDrone; } public static bool IsLinux { get { int p = (int)Environment.OSVersion.Platform; return (p == 4) || (p == 6) || (p == 128); } } //Start the thread to dequeue the capture data and save them in a folder. public void StartRecording() { imagesQueue = new Queue<ImageData>(); isCapturingImagesRunning = true; encoderThread = new Thread(SaveImagesThread); encoderThread.Priority = System.Threading.ThreadPriority.BelowNormal; encoderThread.Start(); folderLocation = docsLocation + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"); if (!Directory.Exists(folderLocation)) { Directory.CreateDirectory(folderLocation); } imagesLocation = IsLinux ? "/images" : "\\images"; imagesLocation = folderLocation + imagesLocation; if (!Directory.Exists(imagesLocation)) { Directory.CreateDirectory(imagesLocation); } fileName = IsLinux ? "/airsim_rec.txt" : "\\airsim_rec.txt"; fileName = folderLocation + fileName; dataWriter = new StreamWriter(File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write)); string heading; if (isDrone) { heading = "Timestamp\tPosition(x)\tPosition(y)\tPosition(z)\tOrientation(w)\tOrientation(x)\tOrientation(y)\tOrientation(z)\tImageName"; } else { heading = "Timestamp\tSpeed (kmph)\tThrottle\tSteering\tBrake\tGear\tImageName"; } dataWriter.WriteLine(heading); } public void StopRecording() { isCapturingImagesRunning = false; if (dataWriter != null) { dataWriter.Close(); dataWriter = null; } } public void AddImageDataToQueue(ImageData data) { if (imagesQueue == null) { return; } imagesQueue.Enqueue(data); } private void SaveImagesThread() { string imageName; while (true) { if (!isCapturingImagesRunning && imagesQueue.Count <= 0) { break; } else if (imagesQueue.Count <= 0) { Thread.Sleep(500); continue; } long timeStamp = DataManager.GetCurrentTimeInMilli(); ImageData data = imagesQueue.Dequeue(); imageName = string.Format("img_{0}_{1}.png", count++, timeStamp); if (isDrone) { dataWriter.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}", timeStamp, data.pose.position.x.ToString(FLOAT_FORMAT), data.pose.position.y.ToString(FLOAT_FORMAT), data.pose.position.z.ToString(FLOAT_FORMAT), data.pose.orientation.w.ToString(FLOAT_FORMAT), data.pose.orientation.x.ToString(FLOAT_FORMAT), data.pose.orientation.y.ToString(FLOAT_FORMAT), data.pose.orientation.z.ToString(FLOAT_FORMAT), imageName)); } else { dataWriter.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", timeStamp, data.carData.speed, data.carData.throttle.ToString(FLOAT_FORMAT), data.carData.steering.ToString(FLOAT_FORMAT), data.carData.brake.ToString(FLOAT_FORMAT), data.carData.gear, imageName)); } if (IsLinux) { imageName = string.Format("{0}/{1}", imagesLocation, imageName); } else { imageName = string.Format("{0}\\{1}", imagesLocation, imageName); } File.WriteAllBytes(imageName, data.image); } imagesQueue = null; } } }
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Utilities/DataRecorder.cs/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Utilities/DataRecorder.cs", "repo_id": "AirSim", "token_count": 2631 }
47
fileFormatVersion: 2 guid: 3cbaa3e986df563438a7f077822cfb79 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Weather/UI.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Weather/UI.meta", "repo_id": "AirSim", "token_count": 70 }
48
fileFormatVersion: 2 guid: 5f7fb84a866473c4fb02d4bfc80b1b16 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/Plugins.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/Plugins.meta", "repo_id": "AirSim", "token_count": 72 }
49
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!21 &2100000 Material: serializedVersion: 6 m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 0} m_Name: SkyCarBodyGrey m_Shader: {fileID: 45, guid: 0000000000000000f000000000000000, type: 0} m_ShaderKeywords: _DETAIL_MUL _EMISSION _LIGHTMAPPING_STATIC_LIGHTMAPS _NORMALMAP _UVPRIM_UV1 _UVSEC_UV1 m_LightmapFlags: 0 m_EnableInstancingVariants: 0 m_DoubleSidedGI: 0 m_CustomRenderQueue: -1 stringTagMap: {} disabledShaderPasses: [] m_SavedProperties: serializedVersion: 3 m_TexEnvs: - _BumpMap: m_Texture: {fileID: 2800000, guid: d4ffb7d0ebee510498fba9d50f2296f7, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _Cube: m_Texture: {fileID: 8900000, guid: d42f3408b3c63734aa9f43fbbf3c9854, type: 2} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailMask: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailNormalMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _EmissionMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: m_Texture: {fileID: 2800000, guid: af58420b18450884782f4761c8f71952, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _Occlusion: m_Texture: {fileID: 2800000, guid: bd0d469704e7c934ebddc45ece4c1868, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: m_Texture: {fileID: 2800000, guid: bd0d469704e7c934ebddc45ece4c1868, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _SpecGlossMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Floats: - _AlphaTestRef: 0.5 - _BumpScale: 1 - _Cutoff: 0.5 - _DetailAlbedoMultiplier: 4.594794 - _DetailMode: 1 - _DetailNormalMapScale: 0 - _DstBlend: 0 - _EmissionScale: 1 - _EmissionScaleUI: 0 - _GlossMapScale: 1 - _Glossiness: 0.4 - _GlossyReflections: 1 - _Lightmapping: 0 - _Mode: 0 - _OcclusionStrength: 1 - _Parallax: 0.02 - _Shininess: 0.48942593 - _SmoothnessTextureChannel: 0 - _SpecularHighlights: 1 - _SrcBlend: 1 - _UVPrim: 0 - _UVSec: 1 - _ZWrite: 1 m_Colors: - _Color: {r: 0.08388218, g: 0.14448921, b: 0.6132076, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} - _EmissionColorUI: {r: 0, g: 0, b: 0, a: 1} - _EmissionColorWithMapUI: {r: 0, g: 0, b: 0, a: 1} - _ReflectColor: {r: 0.2205882, g: 0.2205882, b: 0.2205882, a: 0.5019608} - _SpecColor: {r: 0.07631719, g: 0.26018423, b: 0.46226418, a: 1} - _SpecularColor: {r: 0.3455882, g: 0.3455882, b: 0.3455882, a: 1}
AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Materials/SkyCarBodyGrey.mat/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Materials/SkyCarBodyGrey.mat", "repo_id": "AirSim", "token_count": 1718 }
50
fileFormatVersion: 2 guid: e6fec471c20b9d148b1f87910e67bea4 ModelImporter: serializedVersion: 19 fileIDToRecycleName: 100000: vehicle_skyCar_body_paintwork 100002: vehicle_skyCar_body_parts 100004: vehicle_skyCar_mudGuard_frontLeft 100006: vehicle_skyCar_mudGuard_frontRight 100008: vehicle_skyCar_suspension_frontLeft 100010: vehicle_skyCar_suspension_frontRight 100012: //RootNode 100014: vehicle_skyCar_underside 100016: vehicle_skyCar_wheel_frontLeft 100018: vehicle_skyCar_wheel_frontRight 100020: vehicle_skyCar_wheel_rearLeft 100022: vehicle_skyCar_wheel_rearRight 100024: pPlane2 100026: transform2 100028: vehicle_skyCar_brakeLights 100030: vehicle_skyCar_headLights 100032: vehicle_skyCar_brakeLights_glow 100034: vehicle_skyCar_headLights_glow 100036: SkyCarBodyPaintwork 100038: SkyCarBodyParts 100040: SkyCarBrakeLightsGlow 100042: SkyCarHeadLightsGlow 100044: SkyCarMudGuardFrontLeft 100046: SkyCarMudGuardFrontRight 100048: SkyCarSuspensionFrontLeft 100050: SkyCarSuspensionFrontRight 100052: SkyCarUndercarriage 100054: SkyCarWheelFrontLeft 100056: SkyCarWheelFrontRight 100058: SkyCarWheelRearLeft 100060: SkyCarWheelRearRight 100062: SkyCarParts 100064: SkyCarParts_MeshPart0 100066: SkyCarParts_MeshPart1 100068: SkyCarBody 100070: SkyCarComponents 400000: vehicle_skyCar_body_paintwork 400002: vehicle_skyCar_body_parts 400004: vehicle_skyCar_mudGuard_frontLeft 400006: vehicle_skyCar_mudGuard_frontRight 400008: vehicle_skyCar_suspension_frontLeft 400010: vehicle_skyCar_suspension_frontRight 400012: //RootNode 400014: vehicle_skyCar_underside 400016: vehicle_skyCar_wheel_frontLeft 400018: vehicle_skyCar_wheel_frontRight 400020: vehicle_skyCar_wheel_rearLeft 400022: vehicle_skyCar_wheel_rearRight 400024: pPlane2 400026: transform2 400028: vehicle_skyCar_brakeLights 400030: vehicle_skyCar_headLights 400032: vehicle_skyCar_brakeLights_glow 400034: vehicle_skyCar_headLights_glow 400036: SkyCarBodyPaintwork 400038: SkyCarBodyParts 400040: SkyCarBrakeLightsGlow 400042: SkyCarHeadLightsGlow 400044: SkyCarMudGuardFrontLeft 400046: SkyCarMudGuardFrontRight 400048: SkyCarSuspensionFrontLeft 400050: SkyCarSuspensionFrontRight 400052: SkyCarUndercarriage 400054: SkyCarWheelFrontLeft 400056: SkyCarWheelFrontRight 400058: SkyCarWheelRearLeft 400060: SkyCarWheelRearRight 400062: SkyCarParts 400064: SkyCarParts_MeshPart0 400066: SkyCarParts_MeshPart1 400068: SkyCarBody 400070: SkyCarComponents 2300000: vehicle_skyCar_body_paintwork 2300002: vehicle_skyCar_body_parts 2300004: vehicle_skyCar_mudGuard_frontLeft 2300006: vehicle_skyCar_mudGuard_frontRight 2300008: vehicle_skyCar_suspension_frontLeft 2300010: vehicle_skyCar_suspension_frontRight 2300012: vehicle_skyCar_underside 2300014: vehicle_skyCar_wheel_frontLeft 2300016: vehicle_skyCar_wheel_frontRight 2300018: vehicle_skyCar_wheel_rearLeft 2300020: vehicle_skyCar_wheel_rearRight 2300022: vehicle_skyCar_brakeLights 2300024: vehicle_skyCar_headLights 2300026: vehicle_skyCar_brakeLights_glow 2300028: vehicle_skyCar_headLights_glow 2300030: SkyCarBodyPaintwork 2300032: SkyCarBodyParts 2300034: SkyCarBrakeLightsGlow 2300036: SkyCarHeadLightsGlow 2300038: SkyCarMudGuardFrontLeft 2300040: SkyCarMudGuardFrontRight 2300042: SkyCarSuspensionFrontLeft 2300044: SkyCarSuspensionFrontRight 2300046: SkyCarUndercarriage 2300048: SkyCarWheelFrontLeft 2300050: SkyCarWheelFrontRight 2300052: SkyCarWheelRearLeft 2300054: SkyCarWheelRearRight 2300056: SkyCarParts_MeshPart0 2300058: SkyCarParts_MeshPart1 2300060: SkyCarBody 2300062: SkyCarComponents 3300000: vehicle_skyCar_body_paintwork 3300002: vehicle_skyCar_body_parts 3300004: vehicle_skyCar_mudGuard_frontLeft 3300006: vehicle_skyCar_mudGuard_frontRight 3300008: vehicle_skyCar_suspension_frontLeft 3300010: vehicle_skyCar_suspension_frontRight 3300012: vehicle_skyCar_underside 3300014: vehicle_skyCar_wheel_frontLeft 3300016: vehicle_skyCar_wheel_frontRight 3300018: vehicle_skyCar_wheel_rearLeft 3300020: vehicle_skyCar_wheel_rearRight 3300022: vehicle_skyCar_brakeLights 3300024: vehicle_skyCar_headLights 3300026: vehicle_skyCar_brakeLights_glow 3300028: vehicle_skyCar_headLights_glow 3300030: SkyCarBodyPaintwork 3300032: SkyCarBodyParts 3300034: SkyCarBrakeLightsGlow 3300036: SkyCarHeadLightsGlow 3300038: SkyCarMudGuardFrontLeft 3300040: SkyCarMudGuardFrontRight 3300042: SkyCarSuspensionFrontLeft 3300044: SkyCarSuspensionFrontRight 3300046: SkyCarUndercarriage 3300048: SkyCarWheelFrontLeft 3300050: SkyCarWheelFrontRight 3300052: SkyCarWheelRearLeft 3300054: SkyCarWheelRearRight 3300056: SkyCarParts_MeshPart0 3300058: SkyCarParts_MeshPart1 3300060: SkyCarBody 3300062: SkyCarComponents 4300000: vehicle_skyCar_wheel_rearLeft 4300002: vehicle_skyCar_wheel_rearRight 4300004: vehicle_skyCar_underside 4300006: vehicle_skyCar_mudGuard_frontLeft 4300008: vehicle_skyCar_suspension_frontLeft 4300010: vehicle_skyCar_suspension_frontRight 4300012: vehicle_skyCar_mudGuard_frontRight 4300014: vehicle_skyCar_body_paintwork 4300016: vehicle_skyCar_wheel_frontRight 4300018: vehicle_skyCar_wheel_frontLeft 4300020: vehicle_skyCar_body_parts 4300022: vehicle_skyCar_brakeLights 4300024: vehicle_skyCar_headLights 4300026: vehicle_skyCar_brakeLights_glow 4300028: vehicle_skyCar_headLights_glow 4300030: SkyCarWheelRearLeft 4300032: SkyCarWheelRearRight 4300034: SkyCarUndercarriage 4300036: SkyCarMudGuardFrontLeft 4300038: SkyCarSuspensionFrontLeft 4300040: SkyCarSuspensionFrontRight 4300042: SkyCarMudGuardFrontRight 4300044: SkyCarBodyPaintwork 4300046: SkyCarWheelFrontRight 4300048: SkyCarWheelFrontLeft 4300050: SkyCarBodyParts 4300052: SkyCarBrakeLightsGlow 4300054: SkyCarHeadLightsGlow 4300056: SkyCarParts_MeshPart0 4300058: SkyCarParts_MeshPart1 4300060: SkyCarComponents 4300062: SkyCarBody 9500000: //RootNode materials: importMaterials: 1 materialName: 1 materialSearch: 2 animations: legacyGenerateAnimations: 4 bakeSimulation: 0 resampleCurves: 1 optimizeGameObjects: 0 motionNodeName: animationImportErrors: animationImportWarnings: animationRetargetingWarnings: animationDoRetargetingWarnings: 0 animationCompression: 1 animationRotationError: 0.5 animationPositionError: 0.5 animationScaleError: 0.5 animationWrapMode: 0 extraExposedTransformPaths: [] clipAnimations: [] isReadable: 1 meshes: lODScreenPercentages: [] globalScale: 0.01 meshCompression: 0 addColliders: 0 importBlendShapes: 1 swapUVChannels: 0 generateSecondaryUV: 0 useFileUnits: 0 optimizeMeshForGPU: 0 keepQuads: 0 weldVertices: 1 secondaryUVAngleDistortion: 8 secondaryUVAreaDistortion: 15.000001 secondaryUVHardAngle: 88 secondaryUVPackMargin: 4 useFileScale: 0 tangentSpace: normalSmoothAngle: 60 normalImportMode: 0 tangentImportMode: 3 importAnimation: 1 copyAvatar: 0 humanDescription: human: [] skeleton: [] armTwist: 0.5 foreArmTwist: 0.5 upperLegTwist: 0.5 legTwist: 0.5 armStretch: 0.05 legStretch: 0.05 feetSpacing: 0 rootMotionBoneName: hasTranslationDoF: 0 lastHumanDescriptionAvatarSource: {instanceID: 0} animationType: 0 humanoidOversampling: 1 additionalBone: 0 userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Models/SkyCar.fbx.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Models/SkyCar.fbx.meta", "repo_id": "AirSim", "token_count": 3186 }
51
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1045 &1 EditorBuildSettings: m_ObjectHideFlags: 0 serializedVersion: 2 m_Scenes: - enabled: 1 path: Assets/Scenes/SimModeSelector.unity guid: 2a2adab4f94d2a8428812b3c4db5f357 - enabled: 1 path: Assets/Scenes/CarDemo.unity guid: 48447221fb4a8864dbedfeed703bf275 - enabled: 1 path: Assets/Scenes/DroneDemo.unity guid: 012f6bdfaada17042bf7917f7d4fcbd8 m_configObjects: {}
AirSim/Unity/UnityDemo/ProjectSettings/EditorBuildSettings.asset/0
{ "file_path": "AirSim/Unity/UnityDemo/ProjectSettings/EditorBuildSettings.asset", "repo_id": "AirSim", "token_count": 213 }
52
# Unity AirSim Demo A Unity project to demonstrate the usage of [AirSimAssets](https://github.com/Microsoft/AirSim/tree/main/Unity/UnityDemo) for *Car* & *Multirotor* simulation. ## Usage Open the *UnityDemo* project to test the simulation. Make sure that *SimModeSelector* scene is loaded. Hit Play button and select desired SimMode (if asked). Use WASD/Arrow keys or AirSim client to control the car and PageUP/PageDown with WASD/Arrow keys to control drone. Keys 0, 1, 2, and 3 are used to toggle windows of different camera views. Press *Record* button(Red button) located at the right bottom corner of the screen, to toggle recording of the simulation data. The recorded data can be found at **Documents\AirSim\(Date of recording)**
AirSim/Unity/UnityDemo/README.md/0
{ "file_path": "AirSim/Unity/UnityDemo/README.md", "repo_id": "AirSim", "token_count": 201 }
53
robocopy /MIR Plugins\AirSim ..\..\Plugins\AirSim /XD temp Intermediate Binaries Saved *. /njh /njs /ndl /np robocopy /MIR Plugins\AirSim\Source\AirLib ..\..\..\AirLib /XD temp Intermediate Binaries Saved *. /njh /njs /ndl /np pause
AirSim/Unreal/Environments/Blocks/update_to_git.bat/0
{ "file_path": "AirSim/Unreal/Environments/Blocks/update_to_git.bat", "repo_id": "AirSim", "token_count": 91 }
54
#include "ManualPoseController.h" #include "AirBlueprintLib.h" void UManualPoseController::initializeForPlay() { actor_ = nullptr; clearBindings(); left_mapping_ = FInputAxisKeyMapping("inputManualArrowLeft", EKeys::Left); right_mapping_ = FInputAxisKeyMapping("inputManualArrowRight", EKeys::Right); forward_mapping_ = FInputAxisKeyMapping("inputManualForward", EKeys::Up); backward_mapping_ = FInputAxisKeyMapping("inputManualBackward", EKeys::Down); up_mapping_ = FInputAxisKeyMapping("inputManualArrowUp", EKeys::PageUp); down_mapping_ = FInputAxisKeyMapping("inputManualArrowDown", EKeys::PageDown); left_yaw_mapping_ = FInputAxisKeyMapping("inputManualLeftYaw", EKeys::A); right_yaw_mapping_ = FInputAxisKeyMapping("inputManualRightYaw", EKeys::D); left_roll_mapping_ = FInputAxisKeyMapping("inputManualLefRoll", EKeys::Q); right_roll_mapping_ = FInputAxisKeyMapping("inputManualRightRoll", EKeys::E); up_pitch_mapping_ = FInputAxisKeyMapping("inputManualUpPitch", EKeys::W); down_pitch_mapping_ = FInputAxisKeyMapping("inputManualDownPitch", EKeys::S); inc_speed_mapping_ = FInputAxisKeyMapping("inputManualSpeedIncrease", EKeys::LeftShift); dec_speed_mapping_ = FInputAxisKeyMapping("inputManualSpeedDecrease", EKeys::LeftControl); input_positive_ = inpute_negative_ = last_velocity_ = FVector::ZeroVector; } void UManualPoseController::clearBindings() { left_binding_ = right_binding_ = up_binding_ = down_binding_ = nullptr; forward_binding_ = backward_binding_ = left_yaw_binding_ = up_pitch_binding_ = nullptr; right_yaw_binding_ = down_pitch_binding_ = left_roll_binding_ = right_roll_binding_ = nullptr; inc_speed_binding_ = dec_speed_binding_ = nullptr; } void UManualPoseController::setActor(AActor* actor) { //if we already have attached actor if (actor_) { removeInputBindings(); } actor_ = actor; if (actor_ != nullptr) { resetDelta(); setupInputBindings(); } } AActor* UManualPoseController::getActor() const { return actor_; } void UManualPoseController::updateActorPose(float dt) { if (actor_ != nullptr) { updateDeltaPosition(dt); FVector location = actor_->GetActorLocation(); FRotator rotation = actor_->GetActorRotation(); actor_->SetActorLocationAndRotation(location + delta_position_, rotation + delta_rotation_); resetDelta(); } else { UAirBlueprintLib::LogMessageString("UManualPoseController::updateActorPose should not be called when actor is not set", "", LogDebugLevel::Failure); } } void UManualPoseController::getDeltaPose(FVector& delta_position, FRotator& delta_rotation) const { delta_position = delta_position_; delta_rotation = delta_rotation_; } void UManualPoseController::resetDelta() { delta_position_ = FVector::ZeroVector; delta_rotation_ = FRotator::ZeroRotator; } void UManualPoseController::removeInputBindings() { if (left_binding_) UAirBlueprintLib::RemoveAxisBinding(left_mapping_, left_binding_, actor_); if (right_binding_) UAirBlueprintLib::RemoveAxisBinding(right_mapping_, right_binding_, actor_); if (forward_binding_) UAirBlueprintLib::RemoveAxisBinding(forward_mapping_, forward_binding_, actor_); if (backward_binding_) UAirBlueprintLib::RemoveAxisBinding(backward_mapping_, backward_binding_, actor_); if (up_binding_) UAirBlueprintLib::RemoveAxisBinding(up_mapping_, up_binding_, actor_); if (down_binding_) UAirBlueprintLib::RemoveAxisBinding(down_mapping_, down_binding_, actor_); if (left_yaw_binding_) UAirBlueprintLib::RemoveAxisBinding(left_yaw_mapping_, left_yaw_binding_, actor_); if (right_yaw_binding_) UAirBlueprintLib::RemoveAxisBinding(right_yaw_mapping_, right_yaw_binding_, actor_); if (left_roll_binding_) UAirBlueprintLib::RemoveAxisBinding(left_roll_mapping_, left_roll_binding_, actor_); if (right_roll_binding_) UAirBlueprintLib::RemoveAxisBinding(right_roll_mapping_, right_roll_binding_, actor_); if (up_pitch_binding_) UAirBlueprintLib::RemoveAxisBinding(up_pitch_mapping_, up_pitch_binding_, actor_); if (down_pitch_binding_) UAirBlueprintLib::RemoveAxisBinding(down_pitch_mapping_, down_pitch_binding_, actor_); if (inc_speed_binding_) UAirBlueprintLib::RemoveAxisBinding(inc_speed_mapping_, inc_speed_binding_, actor_); if (dec_speed_binding_) UAirBlueprintLib::RemoveAxisBinding(dec_speed_mapping_, dec_speed_binding_, actor_); clearBindings(); } void UManualPoseController::setupInputBindings() { UAirBlueprintLib::EnableInput(actor_); left_binding_ = &UAirBlueprintLib::BindAxisToKey(left_mapping_, actor_, this, &UManualPoseController::inputManualLeft); right_binding_ = &UAirBlueprintLib::BindAxisToKey(right_mapping_, actor_, this, &UManualPoseController::inputManualRight); forward_binding_ = &UAirBlueprintLib::BindAxisToKey(forward_mapping_, actor_, this, &UManualPoseController::inputManualForward); backward_binding_ = &UAirBlueprintLib::BindAxisToKey(backward_mapping_, actor_, this, &UManualPoseController::inputManualBackward); up_binding_ = &UAirBlueprintLib::BindAxisToKey(up_mapping_, actor_, this, &UManualPoseController::inputManualMoveUp); down_binding_ = &UAirBlueprintLib::BindAxisToKey(down_mapping_, actor_, this, &UManualPoseController::inputManualDown); left_yaw_binding_ = &UAirBlueprintLib::BindAxisToKey(left_yaw_mapping_, actor_, this, &UManualPoseController::inputManualLeftYaw); right_yaw_binding_ = &UAirBlueprintLib::BindAxisToKey(right_yaw_mapping_, actor_, this, &UManualPoseController::inputManualRightYaw); left_roll_binding_ = &UAirBlueprintLib::BindAxisToKey(left_roll_mapping_, actor_, this, &UManualPoseController::inputManualLeftRoll); right_roll_binding_ = &UAirBlueprintLib::BindAxisToKey(right_roll_mapping_, actor_, this, &UManualPoseController::inputManualRightRoll); up_pitch_binding_ = &UAirBlueprintLib::BindAxisToKey(up_pitch_mapping_, actor_, this, &UManualPoseController::inputManualUpPitch); down_pitch_binding_ = &UAirBlueprintLib::BindAxisToKey(down_pitch_mapping_, actor_, this, &UManualPoseController::inputManualDownPitch); inc_speed_binding_ = &UAirBlueprintLib::BindAxisToKey(inc_speed_mapping_, actor_, this, &UManualPoseController::inputManualSpeedIncrease); dec_speed_binding_ = &UAirBlueprintLib::BindAxisToKey(dec_speed_mapping_, actor_, this, &UManualPoseController::inputManualSpeedDecrease); } void UManualPoseController::updateDeltaPosition(float dt) { FVector input = input_positive_ - inpute_negative_; if (!FMath::IsNearlyZero(input.SizeSquared())) { if (FMath::IsNearlyZero(acceleration_)) last_velocity_ = input * speed_scaler_; else last_velocity_ += input * (acceleration_ * dt); delta_position_ += actor_->GetActorRotation().RotateVector(last_velocity_ * dt); } else { delta_position_ = last_velocity_ = FVector::ZeroVector; } } void UManualPoseController::inputManualSpeedIncrease(float val) { if (!FMath::IsNearlyEqual(val, 0.f)) speed_scaler_ += val * 20; } void UManualPoseController::inputManualSpeedDecrease(float val) { if (!FMath::IsNearlyEqual(val, 0.f)) speed_scaler_ -= val * 20; if (speed_scaler_ <= 0.0) speed_scaler_ = 20.0; } void UManualPoseController::inputManualLeft(float val) { inpute_negative_.Y = val; } void UManualPoseController::inputManualRight(float val) { input_positive_.Y = val; } void UManualPoseController::inputManualForward(float val) { input_positive_.X = val; } void UManualPoseController::inputManualBackward(float val) { inpute_negative_.X = val; } void UManualPoseController::inputManualMoveUp(float val) { input_positive_.Z = val; } void UManualPoseController::inputManualDown(float val) { inpute_negative_.Z = val; } void UManualPoseController::inputManualLeftYaw(float val) { if (!FMath::IsNearlyEqual(val, 0.f)) delta_rotation_.Add(0, -val, 0); } void UManualPoseController::inputManualRightYaw(float val) { if (!FMath::IsNearlyEqual(val, 0.f)) delta_rotation_.Add(0, val, 0); } void UManualPoseController::inputManualLeftRoll(float val) { if (!FMath::IsNearlyEqual(val, 0.f)) delta_rotation_.Add(0, 0, -val); } void UManualPoseController::inputManualRightRoll(float val) { if (!FMath::IsNearlyEqual(val, 0.f)) delta_rotation_.Add(0, 0, val); } void UManualPoseController::inputManualUpPitch(float val) { if (!FMath::IsNearlyEqual(val, 0.f)) delta_rotation_.Add(val, 0, 0); } void UManualPoseController::inputManualDownPitch(float val) { if (!FMath::IsNearlyEqual(val, 0.f)) delta_rotation_.Add(-val, 0, 0); }
AirSim/Unreal/Plugins/AirSim/Source/ManualPoseController.cpp/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/ManualPoseController.cpp", "repo_id": "AirSim", "token_count": 3539 }
55
#include "RenderRequest.h" #include "TextureResource.h" #include "Engine/TextureRenderTarget2D.h" #include "Async/TaskGraphInterfaces.h" #include "ImageUtils.h" #include "AirBlueprintLib.h" #include "Async/Async.h" RenderRequest::RenderRequest(UGameViewportClient* game_viewport, std::function<void()>&& query_camera_pose_cb) : params_(nullptr), results_(nullptr), req_size_(0), wait_signal_(new msr::airlib::WorkerThreadSignal), game_viewport_(game_viewport), query_camera_pose_cb_(std::move(query_camera_pose_cb)) { } RenderRequest::~RenderRequest() { } // read pixels from render target using render thread, then compress the result into PNG // argument on the thread that calls this method. void RenderRequest::getScreenshot(std::shared_ptr<RenderParams> params[], std::vector<std::shared_ptr<RenderResult>>& results, unsigned int req_size, bool use_safe_method) { //TODO: is below really needed? for (unsigned int i = 0; i < req_size; ++i) { results.push_back(std::make_shared<RenderResult>()); if (!params[i]->pixels_as_float) results[i]->bmp.Reset(); else results[i]->bmp_float.Reset(); results[i]->time_stamp = 0; } //make sure we are not on the rendering thread CheckNotBlockedOnRenderThread(); if (use_safe_method) { for (unsigned int i = 0; i < req_size; ++i) { //TODO: below doesn't work right now because it must be running in game thread FIntPoint img_size; if (!params[i]->pixels_as_float) { //below is documented method but more expensive because it forces flush FTextureRenderTargetResource* rt_resource = params[i]->render_target->GameThread_GetRenderTargetResource(); auto flags = setupRenderResource(rt_resource, params[i].get(), results[i].get(), img_size); rt_resource->ReadPixels(results[i]->bmp, flags); } else { FTextureRenderTargetResource* rt_resource = params[i]->render_target->GetRenderTargetResource(); setupRenderResource(rt_resource, params[i].get(), results[i].get(), img_size); rt_resource->ReadFloat16Pixels(results[i]->bmp_float); } } } else { //wait for render thread to pick up our task params_ = params; results_ = results.data(); req_size_ = req_size; // Queue up the task of querying camera pose in the game thread and synchronizing render thread with camera pose AsyncTask(ENamedThreads::GameThread, [this]() { check(IsInGameThread()); saved_DisableWorldRendering_ = game_viewport_->bDisableWorldRendering; game_viewport_->bDisableWorldRendering = 0; end_draw_handle_ = game_viewport_->OnEndDraw().AddLambda([this] { check(IsInGameThread()); // capture CameraPose for this frame query_camera_pose_cb_(); // The completion is called immeidately after GameThread sends the // rendering commands to RenderThread. Hence, our ExecuteTask will // execute *immediately* after RenderThread renders the scene! RenderRequest* This = this; ENQUEUE_RENDER_COMMAND(SceneDrawCompletion) ( [This](FRHICommandListImmediate& RHICmdList) { This->ExecuteTask(); }); game_viewport_->bDisableWorldRendering = saved_DisableWorldRendering_; assert(end_draw_handle_.IsValid()); game_viewport_->OnEndDraw().Remove(end_draw_handle_); }); // while we're still on GameThread, enqueue request for capture the scene! for (unsigned int i = 0; i < req_size_; ++i) { params_[i]->render_component->CaptureSceneDeferred(); } }); // wait for this task to complete while (!wait_signal_->waitFor(5)) { // log a message and continue wait // lamda function still references a few objects for which there is no refcount. // Walking away will cause memory corruption, which is much more difficult to debug. UE_LOG(LogTemp, Warning, TEXT("Failed: timeout waiting for screenshot")); } } for (unsigned int i = 0; i < req_size; ++i) { if (!params[i]->pixels_as_float) { if (results[i]->width != 0 && results[i]->height != 0) { results[i]->image_data_uint8.SetNumUninitialized(results[i]->width * results[i]->height * 3, false); if (params[i]->compress) UAirBlueprintLib::CompressImageArray(results[i]->width, results[i]->height, results[i]->bmp, results[i]->image_data_uint8); else { uint8* ptr = results[i]->image_data_uint8.GetData(); for (const auto& item : results[i]->bmp) { *ptr++ = item.B; *ptr++ = item.G; *ptr++ = item.R; } } } } else { results[i]->image_data_float.SetNumUninitialized(results[i]->width * results[i]->height); float* ptr = results[i]->image_data_float.GetData(); for (const auto& item : results[i]->bmp_float) { *ptr++ = item.R.GetFloat(); } } } } FReadSurfaceDataFlags RenderRequest::setupRenderResource(const FTextureRenderTargetResource* rt_resource, const RenderParams* params, RenderResult* result, FIntPoint& size) { size = rt_resource->GetSizeXY(); result->width = size.X; result->height = size.Y; FReadSurfaceDataFlags flags(RCM_UNorm, CubeFace_MAX); flags.SetLinearToGamma(false); return flags; } void RenderRequest::ExecuteTask() { if (params_ != nullptr && req_size_ > 0) { for (unsigned int i = 0; i < req_size_; ++i) { FRHICommandListImmediate& RHICmdList = GetImmediateCommandList_ForRenderCommand(); auto rt_resource = params_[i]->render_target->GetRenderTargetResource(); if (rt_resource != nullptr) { const FTexture2DRHIRef& rhi_texture = rt_resource->GetRenderTargetTexture(); FIntPoint size; auto flags = setupRenderResource(rt_resource, params_[i].get(), results_[i].get(), size); //should we be using ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER which was in original commit by @saihv //https://github.com/Microsoft/AirSim/pull/162/commits/63e80c43812300a8570b04ed42714a3f6949e63f#diff-56b790f9394f7ca1949ddbb320d8456fR64 if (!params_[i]->pixels_as_float) { //below is undocumented method that avoids flushing, but it seems to segfault every 2000 or so calls RHICmdList.ReadSurfaceData( rhi_texture, FIntRect(0, 0, size.X, size.Y), results_[i]->bmp, flags); } else { RHICmdList.ReadSurfaceFloatData( rhi_texture, FIntRect(0, 0, size.X, size.Y), results_[i]->bmp_float, CubeFace_PosX, 0, 0); } } results_[i]->time_stamp = msr::airlib::ClockFactory::get()->nowNanos(); } req_size_ = 0; params_ = nullptr; results_ = nullptr; wait_signal_->signal(); } }
AirSim/Unreal/Plugins/AirSim/Source/RenderRequest.cpp/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/RenderRequest.cpp", "repo_id": "AirSim", "token_count": 3649 }
56
#pragma once #include "CoreMinimal.h" #include "Materials/Material.h" #include "common/common_utils/Utils.hpp" #include "common/AirSimSettings.hpp" #include "Engine/StaticMeshActor.h" #include "TextureShuffleActor.generated.h" UCLASS() class AIRSIM_API ATextureShuffleActor : public AStaticMeshActor { GENERATED_BODY() protected: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = TextureShuffle) UMaterialInterface* DynamicMaterial = nullptr; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = TextureShuffle) TArray<UTexture2D*> SwappableTextures; public: UFUNCTION(BlueprintNativeEvent) void SwapTexture(int tex_id = 0, int component_id = 0, int material_id = 0); private: bool MaterialCacheInitialized = false; int NumComponents = -1; UPROPERTY() TArray<UMaterialInstanceDynamic*> DynamicMaterialInstances; };
AirSim/Unreal/Plugins/AirSim/Source/TextureShuffleActor.h/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/TextureShuffleActor.h", "repo_id": "AirSim", "token_count": 302 }
57
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "VehicleWheel.h" #include "CarWheelFront.generated.h" UCLASS() class UCarWheelFront : public UVehicleWheel { GENERATED_BODY() public: UCarWheelFront(); };
AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Car/CarWheelFront.h/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Car/CarWheelFront.h", "repo_id": "AirSim", "token_count": 100 }
58
#pragma once #include "CoreMinimal.h" #include "FlyingPawn.h" #include "common/Common.hpp" #include "SimMode/SimModeWorldBase.h" #include "api/VehicleSimApiBase.hpp" #include "SimModeWorldMultiRotor.generated.h" UCLASS() class AIRSIM_API ASimModeWorldMultiRotor : public ASimModeWorldBase { GENERATED_BODY() public: virtual void BeginPlay() override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; protected: //overrides virtual void setupClockSpeed() override; virtual std::unique_ptr<msr::airlib::ApiServerBase> createApiServer() const override; virtual void getExistingVehiclePawns(TArray<AActor*>& pawns) const override; virtual bool isVehicleTypeSupported(const std::string& vehicle_type) const override; virtual std::string getVehiclePawnPathName(const AirSimSettings::VehicleSetting& vehicle_setting) const override; virtual PawnEvents* getVehiclePawnEvents(APawn* pawn) const override; virtual const common_utils::UniqueValueMap<std::string, APIPCamera*> getVehiclePawnCameras(APawn* pawn) const override; virtual void initializeVehiclePawn(APawn* pawn) override; virtual std::unique_ptr<PawnSimApi> createVehicleSimApi( const PawnSimApi::Params& pawn_sim_api_params) const override; virtual msr::airlib::VehicleApiBase* getVehicleApi(const PawnSimApi::Params& pawn_sim_api_params, const PawnSimApi* sim_api) const override; private: typedef AFlyingPawn TVehiclePawn; };
AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Multirotor/SimModeWorldMultiRotor.h/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Multirotor/SimModeWorldMultiRotor.h", "repo_id": "AirSim", "token_count": 562 }
59
FROM nvidia/cudagl:9.0-devel RUN apt-get update RUN apt-get install \ sudo \ libglu1-mesa-dev \ xdg-user-dirs \ pulseaudio \ sudo \ x11-xserver-utils \ unzip \ wget \ software-properties-common \ -y --no-install-recommends RUN apt-add-repository ppa:deadsnakes/ppa RUN apt-get update RUN apt-get install -y \ python3.6 \ python3-pip RUN python3.6 -m pip install --upgrade pip RUN python3.6 -m pip install setuptools wheel RUN adduser --force-badname --disabled-password --gecos '' --shell /bin/bash airsim_user && \ echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers && \ adduser airsim_user sudo && \ adduser airsim_user audio && \ adduser airsim_user video USER airsim_user WORKDIR /home/airsim_user # Change the following values to use a different AirSim binary # Also change the AIRSIM_EXECUTABLE variable in docker-entrypoint.sh ENV AIRSIM_BINARY_ZIP_URL=https://github.com/microsoft/AirSim/releases/download/v1.3.1-linux/Blocks.zip ENV AIRSIM_BINARY_ZIP_FILENAME=Blocks.zip ENV SDL_VIDEODRIVER_VALUE=offscreen ENV SDL_HINT_CUDA_DEVICE=0 # Download and unzip the AirSim binary RUN wget -c $AIRSIM_BINARY_ZIP_URL RUN unzip $AIRSIM_BINARY_ZIP_FILENAME RUN rm $AIRSIM_BINARY_ZIP_FILENAME # Add the Python app to the image ADD ./app /home/airsim_user/app WORKDIR /home/airsim_user RUN mkdir -p /home/airsim_user/Documents/AirSim ADD ./app/settings.json /home/airsim_user/Documents/AirSim ADD ./docker/docker-entrypoint.sh /home/airsim_user/docker-entrypoint.sh RUN sudo chown -R airsim_user /home/airsim_user WORKDIR /home/airsim_user/app # Install Python requirements RUN python3.6 -m pip install -r requirements.txt ENTRYPOINT /home/airsim_user/docker-entrypoint.sh
AirSim/azure/docker/Dockerfile/0
{ "file_path": "AirSim/azure/docker/Dockerfile", "repo_id": "AirSim", "token_count": 667 }
60
# What's new Below is summarized list of important changes. This does not include minor/less important changes or bug fixes or documentation update. This list updated every few months. For complete detailed changes, please review [commit history](https://github.com/Microsoft/AirSim/commits/main). ### Jan 2022 * Latest release `v1.7.0` for [Windows](https://github.com/microsoft/AirSim/releases/tag/v1.7.0-windows) and [Linux](https://github.com/microsoft/AirSim/releases/tag/v1.7.0-linux) ### Dec 2021 * [Cinematographic Camera](https://github.com/microsoft/AirSim/pull/3949) * [ROS2 wrapper](https://github.com/microsoft/AirSim/pull/3976) * [API to list all assets](https://github.com/microsoft/AirSim/pull/3940) * [movetoGPS API](https://github.com/microsoft/AirSim/pull/3746) ### Nov 2021 * [Optical flow camera](https://github.com/microsoft/AirSim/pull/3938) * [simSetKinematics API](https://github.com/microsoft/AirSim/pull/4066) * [Dynamically set object textures from existing UE material or texture PNG](https://github.com/microsoft/AirSim/pull/3992) * [Ability to spawn/destroy lights and control light parameters](https://github.com/microsoft/AirSim/pull/3991) ### Sep 2021 * [Support for multiple drones in Unity](https://github.com/microsoft/AirSim/pull/3128) ### Aug 2021 * [Control manual camera speed through the keyboard](https://github.com/microsoft/AirSim/pulls?page=6&q=is%3Apr+is%3Aclosed+sort%3Aupdated-desc#:~:text=1-,Control%20manual%20camera%20speed%20through%20the%20keyboard,-%233221%20by%20saihv) * Latest release `v1.6.0` for [Windows](https://github.com/microsoft/AirSim/releases/tag/v1.6.0-windows) and [Linux](https://github.com/microsoft/AirSim/releases/tag/v1.6.0-linux) * [Fix: DepthPlanar capture](https://github.com/microsoft/AirSim/pull/3907) * [Fix: compression bug in segmentation palette](https://github.com/microsoft/AirSim/pull/3937) ### Jul 2021 * [Fixed external cameras](https://github.com/microsoft/AirSim/pull/3320) * [Fix: ROS topic names](https://github.com/microsoft/AirSim/pull/3880) * [Fix: Weather API crash](https://github.com/microsoft/AirSim/pull/3009) ### Jun 2021 * [Object detection API](https://github.com/microsoft/AirSim/pull/3472) * [GazeboDrone project added to connect a gazebo drone to the AirSim drone](https://github.com/microsoft/AirSim/pull/3754) * [Control manual camera speed through the keyboard](https://github.com/microsoft/AirSim/pull/3221) * [Octo X config](https://github.com/microsoft/AirSim/pull/3653) * [API for list of vehicle names](https://github.com/microsoft/AirSim/pull/2936) * [Fix: issue where no new scene is rendered after simContinueForTime](https://github.com/microsoft/AirSim/pull/3305) * [Fix:Check for settings.json in current directory as well](https://github.com/microsoft/AirSim/pull/3436) ### May 2021 * [Make falling leaves visible in depth and segmentation](https://github.com/microsoft/AirSim/pull/3699) * [Fix: Unity Car API](https://github.com/microsoft/AirSim/pull/2937) * Latest release `v1.5.0` for [Windows](https://github.com/microsoft/AirSim/releases/tag/v1.5.0-windows) and [Linux](https://github.com/microsoft/AirSim/releases/tag/v1.5.0-linux) * [fix px4 connection for wsl 2.](https://github.com/microsoft/AirSim/pull/3603) ### Apr 2021 * [External physics engine](https://github.com/microsoft/AirSim/pull/3626) * [ArduPilot Sensor Updates](https://github.com/microsoft/AirSim/pull/3364) * [Add new build configuration "--RelWithDebInfo" which makes it easier to debug](https://github.com/microsoft/AirSim/pull/3596) * [Add ApiServerPort to available AirSim settings](https://github.com/microsoft/AirSim/pull/3196) * [ROS: Use the same settings as AirSim](https://github.com/microsoft/AirSim/pull/3536) ### Mar 2021 * [Add moveByVelocityZBodyFrame](https://github.com/microsoft/AirSim/pull/3475) * [Spawn vehicles via RPC](https://github.com/microsoft/AirSim/pull/2390) * [Unity weather parameters, weather HUD, and a visual effect for snow](https://github.com/microsoft/AirSim/pull/2909) * [Rotor output API](https://github.com/microsoft/AirSim/pull/3242) * [Extend Recording to multiple vehicles](https://github.com/microsoft/AirSim/pull/2861) * [Combine Lidar Segmentation API into getLidarData](https://github.com/microsoft/AirSim/pull/2810) ### Feb 2021 * [Add Ubuntu 20.04 to Actions CI](https://github.com/microsoft/AirSim/pull/3383) * [add tcp server support to MavLinkTest](https://github.com/microsoft/AirSim/pull/3386) ### Jan 2021 * [Added continueForFrames](https://github.com/microsoft/AirSim/pull/3102) * Latest release `v1.4.0` for [Windows](https://github.com/microsoft/AirSim/releases/tag/v1.4.0-windows) and [Linux](https://github.com/microsoft/AirSim/releases/tag/v1.4.0-linux) ### Dec 2020 * [Add Actions script to build and deploy to gh-pages](https://github.com/microsoft/AirSim/pull/3224) * [Gym environments and stable-baselines integration for RL](https://github.com/microsoft/AirSim/pull/3215) * [Programmable camera distortion](https://github.com/microsoft/AirSim/pull/3039) * [Voxel grid construction](https://github.com/microsoft/AirSim/pull/3209) * [Event camera simulation](https://github.com/microsoft/AirSim/pull/3202) * [Add Github Actions CI Checks](https://github.com/microsoft/AirSim/pull/3180) * [Added moveByVelocityBodyFrame](https://github.com/microsoft/AirSim/pull/3169) ### Nov 2020 * [fix auto-detect of pixhawk 4 hardware](https://github.com/microsoft/AirSim/pull/3156) ### Oct 2020 * [\[Travis\] Add Ubuntu 20.04, OSX XCode 11.5 jobs](https://github.com/microsoft/AirSim/pull/2953) ### Sep 2020 * [Add Vehicle option for Subwindow settings](https://github.com/microsoft/AirSim/pull/2841) * [Disable cameras after fetching images, projection matrix](https://github.com/microsoft/AirSim/pull/2881) * [Add Wind simulation](https://github.com/microsoft/AirSim/pull/2867) * [New `simRunConsoleCommand` API](https://github.com/microsoft/AirSim/pull/2996) * [UE4: Fixes and improvements to World APIs](https://github.com/microsoft/AirSim/pull/2898) * [UE4: Fix random crash with Plotting APIs](https://github.com/microsoft/AirSim/pull/2963) * [Add backwards-compatibility layer for `simSetCameraPose`](https://github.com/microsoft/AirSim/pull/2932) * [Disable LogMessages if set to false](https://github.com/microsoft/AirSim/pull/2946) * [ROS: Removed double inclusion of `static_transforms.launch`](https://github.com/microsoft/AirSim/pull/2939) * [Add retry loop when connecting PX4 SITL control channel](https://github.com/microsoft/AirSim/pull/2986) * [Allow for enabling physics when spawning a new object](https://github.com/microsoft/AirSim/pull/2902) ### July 2020 * [Add Python APIs for new Object functions](https://github.com/microsoft/AirSim/pull/2897) * [UE4: Fix Broken List Level Option](https://github.com/microsoft/AirSim/pull/2877) * [Linux build improvements](https://github.com/microsoft/AirSim/pull/2522) * [Allow passing the settings.json file location via `--settings` argument](https://github.com/microsoft/AirSim/pull/2668) * [Distance Sensor Upgrades and fixes](https://github.com/microsoft/AirSim/pull/2807) * [Update to min CMake version required for VS 2019](https://github.com/microsoft/AirSim/pull/2766) * [Fix: Non-linear bias corrupts SurfaceNormals, Segmentation image](https://github.com/microsoft/AirSim/pull/2845) * [Fix: `simGetSegmentationObjectID` will always return -1](https://github.com/microsoft/AirSim/pull/2855) * [Initial implementation of simLoadLevel, simGet/SetObjectScale, simSpawn|DestroyObject APIs](https://github.com/microsoft/AirSim/pull/2651) * [Upgrade `setCameraOrientation` API to `setCameraPose`](https://github.com/microsoft/AirSim/pull/2710) * [ROS: All sensors and car support](https://github.com/microsoft/AirSim/pull/2743) * [Get rid of potential div-0 errors so we can set dt = 0 for pausing](https://github.com/microsoft/AirSim/pull/2705) * [ROS: Add mavros_msgs to build dependencies](https://github.com/microsoft/AirSim/pull/2642) * [Move Wiki pages to docs](https://github.com/microsoft/AirSim/pull/2803) * [Add Recording APIs](https://github.com/microsoft/AirSim/pull/2834) * [Update Dockerfiles and documentation to Ubuntu 18.04](https://github.com/microsoft/AirSim/pull/2865) * [Azure development environment and documentation](https://github.com/microsoft/AirSim/pull/2816) * [ROS: Add airsim_node to install list](https://github.com/microsoft/AirSim/pull/2706) ### May 2020 * [Fix more issues with PX4 master](https://github.com/microsoft/AirSim/pull/2649) * [Reduce warnings level in Unity build](https://github.com/microsoft/AirSim/pull/2672) * [Support for Unreal Engine 4.25](https://github.com/microsoft/AirSim/pull/2669) * [Unity crash fix, upgrade to 2019.3.12, Linux build improvements](https://github.com/microsoft/AirSim/pull/2328) ### April 2020 * [Fix issues with PX4 latest master branch](https://github.com/microsoft/AirSim/pull/2634) * [Fix Lidar DrawDebugPoints causing crash](https://github.com/microsoft/AirSim/pull/2614) * [Add docstrings for Python API](https://github.com/microsoft/AirSim/pull/2565) * [Add missing noise, weather texture materials](https://github.com/microsoft/AirSim/pull/2625) * [Update AirSim.uplugin version to 1.3.1](https://github.com/microsoft/AirSim/pull/2584) * [Camera Roll angle control using Q,E keys in CV mode, manual camera](https://github.com/microsoft/AirSim/pull/2610) * [Remove broken GCC build](https://github.com/microsoft/AirSim/pull/2572) * New API - [`simSetTraceLine()`](https://github.com/microsoft/AirSim/pull/2506) * [ROS package compilation fixes and updates](https://github.com/microsoft/AirSim/pull/2571) * Latest release `v1.3.1` for [Windows](https://github.com/microsoft/AirSim/releases/tag/v1.3.1-windows) and [Linux](https://github.com/microsoft/AirSim/releases/tag/v1.3.1-linux) * APIs added and fixed - [`simSetCameraFov`](https://github.com/microsoft/AirSim/pull/2534), [`rotateToYaw`](https://github.com/microsoft/AirSim/pull/2516) * [airsim](https://pypi.org/project/airsim/) Python package update to `1.2.8` * [NoDisplay ViewMode render state fix](https://github.com/microsoft/AirSim/pull/2518) ### March 2020 * Latest release `v1.3.0` for [Windows](https://github.com/microsoft/AirSim/releases/tag/v1.3.0-Windows) and [Linux](https://github.com/microsoft/AirSim/releases/tag/v1.3.0-linux) * Upgraded to Unreal Engine 4.24, Visual Studio 2019, Clang 8, C++ 17 standard * Mac OSX Catalina support * Updated [airsim](https://pypi.org/project/airsim/) Python package, with lots of new APIs * [Removed legacy API wrappers](https://github.com/microsoft/AirSim/pull/2494) * [Support for latest PX4 stable release](px4_setup.md) * Support for [ArduPilot](https://ardupilot.org/ardupilot/) - [Copter, Rover vehicles](https://ardupilot.org/dev/docs/sitl-with-airsim.html) * [Updated Unity support](Unity.md) * [Removed simChar* APIs](https://github.com/microsoft/AirSim/pull/2493) * [Plotting APIs for Debugging](https://github.com/microsoft/AirSim/pull/2304) * [Low-level Multirotor APIs](https://github.com/microsoft/AirSim/pull/2297) * [Updated Eigen version to 3.3.7](https://github.com/microsoft/AirSim/pull/2325) * [Distance Sensor API fix](https://github.com/microsoft/AirSim/pull/2403) * Add [`simSwapTextures`](retexturing.md) API * Fix [`simContinueForTime`](https://github.com/microsoft/AirSim/pull/2299), [`simPause`](https://github.com/microsoft/AirSim/pull/2292) APIs * [Lidar Sensor Trace Casting fix](https://github.com/microsoft/AirSim/pull/2143) * [Fix rare `reset()` bug which causes Unreal crash](https://github.com/microsoft/AirSim/pull/2146) * [Lidar sensor improvements, add `simGetLidarSegmentation` API](https://github.com/microsoft/AirSim/pull/2011) * [Add RpcLibPort in settings](https://github.com/microsoft/AirSim/pull/2185) * [Recording thread deadlock fix](https://github.com/microsoft/AirSim/pull/1695) * [Prevent environment crash when Sun is not present](https://github.com/microsoft/AirSim/pull/2147) * [Africa Tracking feautre, add `simListSceneObjects()` API, fix camera projection matrix](https://github.com/microsoft/AirSim/pull/1959) * ROS wrapper for multirotors is available. See [airsim_ros_pkgs](airsim_ros_pkgs.md) for the ROS API, and [airsim_tutorial_pkgs](airsim_tutorial_pkgs.md) for tutorials. * [Added sensor APIs for Barometer, IMU, GPS, Magnetometer, Distance Sensor](sensors.md) * Added support for [docker in ubuntu](docker_ubuntu.md) ### November, 2018 * Added Weather Effects and [APIs](apis.md#weather-apis) * Added [Time of Day API](apis.md#time-of-day-api) * An experimental integration of [AirSim on Unity](https://github.com/Microsoft/AirSim/tree/main/Unity) is now available. Learn more in [Unity blog post](https://blogs.unity3d.com/2018/11/14/airsim-on-unity-experiment-with-autonomous-vehicle-simulation). * [New environments](https://github.com/Microsoft/AirSim/releases/tag/v1.2.1): Forest, Plains (windmill farm), TalkingHeads (human head simulation), TrapCam (animal detection via camera) * Highly efficient [NoDisplay view mode](settings.md#viewmode) to turn off main screen rendering so you can capture images at high rate * [Enable/disable sensors](https://github.com/Microsoft/AirSim/pull/1479) via settings * [Lidar Sensor](lidar.md) * [Support for Flysky FS-SM100 RC](https://github.com/Microsoft/AirSim/commit/474214364676b6631c01b3ed79d00c83ba5bccf5) USB adapter * Case Study: [Formula Student Technion Driverless](https://github.com/Microsoft/AirSim/wiki/technion) * [Multi-Vehicle Capability](multi_vehicle.md) * [Custom speed units](https://github.com/Microsoft/AirSim/pull/1181) * [ROS publisher](https://github.com/Microsoft/AirSim/pull/1135) * [simSetObjectPose API](https://github.com/Microsoft/AirSim/pull/1161) * [Character Control APIs](https://github.com/Microsoft/AirSim/blob/main/PythonClient/airsim/client.py#L137) (works on TalkingHeads binaries in release) * [Arducopter Solo Support](https://github.com/Microsoft/AirSim/pull/1387) * [Linux install without sudo access](https://github.com/Microsoft/AirSim/pull/1434) * [Kinect like ROS publisher](https://github.com/Microsoft/AirSim/pull/1298) ### June, 2018 * Development workflow doc * Better Python 2 compatibility * OSX setup fixes * Almost complete rewrite of our APIs with new threading model, merging old APIs and creating few newer ones ### April, 2018 * Upgraded to Unreal Engine 4.18 and Visual Studio 2017 * API framework refactoring to support world-level APIs * Latest PX4 firmware now supported * CarState with more information * ThrustMaster wheel support * pause and continueForTime APIs for drone as well as car * Allow drone simulation run at higher clock rate without any degradation * Forward-only mode fully functional for drone (do orbits while looking at center) * Better PID tuning to reduce wobble for drones * Ability to set arbitrary vehicle blueprint for drone as well as car * gimbal stabilization via settings * Ability to segment skinned and skeletal meshes by their name * moveByAngleThrottle API * Car physics tuning for better maneuverability * Configure additional cameras via settings * Time of day with geographically computed sun position * Better car steering via keyboard * Added MeshNamingMethod in segmentation setting * gimbal API * getCameraParameters API * Ability turn off main rendering to save GPU resources * Projection mode for capture settings * getRCData, setRCData APIs * Ability to turn off segmentation using negative IDs * OSX build improvements * Segmentation working for very large environments with initial IDs * Better and extensible hash calculation for segmentation IDs * Extensible PID controller for custom integration methods * Sensor architecture now enables renderer specific features like ray casting * Laser altimeter sensor ### Jan 2018 * Config system rewrite, enable flexible config we are targeting in future * Multi-Vehicle support Phase 1, core infrastructure changes * MacOS support * Infrared view * 5 types of noise and interference for cameras * WYSIWIG capture settings for cameras, preview recording settings in main view * Azure support Phase 1, enable configurability of instances for headless mode * Full kinematics APIs, ability to get pose, linear and angular velocities + accelerations via APIs * Record multiple images from multiple cameras * New segmentation APIs, ability to set configure object IDs, search via regex * New object pose APIs, ability to get pose of objects (like animals) in environment * Camera infrastructure enhancements, ability to add new image types like IR with just few lines * Clock speed APIs for drone as well as car, simulation can be run with speed factor of 0 < x < infinity * Support for Logitech G920 wheel * Physics tuning of the car, Car doesn’t roll over, responds to steering with better curve, releasing gas paddle behavior more realistic * Debugging APIs * Stress tested to 24+ hours of continuous runs * Support for Landscape and sky segmentation * Manual navigation with accelerated controls in CV mode, user can explore environment much more easily * Collison APIs * Recording enhancements, log several new data points including ground truth, multiple images, controls state * Planner and Perspective Depth views * Disparity view * New Image APIs supports float, png or numpy formats * 6 config settings for image capture, ability to set auto-exposure, motion blur, gamma etc * Full multi-camera support through out including sub-windows, recording, APIs etc * Command line script to build all environments in one shot * Remove submodules, use rpclib as download ### Nov 2017 * We now have the [car model](using_car.md). * No need to build the code. Just download [binaries](https://github.com/Microsoft/AirSim/releases) and you are good to go! * The [reinforcement learning example](reinforcement_learning.md) with AirSim * New built-in flight controller called [simple_flight](simple_flight.md) that "just works" without any additional setup. It is also now *default*. * AirSim now also generates [depth as well as disparity images](image_apis.md) that are in camera plane. * We also have official Linux build now! ## Sep 2017 - We have added [car model](using_car.md)! ## Aug 2017 - [simple_flight](simple_flight.md) is now default flight controller for drones. If you want to use PX4, you will need to modify settings.json as per [PX4 setup doc](px4_setup.md). - Linux build is official and currently uses Unreal 4.17 due to various bug fixes required - ImageType enum has breaking changes with several new additions and clarifying existing ones - SubWindows are now configurable from settings.json - PythonClient is now complete and has parity with C++ APIs. Some of these would have breaking changes. ## Feb 2017 - First release!
AirSim/docs/CHANGELOG.md/0
{ "file_path": "AirSim/docs/CHANGELOG.md", "repo_id": "AirSim", "token_count": 5670 }
61
# Installing cmake on Linux If you don't have cmake version 3.10 (for example, 3.2.2 is the default on Ubuntu 14) you can run the following: ``` mkdir ~/cmake-3.10.2 cd ~/cmake-3.10.2 wget https://cmake.org/files/v3.10/cmake-3.10.2-Linux-x86_64.sh ``` Now you have to run this command by itself (it is interactive) ``` sh cmake-3.10.2-Linux-x86_64.sh --prefix ~/cmake-3.10.2 ``` Answer 'n' to the question about creating another cmake-3.10.2-Linux-x86_64 folder and then ``` sudo update-alternatives --install /usr/bin/cmake cmake ~/cmake-3.10.2/bin/cmake 60 ``` Now type `cmake --version` to make sure your cmake version is 3.10.2.
AirSim/docs/cmake_linux.md/0
{ "file_path": "AirSim/docs/cmake_linux.md", "repo_id": "AirSim", "token_count": 251 }
62
# Hello Drone ## How does Hello Drone work? Hello Drone uses the RPC client to connect to the RPC server that is automatically started by the AirSim. The RPC server routes all the commands to a class that implements [MultirotorApiBase](https://github.com/Microsoft/AirSim/tree/main/AirLib//include/vehicles/multirotor/api/MultirotorApiBase.hpp). In essence, MultirotorApiBase defines our abstract interface for getting data from the quadrotor and sending back commands. We currently have concrete implementation for MultirotorApiBase for MavLink based vehicles. The implementation for DJI drone platforms, specifically Matrice, is in works.
AirSim/docs/hello_drone.md/0
{ "file_path": "AirSim/docs/hello_drone.md", "repo_id": "AirSim", "token_count": 158 }
63
# How to use plugin contents Plugin contents are not shown in Unreal projects by default. To view plugin content, you need to click on few semi-hidden buttons: ![plugin contents screenshot](images/plugin_contents.png) **Causion** Changes you make in content folder are changes to binary files so be careful.
AirSim/docs/working_with_plugin_contents.md/0
{ "file_path": "AirSim/docs/working_with_plugin_contents.md", "repo_id": "AirSim", "token_count": 74 }
64
<launch> <arg name="output" default="log"/> <arg name="publish_clock" default="false"/> <arg name="is_vulkan" default="true"/> <arg name="host" default="localhost" /> <node name="airsim_node" pkg="airsim_ros_pkgs" type="airsim_node" output="$(arg output)"> <param name="is_vulkan" type="bool" value="false" /> <!-- ROS timer rates. Note that timer callback will be processed at maximum possible rate, upperbounded by the following ROS params --> <param name="update_airsim_img_response_every_n_sec" type="double" value="0.05" /> <param name="update_airsim_control_every_n_sec" type="double" value="0.01" /> <param name="update_lidar_every_n_sec" type="double" value="0.01" /> <param name="publish_clock" type="bool" value="$(arg publish_clock)" /> <param name="host_ip" type="string" value="$(arg host)" /> </node> <!-- Static transforms --> <include file="$(find airsim_ros_pkgs)/launch/static_transforms.launch"/> </launch>
AirSim/ros/src/airsim_ros_pkgs/launch/airsim_node.launch/0
{ "file_path": "AirSim/ros/src/airsim_ros_pkgs/launch/airsim_node.launch", "repo_id": "AirSim", "token_count": 334 }
65
float64 latitude float64 longitude float64 altitude float64 yaw
AirSim/ros2/src/airsim_interfaces/msg/GPSYaw.msg/0
{ "file_path": "AirSim/ros2/src/airsim_interfaces/msg/GPSYaw.msg", "repo_id": "AirSim", "token_count": 17 }
66
#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 "common/common_utils/FileSystem.hpp" #include <iostream> #include <chrono> #include "common/AirSimSettings.hpp" // a minimal airsim settings parser, adapted from Unreal/Plugins/AirSim/SimHUD/SimHUD.h class AirSimSettingsParser { public: typedef msr::airlib::AirSimSettings AirSimSettings; public: AirSimSettingsParser(const std::string& host_ip); ~AirSimSettingsParser() = default; bool success(); private: std::string getSimMode(); bool getSettingsText(std::string& settings_text) const; bool initializeSettings(); bool success_; std::string settings_text_; std::string host_ip_; };
AirSim/ros2/src/airsim_ros_pkgs/include/airsim_settings_parser.h/0
{ "file_path": "AirSim/ros2/src/airsim_ros_pkgs/include/airsim_settings_parser.h", "repo_id": "AirSim", "token_count": 328 }
67
#include "airsim_settings_parser.h" AirSimSettingsParser::AirSimSettingsParser(const std::string& host_ip) : host_ip_(host_ip) { success_ = initializeSettings(); } bool AirSimSettingsParser::success() { return success_; } bool AirSimSettingsParser::getSettingsText(std::string& settings_text) const { msr::airlib::RpcLibClientBase airsim_client(host_ip_); airsim_client.confirmConnection(); settings_text = airsim_client.getSettingsString(); return !settings_text.empty(); } std::string AirSimSettingsParser::getSimMode() { const auto& settings_json = msr::airlib::Settings::loadJSonString(settings_text_); return settings_json.getString("SimMode", ""); } // mimics void ASimHUD::initializeSettings() bool AirSimSettingsParser::initializeSettings() { if (getSettingsText(settings_text_)) { AirSimSettings::initializeSettings(settings_text_); AirSimSettings::singleton().load(std::bind(&AirSimSettingsParser::getSimMode, this)); std::cout << "SimMode: " << AirSimSettings::singleton().simmode_name << std::endl; return true; } return false; }
AirSim/ros2/src/airsim_ros_pkgs/src/airsim_settings_parser.cpp/0
{ "file_path": "AirSim/ros2/src/airsim_ros_pkgs/src/airsim_settings_parser.cpp", "repo_id": "AirSim", "token_count": 397 }
68
// InBuffer.cs namespace SevenZip.Buffer { public class InBuffer { byte[] m_Buffer; uint m_Pos; uint m_Limit; uint m_BufferSize; System.IO.Stream m_Stream; bool m_StreamWasExhausted; ulong m_ProcessedSize; public InBuffer(uint bufferSize) { m_Buffer = new byte[bufferSize]; m_BufferSize = bufferSize; } public void Init(System.IO.Stream stream) { m_Stream = stream; m_ProcessedSize = 0; m_Limit = 0; m_Pos = 0; m_StreamWasExhausted = false; } public bool ReadBlock() { if (m_StreamWasExhausted) return false; m_ProcessedSize += m_Pos; int aNumProcessedBytes = m_Stream.Read(m_Buffer, 0, (int)m_BufferSize); m_Pos = 0; m_Limit = (uint)aNumProcessedBytes; m_StreamWasExhausted = (aNumProcessedBytes == 0); return (!m_StreamWasExhausted); } public void ReleaseStream() { // m_Stream.Close(); m_Stream = null; } public bool ReadByte(byte b) // check it { if (m_Pos >= m_Limit) if (!ReadBlock()) return false; b = m_Buffer[m_Pos++]; return true; } public byte ReadByte() { // return (byte)m_Stream.ReadByte(); if (m_Pos >= m_Limit) if (!ReadBlock()) return 0xFF; return m_Buffer[m_Pos++]; } public ulong GetProcessedSize() { return m_ProcessedSize + m_Pos; } } }
AssetStudio/AssetStudio/7zip/Common/InBuffer.cs/0
{ "file_path": "AssetStudio/AssetStudio/7zip/Common/InBuffer.cs", "repo_id": "AssetStudio", "token_count": 598 }
69
/* Copyright 2015 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ namespace Org.Brotli.Dec { /// <summary>Bit reading helpers.</summary> internal sealed class BitReader { /// <summary> /// Input byte buffer, consist of a ring-buffer and a "slack" region where bytes from the start of /// the ring-buffer are copied. /// </summary> private const int Capacity = 1024; private const int Slack = 16; private const int IntBufferSize = Capacity + Slack; private const int ByteReadSize = Capacity << 2; private const int ByteBufferSize = IntBufferSize << 2; private readonly byte[] byteBuffer = new byte[ByteBufferSize]; private readonly int[] intBuffer = new int[IntBufferSize]; private readonly Org.Brotli.Dec.IntReader intReader = new Org.Brotli.Dec.IntReader(); private System.IO.Stream input; /// <summary>Input stream is finished.</summary> private bool endOfStreamReached; /// <summary>Pre-fetched bits.</summary> internal long accumulator; /// <summary>Current bit-reading position in accumulator.</summary> internal int bitOffset; /// <summary>Offset of next item in intBuffer.</summary> private int intOffset; private int tailBytes = 0; /* Number of bytes in unfinished "int" item. */ /// <summary>Fills up the input buffer.</summary> /// <remarks> /// Fills up the input buffer. /// <p> No-op if there are at least 36 bytes present after current position. /// <p> After encountering the end of the input stream, 64 additional zero bytes are copied to the /// buffer. /// </remarks> internal static void ReadMoreInput(Org.Brotli.Dec.BitReader br) { // TODO: Split to check and read; move read outside of decoding loop. if (br.intOffset <= Capacity - 9) { return; } if (br.endOfStreamReached) { if (IntAvailable(br) >= -2) { return; } throw new Org.Brotli.Dec.BrotliRuntimeException("No more input"); } int readOffset = br.intOffset << 2; int bytesRead = ByteReadSize - readOffset; System.Array.Copy(br.byteBuffer, readOffset, br.byteBuffer, 0, bytesRead); br.intOffset = 0; try { while (bytesRead < ByteReadSize) { int len = br.input.Read(br.byteBuffer, bytesRead, ByteReadSize - bytesRead); // EOF is -1 in Java, but 0 in C#. if (len <= 0) { br.endOfStreamReached = true; br.tailBytes = bytesRead; bytesRead += 3; break; } bytesRead += len; } } catch (System.IO.IOException e) { throw new Org.Brotli.Dec.BrotliRuntimeException("Failed to read input", e); } Org.Brotli.Dec.IntReader.Convert(br.intReader, bytesRead >> 2); } internal static void CheckHealth(Org.Brotli.Dec.BitReader br, bool endOfStream) { if (!br.endOfStreamReached) { return; } int byteOffset = (br.intOffset << 2) + ((br.bitOffset + 7) >> 3) - 8; if (byteOffset > br.tailBytes) { throw new Org.Brotli.Dec.BrotliRuntimeException("Read after end"); } if (endOfStream && (byteOffset != br.tailBytes)) { throw new Org.Brotli.Dec.BrotliRuntimeException("Unused bytes after end"); } } /// <summary>Advances the Read buffer by 5 bytes to make room for reading next 24 bits.</summary> internal static void FillBitWindow(Org.Brotli.Dec.BitReader br) { if (br.bitOffset >= 32) { br.accumulator = ((long)br.intBuffer[br.intOffset++] << 32) | ((long)(((ulong)br.accumulator) >> 32)); br.bitOffset -= 32; } } /// <summary>Reads the specified number of bits from Read Buffer.</summary> internal static int ReadBits(Org.Brotli.Dec.BitReader br, int n) { FillBitWindow(br); int val = (int)((long)(((ulong)br.accumulator) >> br.bitOffset)) & ((1 << n) - 1); br.bitOffset += n; return val; } /// <summary>Initialize bit reader.</summary> /// <remarks> /// Initialize bit reader. /// <p> Initialisation turns bit reader to a ready state. Also a number of bytes is prefetched to /// accumulator. Because of that this method may block until enough data could be read from input. /// </remarks> /// <param name="br">BitReader POJO</param> /// <param name="input">data source</param> internal static void Init(Org.Brotli.Dec.BitReader br, System.IO.Stream input) { if (br.input != null) { throw new System.InvalidOperationException("Bit reader already has associated input stream"); } Org.Brotli.Dec.IntReader.Init(br.intReader, br.byteBuffer, br.intBuffer); br.input = input; br.accumulator = 0; br.bitOffset = 64; br.intOffset = Capacity; br.endOfStreamReached = false; Prepare(br); } private static void Prepare(Org.Brotli.Dec.BitReader br) { ReadMoreInput(br); CheckHealth(br, false); FillBitWindow(br); FillBitWindow(br); } internal static void Reload(Org.Brotli.Dec.BitReader br) { if (br.bitOffset == 64) { Prepare(br); } } /// <exception cref="System.IO.IOException"/> internal static void Close(Org.Brotli.Dec.BitReader br) { System.IO.Stream @is = br.input; br.input = null; if (@is != null) { @is.Close(); } } internal static void JumpToByteBoundary(Org.Brotli.Dec.BitReader br) { int padding = (64 - br.bitOffset) & 7; if (padding != 0) { int paddingBits = Org.Brotli.Dec.BitReader.ReadBits(br, padding); if (paddingBits != 0) { throw new Org.Brotli.Dec.BrotliRuntimeException("Corrupted padding bits"); } } } internal static int IntAvailable(Org.Brotli.Dec.BitReader br) { int limit = Capacity; if (br.endOfStreamReached) { limit = (br.tailBytes + 3) >> 2; } return limit - br.intOffset; } internal static void CopyBytes(Org.Brotli.Dec.BitReader br, byte[] data, int offset, int length) { if ((br.bitOffset & 7) != 0) { throw new Org.Brotli.Dec.BrotliRuntimeException("Unaligned copyBytes"); } // Drain accumulator. while ((br.bitOffset != 64) && (length != 0)) { data[offset++] = unchecked((byte)((long)(((ulong)br.accumulator) >> br.bitOffset))); br.bitOffset += 8; length--; } if (length == 0) { return; } // Get data from shadow buffer with "sizeof(int)" granularity. int copyInts = System.Math.Min(IntAvailable(br), length >> 2); if (copyInts > 0) { int readOffset = br.intOffset << 2; System.Array.Copy(br.byteBuffer, readOffset, data, offset, copyInts << 2); offset += copyInts << 2; length -= copyInts << 2; br.intOffset += copyInts; } if (length == 0) { return; } // Read tail bytes. if (IntAvailable(br) > 0) { // length = 1..3 FillBitWindow(br); while (length != 0) { data[offset++] = unchecked((byte)((long)(((ulong)br.accumulator) >> br.bitOffset))); br.bitOffset += 8; length--; } CheckHealth(br, false); return; } // Now it is possible to copy bytes directly. try { while (length > 0) { int len = br.input.Read(data, offset, length); if (len == -1) { throw new Org.Brotli.Dec.BrotliRuntimeException("Unexpected end of input"); } offset += len; length -= len; } } catch (System.IO.IOException e) { throw new Org.Brotli.Dec.BrotliRuntimeException("Failed to read input", e); } } } }
AssetStudio/AssetStudio/Brotli/BitReader.cs/0
{ "file_path": "AssetStudio/AssetStudio/Brotli/BitReader.cs", "repo_id": "AssetStudio", "token_count": 2979 }
70
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AssetStudio { public class BuildType { private string buildType; public BuildType(string type) { buildType = type; } public bool IsAlpha => buildType == "a"; public bool IsPatch => buildType == "p"; } }
AssetStudio/AssetStudio/BuildType.cs/0
{ "file_path": "AssetStudio/AssetStudio/BuildType.cs", "repo_id": "AssetStudio", "token_count": 158 }
71
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AssetStudio { public sealed class GameObject : EditorExtension { public PPtr<Component>[] m_Components; public string m_Name; public Transform m_Transform; public MeshRenderer m_MeshRenderer; public MeshFilter m_MeshFilter; public SkinnedMeshRenderer m_SkinnedMeshRenderer; public Animator m_Animator; public Animation m_Animation; public GameObject(ObjectReader reader) : base(reader) { int m_Component_size = reader.ReadInt32(); m_Components = new PPtr<Component>[m_Component_size]; for (int i = 0; i < m_Component_size; i++) { if ((version[0] == 5 && version[1] < 5) || version[0] < 5) //5.5 down { int first = reader.ReadInt32(); } m_Components[i] = new PPtr<Component>(reader); } var m_Layer = reader.ReadInt32(); m_Name = reader.ReadAlignedString(); } } }
AssetStudio/AssetStudio/Classes/GameObject.cs/0
{ "file_path": "AssetStudio/AssetStudio/Classes/GameObject.cs", "repo_id": "AssetStudio", "token_count": 534 }
72
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace AssetStudio { public class Hash128 { public byte[] bytes; public Hash128(BinaryReader reader) { bytes = reader.ReadBytes(16); } } public class StructParameter { public MatrixParameter[] m_MatrixParams; public VectorParameter[] m_VectorParams; public StructParameter(BinaryReader reader) { var m_NameIndex = reader.ReadInt32(); var m_Index = reader.ReadInt32(); var m_ArraySize = reader.ReadInt32(); var m_StructSize = reader.ReadInt32(); int numVectorParams = reader.ReadInt32(); m_VectorParams = new VectorParameter[numVectorParams]; for (int i = 0; i < numVectorParams; i++) { m_VectorParams[i] = new VectorParameter(reader); } int numMatrixParams = reader.ReadInt32(); m_MatrixParams = new MatrixParameter[numMatrixParams]; for (int i = 0; i < numMatrixParams; i++) { m_MatrixParams[i] = new MatrixParameter(reader); } } } public class SamplerParameter { public uint sampler; public int bindPoint; public SamplerParameter(BinaryReader reader) { sampler = reader.ReadUInt32(); bindPoint = reader.ReadInt32(); } } public enum TextureDimension { Unknown = -1, None = 0, Any = 1, Tex2D = 2, Tex3D = 3, Cube = 4, Tex2DArray = 5, CubeArray = 6 }; public class SerializedTextureProperty { public string m_DefaultName; public TextureDimension m_TexDim; public SerializedTextureProperty(BinaryReader reader) { m_DefaultName = reader.ReadAlignedString(); m_TexDim = (TextureDimension)reader.ReadInt32(); } } public enum SerializedPropertyType { Color = 0, Vector = 1, Float = 2, Range = 3, Texture = 4, Int = 5 }; public class SerializedProperty { public string m_Name; public string m_Description; public string[] m_Attributes; public SerializedPropertyType m_Type; public uint m_Flags; public float[] m_DefValue; public SerializedTextureProperty m_DefTexture; public SerializedProperty(BinaryReader reader) { m_Name = reader.ReadAlignedString(); m_Description = reader.ReadAlignedString(); m_Attributes = reader.ReadStringArray(); m_Type = (SerializedPropertyType)reader.ReadInt32(); m_Flags = reader.ReadUInt32(); m_DefValue = reader.ReadSingleArray(4); m_DefTexture = new SerializedTextureProperty(reader); } } public class SerializedProperties { public SerializedProperty[] m_Props; public SerializedProperties(BinaryReader reader) { int numProps = reader.ReadInt32(); m_Props = new SerializedProperty[numProps]; for (int i = 0; i < numProps; i++) { m_Props[i] = new SerializedProperty(reader); } } } public class SerializedShaderFloatValue { public float val; public string name; public SerializedShaderFloatValue(BinaryReader reader) { val = reader.ReadSingle(); name = reader.ReadAlignedString(); } } public class SerializedShaderRTBlendState { public SerializedShaderFloatValue srcBlend; public SerializedShaderFloatValue destBlend; public SerializedShaderFloatValue srcBlendAlpha; public SerializedShaderFloatValue destBlendAlpha; public SerializedShaderFloatValue blendOp; public SerializedShaderFloatValue blendOpAlpha; public SerializedShaderFloatValue colMask; public SerializedShaderRTBlendState(BinaryReader reader) { srcBlend = new SerializedShaderFloatValue(reader); destBlend = new SerializedShaderFloatValue(reader); srcBlendAlpha = new SerializedShaderFloatValue(reader); destBlendAlpha = new SerializedShaderFloatValue(reader); blendOp = new SerializedShaderFloatValue(reader); blendOpAlpha = new SerializedShaderFloatValue(reader); colMask = new SerializedShaderFloatValue(reader); } } public class SerializedStencilOp { public SerializedShaderFloatValue pass; public SerializedShaderFloatValue fail; public SerializedShaderFloatValue zFail; public SerializedShaderFloatValue comp; public SerializedStencilOp(BinaryReader reader) { pass = new SerializedShaderFloatValue(reader); fail = new SerializedShaderFloatValue(reader); zFail = new SerializedShaderFloatValue(reader); comp = new SerializedShaderFloatValue(reader); } } public class SerializedShaderVectorValue { public SerializedShaderFloatValue x; public SerializedShaderFloatValue y; public SerializedShaderFloatValue z; public SerializedShaderFloatValue w; public string name; public SerializedShaderVectorValue(BinaryReader reader) { x = new SerializedShaderFloatValue(reader); y = new SerializedShaderFloatValue(reader); z = new SerializedShaderFloatValue(reader); w = new SerializedShaderFloatValue(reader); name = reader.ReadAlignedString(); } } public enum FogMode { Unknown = -1, Disabled = 0, Linear = 1, Exp = 2, Exp2 = 3 }; public class SerializedShaderState { public string m_Name; public SerializedShaderRTBlendState[] rtBlend; public bool rtSeparateBlend; public SerializedShaderFloatValue zClip; public SerializedShaderFloatValue zTest; public SerializedShaderFloatValue zWrite; public SerializedShaderFloatValue culling; public SerializedShaderFloatValue conservative; public SerializedShaderFloatValue offsetFactor; public SerializedShaderFloatValue offsetUnits; public SerializedShaderFloatValue alphaToMask; public SerializedStencilOp stencilOp; public SerializedStencilOp stencilOpFront; public SerializedStencilOp stencilOpBack; public SerializedShaderFloatValue stencilReadMask; public SerializedShaderFloatValue stencilWriteMask; public SerializedShaderFloatValue stencilRef; public SerializedShaderFloatValue fogStart; public SerializedShaderFloatValue fogEnd; public SerializedShaderFloatValue fogDensity; public SerializedShaderVectorValue fogColor; public FogMode fogMode; public int gpuProgramID; public SerializedTagMap m_Tags; public int m_LOD; public bool lighting; public SerializedShaderState(ObjectReader reader) { var version = reader.version; m_Name = reader.ReadAlignedString(); rtBlend = new SerializedShaderRTBlendState[8]; for (int i = 0; i < 8; i++) { rtBlend[i] = new SerializedShaderRTBlendState(reader); } rtSeparateBlend = reader.ReadBoolean(); reader.AlignStream(); if (version[0] > 2017 || (version[0] == 2017 && version[1] >= 2)) //2017.2 and up { zClip = new SerializedShaderFloatValue(reader); } zTest = new SerializedShaderFloatValue(reader); zWrite = new SerializedShaderFloatValue(reader); culling = new SerializedShaderFloatValue(reader); if (version[0] >= 2020) //2020.1 and up { conservative = new SerializedShaderFloatValue(reader); } offsetFactor = new SerializedShaderFloatValue(reader); offsetUnits = new SerializedShaderFloatValue(reader); alphaToMask = new SerializedShaderFloatValue(reader); stencilOp = new SerializedStencilOp(reader); stencilOpFront = new SerializedStencilOp(reader); stencilOpBack = new SerializedStencilOp(reader); stencilReadMask = new SerializedShaderFloatValue(reader); stencilWriteMask = new SerializedShaderFloatValue(reader); stencilRef = new SerializedShaderFloatValue(reader); fogStart = new SerializedShaderFloatValue(reader); fogEnd = new SerializedShaderFloatValue(reader); fogDensity = new SerializedShaderFloatValue(reader); fogColor = new SerializedShaderVectorValue(reader); fogMode = (FogMode)reader.ReadInt32(); gpuProgramID = reader.ReadInt32(); m_Tags = new SerializedTagMap(reader); m_LOD = reader.ReadInt32(); lighting = reader.ReadBoolean(); reader.AlignStream(); } } public class ShaderBindChannel { public sbyte source; public sbyte target; public ShaderBindChannel(BinaryReader reader) { source = reader.ReadSByte(); target = reader.ReadSByte(); } } public class ParserBindChannels { public ShaderBindChannel[] m_Channels; public uint m_SourceMap; public ParserBindChannels(BinaryReader reader) { int numChannels = reader.ReadInt32(); m_Channels = new ShaderBindChannel[numChannels]; for (int i = 0; i < numChannels; i++) { m_Channels[i] = new ShaderBindChannel(reader); } reader.AlignStream(); m_SourceMap = reader.ReadUInt32(); } } public class VectorParameter { public int m_NameIndex; public int m_Index; public int m_ArraySize; public sbyte m_Type; public sbyte m_Dim; public VectorParameter(BinaryReader reader) { m_NameIndex = reader.ReadInt32(); m_Index = reader.ReadInt32(); m_ArraySize = reader.ReadInt32(); m_Type = reader.ReadSByte(); m_Dim = reader.ReadSByte(); reader.AlignStream(); } } public class MatrixParameter { public int m_NameIndex; public int m_Index; public int m_ArraySize; public sbyte m_Type; public sbyte m_RowCount; public MatrixParameter(BinaryReader reader) { m_NameIndex = reader.ReadInt32(); m_Index = reader.ReadInt32(); m_ArraySize = reader.ReadInt32(); m_Type = reader.ReadSByte(); m_RowCount = reader.ReadSByte(); reader.AlignStream(); } } public class TextureParameter { public int m_NameIndex; public int m_Index; public int m_SamplerIndex; public sbyte m_Dim; public TextureParameter(ObjectReader reader) { var version = reader.version; m_NameIndex = reader.ReadInt32(); m_Index = reader.ReadInt32(); m_SamplerIndex = reader.ReadInt32(); if (version[0] > 2017 || (version[0] == 2017 && version[1] >= 3)) //2017.3 and up { var m_MultiSampled = reader.ReadBoolean(); } m_Dim = reader.ReadSByte(); reader.AlignStream(); } } public class BufferBinding { public int m_NameIndex; public int m_Index; public int m_ArraySize; public BufferBinding(ObjectReader reader) { var version = reader.version; m_NameIndex = reader.ReadInt32(); m_Index = reader.ReadInt32(); if (version[0] >= 2020) //2020.1 and up { m_ArraySize = reader.ReadInt32(); } } } public class ConstantBuffer { public int m_NameIndex; public MatrixParameter[] m_MatrixParams; public VectorParameter[] m_VectorParams; public StructParameter[] m_StructParams; public int m_Size; public bool m_IsPartialCB; public ConstantBuffer(ObjectReader reader) { var version = reader.version; m_NameIndex = reader.ReadInt32(); int numMatrixParams = reader.ReadInt32(); m_MatrixParams = new MatrixParameter[numMatrixParams]; for (int i = 0; i < numMatrixParams; i++) { m_MatrixParams[i] = new MatrixParameter(reader); } int numVectorParams = reader.ReadInt32(); m_VectorParams = new VectorParameter[numVectorParams]; for (int i = 0; i < numVectorParams; i++) { m_VectorParams[i] = new VectorParameter(reader); } if (version[0] > 2017 || (version[0] == 2017 && version[1] >= 3)) //2017.3 and up { int numStructParams = reader.ReadInt32(); m_StructParams = new StructParameter[numStructParams]; for (int i = 0; i < numStructParams; i++) { m_StructParams[i] = new StructParameter(reader); } } m_Size = reader.ReadInt32(); if ((version[0] == 2020 && version[1] > 3) || (version[0] == 2020 && version[1] == 3 && version[2] >= 2) || //2020.3.2f1 and up (version[0] > 2021) || (version[0] == 2021 && version[1] > 1) || (version[0] == 2021 && version[1] == 1 && version[2] >= 4)) //2021.1.4f1 and up { m_IsPartialCB = reader.ReadBoolean(); reader.AlignStream(); } } } public class UAVParameter { public int m_NameIndex; public int m_Index; public int m_OriginalIndex; public UAVParameter(BinaryReader reader) { m_NameIndex = reader.ReadInt32(); m_Index = reader.ReadInt32(); m_OriginalIndex = reader.ReadInt32(); } } public enum ShaderGpuProgramType { Unknown = 0, GLLegacy = 1, GLES31AEP = 2, GLES31 = 3, GLES3 = 4, GLES = 5, GLCore32 = 6, GLCore41 = 7, GLCore43 = 8, DX9VertexSM20 = 9, DX9VertexSM30 = 10, DX9PixelSM20 = 11, DX9PixelSM30 = 12, DX10Level9Vertex = 13, DX10Level9Pixel = 14, DX11VertexSM40 = 15, DX11VertexSM50 = 16, DX11PixelSM40 = 17, DX11PixelSM50 = 18, DX11GeometrySM40 = 19, DX11GeometrySM50 = 20, DX11HullSM50 = 21, DX11DomainSM50 = 22, MetalVS = 23, MetalFS = 24, SPIRV = 25, ConsoleVS = 26, ConsoleFS = 27, ConsoleHS = 28, ConsoleDS = 29, ConsoleGS = 30, RayTracing = 31, PS5NGGC = 32 }; public class SerializedProgramParameters { public VectorParameter[] m_VectorParams; public MatrixParameter[] m_MatrixParams; public TextureParameter[] m_TextureParams; public BufferBinding[] m_BufferParams; public ConstantBuffer[] m_ConstantBuffers; public BufferBinding[] m_ConstantBufferBindings; public UAVParameter[] m_UAVParams; public SamplerParameter[] m_Samplers; public SerializedProgramParameters(ObjectReader reader) { int numVectorParams = reader.ReadInt32(); m_VectorParams = new VectorParameter[numVectorParams]; for (int i = 0; i < numVectorParams; i++) { m_VectorParams[i] = new VectorParameter(reader); } int numMatrixParams = reader.ReadInt32(); m_MatrixParams = new MatrixParameter[numMatrixParams]; for (int i = 0; i < numMatrixParams; i++) { m_MatrixParams[i] = new MatrixParameter(reader); } int numTextureParams = reader.ReadInt32(); m_TextureParams = new TextureParameter[numTextureParams]; for (int i = 0; i < numTextureParams; i++) { m_TextureParams[i] = new TextureParameter(reader); } int numBufferParams = reader.ReadInt32(); m_BufferParams = new BufferBinding[numBufferParams]; for (int i = 0; i < numBufferParams; i++) { m_BufferParams[i] = new BufferBinding(reader); } int numConstantBuffers = reader.ReadInt32(); m_ConstantBuffers = new ConstantBuffer[numConstantBuffers]; for (int i = 0; i < numConstantBuffers; i++) { m_ConstantBuffers[i] = new ConstantBuffer(reader); } int numConstantBufferBindings = reader.ReadInt32(); m_ConstantBufferBindings = new BufferBinding[numConstantBufferBindings]; for (int i = 0; i < numConstantBufferBindings; i++) { m_ConstantBufferBindings[i] = new BufferBinding(reader); } int numUAVParams = reader.ReadInt32(); m_UAVParams = new UAVParameter[numUAVParams]; for (int i = 0; i < numUAVParams; i++) { m_UAVParams[i] = new UAVParameter(reader); } int numSamplers = reader.ReadInt32(); m_Samplers = new SamplerParameter[numSamplers]; for (int i = 0; i < numSamplers; i++) { m_Samplers[i] = new SamplerParameter(reader); } } } public class SerializedSubProgram { public uint m_BlobIndex; public ParserBindChannels m_Channels; public ushort[] m_KeywordIndices; public sbyte m_ShaderHardwareTier; public ShaderGpuProgramType m_GpuProgramType; public SerializedProgramParameters m_Parameters; public VectorParameter[] m_VectorParams; public MatrixParameter[] m_MatrixParams; public TextureParameter[] m_TextureParams; public BufferBinding[] m_BufferParams; public ConstantBuffer[] m_ConstantBuffers; public BufferBinding[] m_ConstantBufferBindings; public UAVParameter[] m_UAVParams; public SamplerParameter[] m_Samplers; public SerializedSubProgram(ObjectReader reader) { var version = reader.version; m_BlobIndex = reader.ReadUInt32(); m_Channels = new ParserBindChannels(reader); if ((version[0] >= 2019 && version[0] < 2021) || (version[0] == 2021 && version[1] < 2)) //2019 ~2021.1 { var m_GlobalKeywordIndices = reader.ReadUInt16Array(); reader.AlignStream(); var m_LocalKeywordIndices = reader.ReadUInt16Array(); reader.AlignStream(); } else { m_KeywordIndices = reader.ReadUInt16Array(); if (version[0] >= 2017) //2017 and up { reader.AlignStream(); } } m_ShaderHardwareTier = reader.ReadSByte(); m_GpuProgramType = (ShaderGpuProgramType)reader.ReadSByte(); reader.AlignStream(); if ((version[0] == 2020 && version[1] > 3) || (version[0] == 2020 && version[1] == 3 && version[2] >= 2) || //2020.3.2f1 and up (version[0] > 2021) || (version[0] == 2021 && version[1] > 1) || (version[0] == 2021 && version[1] == 1 && version[2] >= 1)) //2021.1.1f1 and up { m_Parameters = new SerializedProgramParameters(reader); } else { int numVectorParams = reader.ReadInt32(); m_VectorParams = new VectorParameter[numVectorParams]; for (int i = 0; i < numVectorParams; i++) { m_VectorParams[i] = new VectorParameter(reader); } int numMatrixParams = reader.ReadInt32(); m_MatrixParams = new MatrixParameter[numMatrixParams]; for (int i = 0; i < numMatrixParams; i++) { m_MatrixParams[i] = new MatrixParameter(reader); } int numTextureParams = reader.ReadInt32(); m_TextureParams = new TextureParameter[numTextureParams]; for (int i = 0; i < numTextureParams; i++) { m_TextureParams[i] = new TextureParameter(reader); } int numBufferParams = reader.ReadInt32(); m_BufferParams = new BufferBinding[numBufferParams]; for (int i = 0; i < numBufferParams; i++) { m_BufferParams[i] = new BufferBinding(reader); } int numConstantBuffers = reader.ReadInt32(); m_ConstantBuffers = new ConstantBuffer[numConstantBuffers]; for (int i = 0; i < numConstantBuffers; i++) { m_ConstantBuffers[i] = new ConstantBuffer(reader); } int numConstantBufferBindings = reader.ReadInt32(); m_ConstantBufferBindings = new BufferBinding[numConstantBufferBindings]; for (int i = 0; i < numConstantBufferBindings; i++) { m_ConstantBufferBindings[i] = new BufferBinding(reader); } int numUAVParams = reader.ReadInt32(); m_UAVParams = new UAVParameter[numUAVParams]; for (int i = 0; i < numUAVParams; i++) { m_UAVParams[i] = new UAVParameter(reader); } if (version[0] >= 2017) //2017 and up { int numSamplers = reader.ReadInt32(); m_Samplers = new SamplerParameter[numSamplers]; for (int i = 0; i < numSamplers; i++) { m_Samplers[i] = new SamplerParameter(reader); } } } if (version[0] > 2017 || (version[0] == 2017 && version[1] >= 2)) //2017.2 and up { if (version[0] >= 2021) //2021.1 and up { var m_ShaderRequirements = reader.ReadInt64(); } else { var m_ShaderRequirements = reader.ReadInt32(); } } } } public class SerializedProgram { public SerializedSubProgram[] m_SubPrograms; public SerializedProgramParameters m_CommonParameters; public ushort[] m_SerializedKeywordStateMask; public SerializedProgram(ObjectReader reader) { var version = reader.version; int numSubPrograms = reader.ReadInt32(); m_SubPrograms = new SerializedSubProgram[numSubPrograms]; for (int i = 0; i < numSubPrograms; i++) { m_SubPrograms[i] = new SerializedSubProgram(reader); } if ((version[0] == 2020 && version[1] > 3) || (version[0] == 2020 && version[1] == 3 && version[2] >= 2) || //2020.3.2f1 and up (version[0] > 2021) || (version[0] == 2021 && version[1] > 1) || (version[0] == 2021 && version[1] == 1 && version[2] >= 1)) //2021.1.1f1 and up { m_CommonParameters = new SerializedProgramParameters(reader); } if (version[0] > 2022 || (version[0] == 2022 && version[1] >= 1)) //2022.1 and up { m_SerializedKeywordStateMask = reader.ReadUInt16Array(); reader.AlignStream(); } } } public enum PassType { Normal = 0, Use = 1, Grab = 2 }; public class SerializedPass { public Hash128[] m_EditorDataHash; public byte[] m_Platforms; public ushort[] m_LocalKeywordMask; public ushort[] m_GlobalKeywordMask; public KeyValuePair<string, int>[] m_NameIndices; public PassType m_Type; public SerializedShaderState m_State; public uint m_ProgramMask; public SerializedProgram progVertex; public SerializedProgram progFragment; public SerializedProgram progGeometry; public SerializedProgram progHull; public SerializedProgram progDomain; public SerializedProgram progRayTracing; public bool m_HasInstancingVariant; public string m_UseName; public string m_Name; public string m_TextureName; public SerializedTagMap m_Tags; public ushort[] m_SerializedKeywordStateMask; public SerializedPass(ObjectReader reader) { var version = reader.version; if (version[0] > 2020 || (version[0] == 2020 && version[1] >= 2)) //2020.2 and up { int numEditorDataHash = reader.ReadInt32(); m_EditorDataHash = new Hash128[numEditorDataHash]; for (int i = 0; i < numEditorDataHash; i++) { m_EditorDataHash[i] = new Hash128(reader); } reader.AlignStream(); m_Platforms = reader.ReadUInt8Array(); reader.AlignStream(); if (version[0] < 2021 || (version[0] == 2021 && version[1] < 2)) //2021.1 and down { m_LocalKeywordMask = reader.ReadUInt16Array(); reader.AlignStream(); m_GlobalKeywordMask = reader.ReadUInt16Array(); reader.AlignStream(); } } int numIndices = reader.ReadInt32(); m_NameIndices = new KeyValuePair<string, int>[numIndices]; for (int i = 0; i < numIndices; i++) { m_NameIndices[i] = new KeyValuePair<string, int>(reader.ReadAlignedString(), reader.ReadInt32()); } m_Type = (PassType)reader.ReadInt32(); m_State = new SerializedShaderState(reader); m_ProgramMask = reader.ReadUInt32(); progVertex = new SerializedProgram(reader); progFragment = new SerializedProgram(reader); progGeometry = new SerializedProgram(reader); progHull = new SerializedProgram(reader); progDomain = new SerializedProgram(reader); if (version[0] > 2019 || (version[0] == 2019 && version[1] >= 3)) //2019.3 and up { progRayTracing = new SerializedProgram(reader); } m_HasInstancingVariant = reader.ReadBoolean(); if (version[0] >= 2018) //2018 and up { var m_HasProceduralInstancingVariant = reader.ReadBoolean(); } reader.AlignStream(); m_UseName = reader.ReadAlignedString(); m_Name = reader.ReadAlignedString(); m_TextureName = reader.ReadAlignedString(); m_Tags = new SerializedTagMap(reader); if (version[0] == 2021 && version[1] >= 2) //2021.2 ~2021.x { m_SerializedKeywordStateMask = reader.ReadUInt16Array(); reader.AlignStream(); } } } public class SerializedTagMap { public KeyValuePair<string, string>[] tags; public SerializedTagMap(BinaryReader reader) { int numTags = reader.ReadInt32(); tags = new KeyValuePair<string, string>[numTags]; for (int i = 0; i < numTags; i++) { tags[i] = new KeyValuePair<string, string>(reader.ReadAlignedString(), reader.ReadAlignedString()); } } } public class SerializedSubShader { public SerializedPass[] m_Passes; public SerializedTagMap m_Tags; public int m_LOD; public SerializedSubShader(ObjectReader reader) { int numPasses = reader.ReadInt32(); m_Passes = new SerializedPass[numPasses]; for (int i = 0; i < numPasses; i++) { m_Passes[i] = new SerializedPass(reader); } m_Tags = new SerializedTagMap(reader); m_LOD = reader.ReadInt32(); } } public class SerializedShaderDependency { public string from; public string to; public SerializedShaderDependency(BinaryReader reader) { from = reader.ReadAlignedString(); to = reader.ReadAlignedString(); } } public class SerializedCustomEditorForRenderPipeline { public string customEditorName; public string renderPipelineType; public SerializedCustomEditorForRenderPipeline(BinaryReader reader) { customEditorName = reader.ReadAlignedString(); renderPipelineType = reader.ReadAlignedString(); } } public class SerializedShader { public SerializedProperties m_PropInfo; public SerializedSubShader[] m_SubShaders; public string[] m_KeywordNames; public byte[] m_KeywordFlags; public string m_Name; public string m_CustomEditorName; public string m_FallbackName; public SerializedShaderDependency[] m_Dependencies; public SerializedCustomEditorForRenderPipeline[] m_CustomEditorForRenderPipelines; public bool m_DisableNoSubshadersMessage; public SerializedShader(ObjectReader reader) { var version = reader.version; m_PropInfo = new SerializedProperties(reader); int numSubShaders = reader.ReadInt32(); m_SubShaders = new SerializedSubShader[numSubShaders]; for (int i = 0; i < numSubShaders; i++) { m_SubShaders[i] = new SerializedSubShader(reader); } if (version[0] > 2021 || (version[0] == 2021 && version[1] >= 2)) //2021.2 and up { m_KeywordNames = reader.ReadStringArray(); m_KeywordFlags = reader.ReadUInt8Array(); reader.AlignStream(); } m_Name = reader.ReadAlignedString(); m_CustomEditorName = reader.ReadAlignedString(); m_FallbackName = reader.ReadAlignedString(); int numDependencies = reader.ReadInt32(); m_Dependencies = new SerializedShaderDependency[numDependencies]; for (int i = 0; i < numDependencies; i++) { m_Dependencies[i] = new SerializedShaderDependency(reader); } if (version[0] >= 2021) //2021.1 and up { int m_CustomEditorForRenderPipelinesSize = reader.ReadInt32(); m_CustomEditorForRenderPipelines = new SerializedCustomEditorForRenderPipeline[m_CustomEditorForRenderPipelinesSize]; for (int i = 0; i < m_CustomEditorForRenderPipelinesSize; i++) { m_CustomEditorForRenderPipelines[i] = new SerializedCustomEditorForRenderPipeline(reader); } } m_DisableNoSubshadersMessage = reader.ReadBoolean(); reader.AlignStream(); } } public enum ShaderCompilerPlatform { None = -1, GL = 0, D3D9 = 1, Xbox360 = 2, PS3 = 3, D3D11 = 4, GLES20 = 5, NaCl = 6, Flash = 7, D3D11_9x = 8, GLES3Plus = 9, PSP2 = 10, PS4 = 11, XboxOne = 12, PSM = 13, Metal = 14, OpenGLCore = 15, N3DS = 16, WiiU = 17, Vulkan = 18, Switch = 19, XboxOneD3D12 = 20, GameCoreXboxOne = 21, GameCoreScarlett = 22, PS5 = 23, PS5NGGC = 24 }; public class Shader : NamedObject { public byte[] m_Script; //5.3 - 5.4 public uint decompressedSize; public byte[] m_SubProgramBlob; //5.5 and up public SerializedShader m_ParsedForm; public ShaderCompilerPlatform[] platforms; public uint[][] offsets; public uint[][] compressedLengths; public uint[][] decompressedLengths; public byte[] compressedBlob; public Shader(ObjectReader reader) : base(reader) { if (version[0] == 5 && version[1] >= 5 || version[0] > 5) //5.5 and up { m_ParsedForm = new SerializedShader(reader); platforms = reader.ReadUInt32Array().Select(x => (ShaderCompilerPlatform)x).ToArray(); if (version[0] > 2019 || (version[0] == 2019 && version[1] >= 3)) //2019.3 and up { offsets = reader.ReadUInt32ArrayArray(); compressedLengths = reader.ReadUInt32ArrayArray(); decompressedLengths = reader.ReadUInt32ArrayArray(); } else { offsets = reader.ReadUInt32Array().Select(x => new[] { x }).ToArray(); compressedLengths = reader.ReadUInt32Array().Select(x => new[] { x }).ToArray(); decompressedLengths = reader.ReadUInt32Array().Select(x => new[] { x }).ToArray(); } compressedBlob = reader.ReadUInt8Array(); reader.AlignStream(); var m_DependenciesCount = reader.ReadInt32(); for (int i = 0; i < m_DependenciesCount; i++) { new PPtr<Shader>(reader); } if (version[0] >= 2018) { var m_NonModifiableTexturesCount = reader.ReadInt32(); for (int i = 0; i < m_NonModifiableTexturesCount; i++) { var first = reader.ReadAlignedString(); new PPtr<Texture>(reader); } } var m_ShaderIsBaked = reader.ReadBoolean(); reader.AlignStream(); } else { m_Script = reader.ReadUInt8Array(); reader.AlignStream(); var m_PathName = reader.ReadAlignedString(); if (version[0] == 5 && version[1] >= 3) //5.3 - 5.4 { decompressedSize = reader.ReadUInt32(); m_SubProgramBlob = reader.ReadUInt8Array(); } } } } }
AssetStudio/AssetStudio/Classes/Shader.cs/0
{ "file_path": "AssetStudio/AssetStudio/Classes/Shader.cs", "repo_id": "AssetStudio", "token_count": 17446 }
73
using System.IO; using System.Linq; namespace AssetStudio { public class FileReader : EndianBinaryReader { public string FullPath; public string FileName; public FileType FileType; private static readonly byte[] gzipMagic = { 0x1f, 0x8b }; private static readonly byte[] brotliMagic = { 0x62, 0x72, 0x6F, 0x74, 0x6C, 0x69 }; private static readonly byte[] zipMagic = { 0x50, 0x4B, 0x03, 0x04 }; private static readonly byte[] zipSpannedMagic = { 0x50, 0x4B, 0x07, 0x08 }; public FileReader(string path) : this(path, File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { } public FileReader(string path, Stream stream) : base(stream, EndianType.BigEndian) { FullPath = Path.GetFullPath(path); FileName = Path.GetFileName(path); FileType = CheckFileType(); } private FileType CheckFileType() { var signature = this.ReadStringToNull(20); Position = 0; switch (signature) { case "UnityWeb": case "UnityRaw": case "UnityArchive": case "UnityFS": return FileType.BundleFile; case "UnityWebData1.0": return FileType.WebFile; default: { byte[] magic = ReadBytes(2); Position = 0; if (gzipMagic.SequenceEqual(magic)) { return FileType.GZipFile; } Position = 0x20; magic = ReadBytes(6); Position = 0; if (brotliMagic.SequenceEqual(magic)) { return FileType.BrotliFile; } if (IsSerializedFile()) { return FileType.AssetsFile; } magic = ReadBytes(4); Position = 0; if (zipMagic.SequenceEqual(magic) || zipSpannedMagic.SequenceEqual(magic)) return FileType.ZipFile; return FileType.ResourceFile; } } } private bool IsSerializedFile() { var fileSize = BaseStream.Length; if (fileSize < 20) { return false; } var m_MetadataSize = ReadUInt32(); long m_FileSize = ReadUInt32(); var m_Version = ReadUInt32(); long m_DataOffset = ReadUInt32(); var m_Endianess = ReadByte(); var m_Reserved = ReadBytes(3); if (m_Version >= 22) { if (fileSize < 48) { Position = 0; return false; } m_MetadataSize = ReadUInt32(); m_FileSize = ReadInt64(); m_DataOffset = ReadInt64(); } Position = 0; if (m_FileSize != fileSize) { return false; } if (m_DataOffset > fileSize) { return false; } return true; } } }
AssetStudio/AssetStudio/FileReader.cs/0
{ "file_path": "AssetStudio/AssetStudio/FileReader.cs", "repo_id": "AssetStudio", "token_count": 2072 }
74
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace AssetStudio { public class ObjectReader : EndianBinaryReader { public SerializedFile assetsFile; public long m_PathID; public long byteStart; public uint byteSize; public ClassIDType type; public SerializedType serializedType; public BuildTarget platform; public SerializedFileFormatVersion m_Version; public int[] version => assetsFile.version; public BuildType buildType => assetsFile.buildType; public ObjectReader(EndianBinaryReader reader, SerializedFile assetsFile, ObjectInfo objectInfo) : base(reader.BaseStream, reader.Endian) { this.assetsFile = assetsFile; m_PathID = objectInfo.m_PathID; byteStart = objectInfo.byteStart; byteSize = objectInfo.byteSize; if (Enum.IsDefined(typeof(ClassIDType), objectInfo.classID)) { type = (ClassIDType)objectInfo.classID; } else { type = ClassIDType.UnknownType; } serializedType = objectInfo.serializedType; platform = assetsFile.m_TargetPlatform; m_Version = assetsFile.header.m_Version; } public void Reset() { Position = byteStart; } } }
AssetStudio/AssetStudio/ObjectReader.cs/0
{ "file_path": "AssetStudio/AssetStudio/ObjectReader.cs", "repo_id": "AssetStudio", "token_count": 642 }
75
#include <fbxsdk.h> #include "dllexport.h" #include "bool32_t.h" #include "asfbx_context.h" #include "asfbx_skin_context.h" #include "asfbx_anim_context.h" #include "asfbx_morph_context.h" #include "utils.h" using namespace fbxsdk; AS_API(void) AsUtilQuaternionToEuler(float qx, float qy, float qz, float qw, float* vx, float* vy, float* vz) { Quaternion q(qx, qy, qz, qw); auto v = QuaternionToEuler(q); if (vx) { *vx = v.X; } if (vy) { *vy = v.Y; } if (vz) { *vz = v.Z; } } AS_API(void) AsUtilEulerToQuaternion(float vx, float vy, float vz, float* qx, float* qy, float* qz, float* qw) { Vector3 v(vx, vy, vz); auto q = EulerToQuaternion(v); if (qx) { *qx = q.X; } if (qy) { *qy = q.Y; } if (qz) { *qz = q.Z; } if (qw) { *qw = q.W; } } #define MGR_IOS_REF (*(pSdkManager->GetIOSettings())) static const char* FBXVersion[] = { FBX_2010_00_COMPATIBLE, FBX_2011_00_COMPATIBLE, FBX_2012_00_COMPATIBLE, FBX_2013_00_COMPATIBLE, FBX_2014_00_COMPATIBLE, FBX_2016_00_COMPATIBLE }; AS_API(AsFbxContext*) AsFbxCreateContext() { return new AsFbxContext(); } AS_API(bool32_t) AsFbxInitializeContext(AsFbxContext* pContext, const char* pFileName, float scaleFactor, int32_t versionIndex, bool32_t isAscii, bool32_t is60Fps, const char** pErrMsg) { if (pContext == nullptr) { if (pErrMsg != nullptr) { *pErrMsg = "null pointer for pContext"; } return false; } auto pSdkManager = FbxManager::Create(); pContext->pSdkManager = pSdkManager; FbxIOSettings* ios = FbxIOSettings::Create(pSdkManager, IOSROOT); pSdkManager->SetIOSettings(ios); auto pScene = FbxScene::Create(pSdkManager, ""); pContext->pScene = pScene; MGR_IOS_REF.SetBoolProp(EXP_FBX_MATERIAL, true); MGR_IOS_REF.SetBoolProp(EXP_FBX_TEXTURE, true); MGR_IOS_REF.SetBoolProp(EXP_FBX_EMBEDDED, false); MGR_IOS_REF.SetBoolProp(EXP_FBX_SHAPE, true); MGR_IOS_REF.SetBoolProp(EXP_FBX_GOBO, true); MGR_IOS_REF.SetBoolProp(EXP_FBX_ANIMATION, true); MGR_IOS_REF.SetBoolProp(EXP_FBX_GLOBAL_SETTINGS, true); FbxGlobalSettings& globalSettings = pScene->GetGlobalSettings(); globalSettings.SetSystemUnit(FbxSystemUnit(scaleFactor)); if (is60Fps) { globalSettings.SetTimeMode(FbxTime::eFrames60); } auto pExporter = FbxExporter::Create(pScene, ""); pContext->pExporter = pExporter; int pFileFormat = 0; if (versionIndex == 0) { pFileFormat = 3; if (isAscii) { pFileFormat = 4; } } else { pExporter->SetFileExportVersion(FBXVersion[versionIndex]); if (isAscii) { pFileFormat = 1; } } if (!pExporter->Initialize(pFileName, pFileFormat, pSdkManager->GetIOSettings())) { if (pErrMsg != nullptr) { auto errStr = pExporter->GetStatus().GetErrorString(); *pErrMsg = errStr; } return false; } auto pBindPose = FbxPose::Create(pScene, "BindPose"); pContext->pBindPose = pBindPose; pScene->AddPose(pBindPose); return true; } AS_API(void) AsFbxDisposeContext(AsFbxContext** ppContext) { if (ppContext == nullptr) { return; } delete (*ppContext); *ppContext = nullptr; } AS_API(void) AsFbxSetFramePaths(AsFbxContext* pContext, const char* ppPaths[], int32_t count) { if (pContext == nullptr) { return; } auto& framePaths = pContext->framePaths; for (auto i = 0; i < count; i += 1) { const char* path = ppPaths[i]; framePaths.insert(std::string(path)); } } AS_API(void) AsFbxExportScene(AsFbxContext* pContext) { if (pContext == nullptr) { return; } auto pScene = pContext->pScene; auto pExporter = pContext->pExporter; if (pExporter != nullptr && pScene != nullptr) { pExporter->Export(pScene); } } AS_API(FbxNode*) AsFbxGetSceneRootNode(AsFbxContext* pContext) { if (pContext == nullptr) { return nullptr; } if (pContext->pScene == nullptr) { return nullptr; } return pContext->pScene->GetRootNode(); } AS_API(FbxNode*) AsFbxExportSingleFrame(AsFbxContext* pContext, FbxNode* pParentNode, const char* pFramePath, const char* pFrameName, float localPositionX, float localPositionY, float localPositionZ, float localRotationX, float localRotationY, float localRotationZ, float localScaleX, float localScaleY, float localScaleZ) { if (pContext == nullptr || pContext->pScene == nullptr) { return nullptr; } const auto& framePaths = pContext->framePaths; if (!(framePaths.empty() || framePaths.find(pFramePath) != framePaths.end())) { return nullptr; } auto pFrameNode = FbxNode::Create(pContext->pScene, pFrameName); pFrameNode->LclScaling.Set(FbxDouble3(localScaleX, localScaleY, localScaleZ)); pFrameNode->LclRotation.Set(FbxDouble3(localRotationX, localRotationY, localRotationZ)); pFrameNode->LclTranslation.Set(FbxDouble3(localPositionX, localPositionY, localPositionZ)); pFrameNode->SetPreferedAngle(pFrameNode->LclRotation.Get()); pParentNode->AddChild(pFrameNode); if (pContext->pBindPose != nullptr) { pContext->pBindPose->Add(pFrameNode, pFrameNode->EvaluateGlobalTransform()); } return pFrameNode; } AS_API(void) AsFbxSetJointsNode_CastToBone(AsFbxContext* pContext, FbxNode* pNode, float boneSize) { if (pContext == nullptr || pContext->pScene == nullptr) { return; } if (pNode == nullptr) { return; } FbxSkeleton* pJoint = FbxSkeleton::Create(pContext->pScene, ""); pJoint->Size.Set(FbxDouble(boneSize)); pJoint->SetSkeletonType(FbxSkeleton::eLimbNode); pNode->SetNodeAttribute(pJoint); } AS_API(void) AsFbxSetJointsNode_BoneInPath(AsFbxContext* pContext, FbxNode* pNode, float boneSize) { if (pContext == nullptr || pContext->pScene == nullptr) { return; } if (pNode == nullptr) { return; } FbxSkeleton* pJoint = FbxSkeleton::Create(pContext->pScene, ""); pJoint->Size.Set(FbxDouble(boneSize)); pJoint->SetSkeletonType(FbxSkeleton::eLimbNode); pNode->SetNodeAttribute(pJoint); pJoint = FbxSkeleton::Create(pContext->pScene, ""); pJoint->Size.Set(FbxDouble(boneSize)); pJoint->SetSkeletonType(FbxSkeleton::eLimbNode); pNode->GetParent()->SetNodeAttribute(pJoint); } AS_API(void) AsFbxSetJointsNode_Generic(AsFbxContext* pContext, FbxNode* pNode) { if (pContext == nullptr || pContext->pScene == nullptr) { return; } if (pNode == nullptr) { return; } FbxNull* pNull = FbxNull::Create(pContext->pScene, ""); if (pNode->GetChildCount() > 0) { pNull->Look.Set(FbxNull::eNone); } pNode->SetNodeAttribute(pNull); } AS_API(void) AsFbxPrepareMaterials(AsFbxContext* pContext, int32_t materialCount, int32_t textureCount) { if (pContext == nullptr) { return; } pContext->pMaterials = new FbxArray<FbxSurfacePhong*>(); pContext->pTextures = new FbxArray<FbxFileTexture*>(); pContext->pMaterials->Reserve(materialCount); pContext->pTextures->Reserve(textureCount); } AS_API(FbxFileTexture*) AsFbxCreateTexture(AsFbxContext* pContext, const char* pMatTexName) { if (pContext == nullptr || pContext->pScene == nullptr) { return nullptr; } auto pTex = FbxFileTexture::Create(pContext->pScene, pMatTexName); pTex->SetFileName(pMatTexName); pTex->SetTextureUse(FbxTexture::eStandard); pTex->SetMappingType(FbxTexture::eUV); pTex->SetMaterialUse(FbxFileTexture::eModelMaterial); pTex->SetSwapUV(false); pTex->SetTranslation(0.0, 0.0); pTex->SetScale(1.0, 1.0); pTex->SetRotation(0.0, 0.0); if (pContext->pTextures != nullptr) { pContext->pTextures->Add(pTex); } return pTex; } AS_API(void) AsFbxLinkTexture(int32_t dest, FbxFileTexture* pTexture, FbxSurfacePhong* pMaterial, float offsetX, float offsetY, float scaleX, float scaleY) { if (pTexture == nullptr || pMaterial == nullptr) { return; } pTexture->SetTranslation(offsetX, offsetY); pTexture->SetScale(scaleX, scaleY); FbxProperty* pProp; switch (dest) { case 0: pProp = &pMaterial->Diffuse; break; case 1: pProp = &pMaterial->NormalMap; break; case 2: pProp = &pMaterial->Specular; break; case 3: pProp = &pMaterial->Bump; break; default: pProp = nullptr; break; } if (pProp != nullptr) { pProp->ConnectSrcObject(pTexture); } } AS_API(FbxArray<FbxCluster*>*) AsFbxMeshCreateClusterArray(int32_t boneCount) { return new FbxArray<FbxCluster*>(boneCount); } AS_API(void) AsFbxMeshDisposeClusterArray(FbxArray<FbxCluster*>** ppArray) { if (ppArray == nullptr) { return; } delete (*ppArray); *ppArray = nullptr; } AS_API(FbxCluster*) AsFbxMeshCreateCluster(AsFbxContext* pContext, FbxNode* pBoneNode) { if (pContext == nullptr || pContext->pScene == nullptr) { return nullptr; } if (pBoneNode == nullptr) { return nullptr; } FbxString lClusterName = pBoneNode->GetNameOnly() + FbxString("Cluster"); FbxCluster* pCluster = FbxCluster::Create(pContext->pScene, lClusterName.Buffer()); pCluster->SetLink(pBoneNode); pCluster->SetLinkMode(FbxCluster::eTotalOne); return pCluster; } AS_API(void) AsFbxMeshAddCluster(FbxArray<FbxCluster*>* pArray, FbxCluster* pCluster) { if (pArray == nullptr) { return; } pArray->Add(pCluster); } AS_API(FbxMesh*) AsFbxMeshCreateMesh(AsFbxContext* pContext, FbxNode* pFrameNode) { if (pContext == nullptr || pContext->pScene == nullptr) { return nullptr; } if (pFrameNode == nullptr) { return nullptr; } FbxMesh* pMesh = FbxMesh::Create(pContext->pScene, pFrameNode->GetName()); pFrameNode->SetNodeAttribute(pMesh); return pMesh; } AS_API(void) AsFbxMeshInitControlPoints(FbxMesh* pMesh, int32_t vertexCount) { if (pMesh == nullptr) { return; } pMesh->InitControlPoints(vertexCount); } AS_API(void) AsFbxMeshCreateElementNormal(FbxMesh* pMesh) { if (pMesh == nullptr) { return; } auto pNormal = pMesh->CreateElementNormal(); pNormal->SetMappingMode(FbxGeometryElement::eByControlPoint); pNormal->SetReferenceMode(FbxGeometryElement::eDirect); } AS_API(void) AsFbxMeshCreateDiffuseUV(FbxMesh* pMesh, int32_t uv) { if (pMesh == nullptr) { return; } auto pUV = pMesh->CreateElementUV(FbxString("UV") + FbxString(uv), FbxLayerElement::eTextureDiffuse); pUV->SetMappingMode(FbxGeometryElement::eByControlPoint); pUV->SetReferenceMode(FbxGeometryElement::eDirect); } AS_API(void) AsFbxMeshCreateNormalMapUV(FbxMesh* pMesh, int32_t uv) { if (pMesh == nullptr) { return; } auto pUV = pMesh->CreateElementUV(FbxString("UV") + FbxString(uv), FbxLayerElement::eTextureNormalMap); pUV->SetMappingMode(FbxGeometryElement::eByControlPoint); pUV->SetReferenceMode(FbxGeometryElement::eDirect); } AS_API(void) AsFbxMeshCreateElementTangent(FbxMesh* pMesh) { if (pMesh == nullptr) { return; } auto pTangent = pMesh->CreateElementTangent(); pTangent->SetMappingMode(FbxGeometryElement::eByControlPoint); pTangent->SetReferenceMode(FbxGeometryElement::eDirect); } AS_API(void) AsFbxMeshCreateElementVertexColor(FbxMesh* pMesh) { if (pMesh == nullptr) { return; } auto pVertexColor = pMesh->CreateElementVertexColor(); pVertexColor->SetMappingMode(FbxGeometryElement::eByControlPoint); pVertexColor->SetReferenceMode(FbxGeometryElement::eDirect); } AS_API(void) AsFbxMeshCreateElementMaterial(FbxMesh* pMesh) { if (pMesh == nullptr) { return; } auto pMaterial = pMesh->CreateElementMaterial(); pMaterial->SetMappingMode(FbxGeometryElement::eByPolygon); pMaterial->SetReferenceMode(FbxGeometryElement::eIndexToDirect); } AS_API(FbxSurfacePhong*) AsFbxCreateMaterial(AsFbxContext* pContext, const char* pMatName, float diffuseR, float diffuseG, float diffuseB, float ambientR, float ambientG, float ambientB, float emissiveR, float emissiveG, float emissiveB, float specularR, float specularG, float specularB, float reflectR, float reflectG, float reflectB, float shininess, float transparency) { if (pContext == nullptr || pContext->pScene == nullptr) { return nullptr; } if (pMatName == nullptr) { return nullptr; } auto pMat = FbxSurfacePhong::Create(pContext->pScene, pMatName); pMat->Diffuse.Set(FbxDouble3(diffuseR, diffuseG, diffuseB)); pMat->Ambient.Set(FbxDouble3(ambientR, ambientG, ambientB)); pMat->Emissive.Set(FbxDouble3(emissiveR, emissiveG, emissiveB)); pMat->Specular.Set(FbxDouble3(specularR, specularG, specularB)); pMat->Reflection.Set(FbxDouble3(reflectR, reflectG, reflectB)); pMat->Shininess.Set(FbxDouble(shininess)); pMat->TransparencyFactor.Set(FbxDouble(transparency)); pMat->ShadingModel.Set("Phong"); if (pContext->pMaterials) { pContext->pMaterials->Add(pMat); } return pMat; } AS_API(int32_t) AsFbxAddMaterialToFrame(FbxNode* pFrameNode, FbxSurfacePhong* pMaterial) { if (pFrameNode == nullptr || pMaterial == nullptr) { return 0; } return pFrameNode->AddMaterial(pMaterial); } AS_API(void) AsFbxSetFrameShadingModeToTextureShading(FbxNode* pFrameNode) { if (pFrameNode == nullptr) { return; } pFrameNode->SetShadingMode(FbxNode::eTextureShading); } AS_API(void) AsFbxMeshSetControlPoint(FbxMesh* pMesh, int32_t index, float x, float y, float z) { if (pMesh == nullptr) { return; } auto pControlPoints = pMesh->GetControlPoints(); pControlPoints[index] = FbxVector4(x, y, z, 0); } AS_API(void) AsFbxMeshAddPolygon(FbxMesh* pMesh, int32_t materialIndex, int32_t index0, int32_t index1, int32_t index2) { if (pMesh == nullptr) { return; } pMesh->BeginPolygon(materialIndex); pMesh->AddPolygon(index0); pMesh->AddPolygon(index1); pMesh->AddPolygon(index2); pMesh->EndPolygon(); } AS_API(void) AsFbxMeshElementNormalAdd(FbxMesh* pMesh, int32_t elementIndex, float x, float y, float z) { if (pMesh == nullptr) { return; } auto pElem = pMesh->GetElementNormal(elementIndex); auto& array = pElem->GetDirectArray(); array.Add(FbxVector4(x, y, z, 0)); } AS_API(void) AsFbxMeshElementUVAdd(FbxMesh* pMesh, int32_t elementIndex, float u, float v) { if (pMesh == nullptr) { return; } auto pElem = pMesh->GetElementUV(FbxString("UV") + FbxString(elementIndex)); auto& array = pElem->GetDirectArray(); array.Add(FbxVector2(u, v)); } AS_API(void) AsFbxMeshElementTangentAdd(FbxMesh* pMesh, int32_t elementIndex, float x, float y, float z, float w) { if (pMesh == nullptr) { return; } auto pElem = pMesh->GetElementTangent(elementIndex); auto& array = pElem->GetDirectArray(); array.Add(FbxVector4(x, y, z, w)); } AS_API(void) AsFbxMeshElementVertexColorAdd(FbxMesh* pMesh, int32_t elementIndex, float r, float g, float b, float a) { if (pMesh == nullptr) { return; } auto pElem = pMesh->GetElementVertexColor(elementIndex); auto& array = pElem->GetDirectArray(); array.Add(FbxVector4(r, g, b, a)); } AS_API(void) AsFbxMeshSetBoneWeight(FbxArray<FbxCluster*>* pClusterArray, int32_t boneIndex, int32_t vertexIndex, float weight) { if (pClusterArray == nullptr) { return; } auto pCluster = pClusterArray->GetAt(boneIndex); if (pCluster != nullptr) { pCluster->AddControlPointIndex(vertexIndex, weight); } } AS_API(AsFbxSkinContext*) AsFbxMeshCreateSkinContext(AsFbxContext* pContext, FbxNode* pFrameNode) { return new AsFbxSkinContext(pContext, pFrameNode); } AS_API(void) AsFbxMeshDisposeSkinContext(AsFbxSkinContext** ppSkinContext) { if (ppSkinContext == nullptr) { return; } delete (*ppSkinContext); *ppSkinContext = nullptr; } AS_API(bool32_t) FbxClusterArray_HasItemAt(FbxArray<FbxCluster*>* pClusterArray, int32_t index) { if (pClusterArray == nullptr) { return false; } auto pCluster = pClusterArray->GetAt(index); return pCluster != nullptr; } static inline int32_t IndexFrom4x4(int32_t m, int32_t n) { return m * 4 + n; } AS_API(void) AsFbxMeshSkinAddCluster(AsFbxSkinContext* pSkinContext, FbxArray<FbxCluster*>* pClusterArray, int32_t index, float pBoneMatrix[16]) { if (pSkinContext == nullptr) { return; } if (pClusterArray == nullptr) { return; } if (pBoneMatrix == nullptr) { return; } auto pCluster = pClusterArray->GetAt(index); if (pCluster == nullptr) { return; } FbxAMatrix boneMatrix; for (int m = 0; m < 4; m += 1) { for (int n = 0; n < 4; n += 1) { auto index = IndexFrom4x4(m, n); boneMatrix.mData[m][n] = pBoneMatrix[index]; } } pCluster->SetTransformMatrix(pSkinContext->lMeshMatrix); pCluster->SetTransformLinkMatrix(pSkinContext->lMeshMatrix * boneMatrix.Inverse()); if (pSkinContext->pSkin) { pSkinContext->pSkin->AddCluster(pCluster); } } AS_API(void) AsFbxMeshAddDeformer(AsFbxSkinContext* pSkinContext, FbxMesh* pMesh) { if (pSkinContext == nullptr || pSkinContext->pSkin == nullptr) { return; } if (pMesh == nullptr) { return; } if (pSkinContext->pSkin->GetClusterCount() > 0) { pMesh->AddDeformer(pSkinContext->pSkin); } } AS_API(AsFbxAnimContext*) AsFbxAnimCreateContext(bool32_t eulerFilter) { return new AsFbxAnimContext(eulerFilter); } AS_API(void) AsFbxAnimDisposeContext(AsFbxAnimContext** ppAnimContext) { if (ppAnimContext == nullptr) { return; } delete (*ppAnimContext); *ppAnimContext = nullptr; } AS_API(void) AsFbxAnimPrepareStackAndLayer(AsFbxContext* pContext, AsFbxAnimContext* pAnimContext, const char* pTakeName) { if (pContext == nullptr || pContext->pScene == nullptr) { return; } if (pAnimContext == nullptr) { return; } if (pTakeName == nullptr) { return; } pAnimContext->lAnimStack = FbxAnimStack::Create(pContext->pScene, pTakeName); pAnimContext->lAnimLayer = FbxAnimLayer::Create(pContext->pScene, "Base Layer"); pAnimContext->lAnimStack->AddMember(pAnimContext->lAnimLayer); } AS_API(void) AsFbxAnimLoadCurves(FbxNode* pNode, AsFbxAnimContext* pAnimContext) { if (pNode == nullptr) { return; } if (pAnimContext == nullptr) { return; } pAnimContext->lCurveSX = pNode->LclScaling.GetCurve(pAnimContext->lAnimLayer, FBXSDK_CURVENODE_COMPONENT_X, true); pAnimContext->lCurveSY = pNode->LclScaling.GetCurve(pAnimContext->lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y, true); pAnimContext->lCurveSZ = pNode->LclScaling.GetCurve(pAnimContext->lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z, true); pAnimContext->lCurveRX = pNode->LclRotation.GetCurve(pAnimContext->lAnimLayer, FBXSDK_CURVENODE_COMPONENT_X, true); pAnimContext->lCurveRY = pNode->LclRotation.GetCurve(pAnimContext->lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y, true); pAnimContext->lCurveRZ = pNode->LclRotation.GetCurve(pAnimContext->lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z, true); pAnimContext->lCurveTX = pNode->LclTranslation.GetCurve(pAnimContext->lAnimLayer, FBXSDK_CURVENODE_COMPONENT_X, true); pAnimContext->lCurveTY = pNode->LclTranslation.GetCurve(pAnimContext->lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y, true); pAnimContext->lCurveTZ = pNode->LclTranslation.GetCurve(pAnimContext->lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z, true); } AS_API(void) AsFbxAnimBeginKeyModify(AsFbxAnimContext* pAnimContext) { if (pAnimContext == nullptr) { return; } pAnimContext->lCurveSX->KeyModifyBegin(); pAnimContext->lCurveSY->KeyModifyBegin(); pAnimContext->lCurveSZ->KeyModifyBegin(); pAnimContext->lCurveRX->KeyModifyBegin(); pAnimContext->lCurveRY->KeyModifyBegin(); pAnimContext->lCurveRZ->KeyModifyBegin(); pAnimContext->lCurveTX->KeyModifyBegin(); pAnimContext->lCurveTY->KeyModifyBegin(); pAnimContext->lCurveTZ->KeyModifyBegin(); } AS_API(void) AsFbxAnimEndKeyModify(AsFbxAnimContext* pAnimContext) { if (pAnimContext == nullptr) { return; } pAnimContext->lCurveSX->KeyModifyEnd(); pAnimContext->lCurveSY->KeyModifyEnd(); pAnimContext->lCurveSZ->KeyModifyEnd(); pAnimContext->lCurveRX->KeyModifyEnd(); pAnimContext->lCurveRY->KeyModifyEnd(); pAnimContext->lCurveRZ->KeyModifyEnd(); pAnimContext->lCurveTX->KeyModifyEnd(); pAnimContext->lCurveTY->KeyModifyEnd(); pAnimContext->lCurveTZ->KeyModifyEnd(); } AS_API(void) AsFbxAnimAddScalingKey(AsFbxAnimContext* pAnimContext, float time, float x, float y, float z) { if (pAnimContext == nullptr) { return; } FbxTime lTime; lTime.SetSecondDouble(time); pAnimContext->lCurveSX->KeySet(pAnimContext->lCurveSX->KeyAdd(lTime), lTime, x); pAnimContext->lCurveSY->KeySet(pAnimContext->lCurveSY->KeyAdd(lTime), lTime, y); pAnimContext->lCurveSZ->KeySet(pAnimContext->lCurveSZ->KeyAdd(lTime), lTime, z); } AS_API(void) AsFbxAnimAddRotationKey(AsFbxAnimContext* pAnimContext, float time, float x, float y, float z) { if (pAnimContext == nullptr) { return; } FbxTime lTime; lTime.SetSecondDouble(time); pAnimContext->lCurveRX->KeySet(pAnimContext->lCurveRX->KeyAdd(lTime), lTime, x); pAnimContext->lCurveRY->KeySet(pAnimContext->lCurveRY->KeyAdd(lTime), lTime, y); pAnimContext->lCurveRZ->KeySet(pAnimContext->lCurveRZ->KeyAdd(lTime), lTime, z); } AS_API(void) AsFbxAnimAddTranslationKey(AsFbxAnimContext* pAnimContext, float time, float x, float y, float z) { if (pAnimContext == nullptr) { return; } FbxTime lTime; lTime.SetSecondDouble(time); pAnimContext->lCurveTX->KeySet(pAnimContext->lCurveTX->KeyAdd(lTime), lTime, x); pAnimContext->lCurveTY->KeySet(pAnimContext->lCurveTY->KeyAdd(lTime), lTime, y); pAnimContext->lCurveTZ->KeySet(pAnimContext->lCurveTZ->KeyAdd(lTime), lTime, z); } AS_API(void) AsFbxAnimApplyEulerFilter(AsFbxAnimContext* pAnimContext, float filterPrecision) { if (pAnimContext == nullptr || pAnimContext->lFilter == nullptr) { return; } FbxAnimCurve* lCurve[3]; lCurve[0] = pAnimContext->lCurveRX; lCurve[1] = pAnimContext->lCurveRY; lCurve[2] = pAnimContext->lCurveRZ; auto eulerFilter = pAnimContext->lFilter; eulerFilter->Reset(); eulerFilter->SetQualityTolerance(filterPrecision); eulerFilter->Apply(lCurve, 3); } AS_API(int32_t) AsFbxAnimGetCurrentBlendShapeChannelCount(AsFbxAnimContext* pAnimContext, fbxsdk::FbxNode* pNode) { if (pAnimContext == nullptr) { return 0; } if (pNode == nullptr) { return 0; } auto pMesh = pNode->GetMesh(); pAnimContext->pMesh = pMesh; if (pMesh == nullptr) { return 0; } auto blendShapeDeformerCount = pMesh->GetDeformerCount(FbxDeformer::eBlendShape); if (blendShapeDeformerCount <= 0) { return 0; } auto lBlendShape = (FbxBlendShape*)pMesh->GetDeformer(0, FbxDeformer::eBlendShape); pAnimContext->lBlendShape = lBlendShape; if (lBlendShape == nullptr) { return 0; } auto lBlendShapeChannelCount = lBlendShape->GetBlendShapeChannelCount(); return lBlendShapeChannelCount; } AS_API(bool32_t) AsFbxAnimIsBlendShapeChannelMatch(AsFbxAnimContext* pAnimContext, int32_t channelIndex, const char* channelName) { if (pAnimContext == nullptr || pAnimContext->lBlendShape == nullptr) { return false; } if (channelName == nullptr) { return false; } FbxBlendShapeChannel* lChannel = pAnimContext->lBlendShape->GetBlendShapeChannel(channelIndex); auto lChannelName = lChannel->GetNameOnly(); FbxString chanName(channelName); return lChannelName == chanName; } AS_API(void) AsFbxAnimBeginBlendShapeAnimCurve(AsFbxAnimContext* pAnimContext, int32_t channelIndex) { if (pAnimContext == nullptr || pAnimContext->pMesh == nullptr || pAnimContext->lAnimLayer == nullptr) { return; } pAnimContext->lAnimCurve = pAnimContext->pMesh->GetShapeChannel(0, channelIndex, pAnimContext->lAnimLayer, true); pAnimContext->lAnimCurve->KeyModifyBegin(); } AS_API(void) AsFbxAnimEndBlendShapeAnimCurve(AsFbxAnimContext* pAnimContext) { if (pAnimContext == nullptr || pAnimContext->lAnimCurve == nullptr) { return; } pAnimContext->lAnimCurve->KeyModifyEnd(); } AS_API(void) AsFbxAnimAddBlendShapeKeyframe(AsFbxAnimContext* pAnimContext, float time, float value) { if (pAnimContext == nullptr || pAnimContext->lAnimCurve == nullptr) { return; } FbxTime lTime; lTime.SetSecondDouble(time); auto keyIndex = pAnimContext->lAnimCurve->KeyAdd(lTime); pAnimContext->lAnimCurve->KeySetValue(keyIndex, value); pAnimContext->lAnimCurve->KeySetInterpolation(keyIndex, FbxAnimCurveDef::eInterpolationCubic); } AS_API(AsFbxMorphContext*) AsFbxMorphCreateContext() { return new AsFbxMorphContext(); } AS_API(void) AsFbxMorphInitializeContext(AsFbxContext* pContext, AsFbxMorphContext* pMorphContext, fbxsdk::FbxNode* pNode) { if (pContext == nullptr || pContext->pScene == nullptr) { return; } if (pMorphContext == nullptr) { return; } if (pNode == nullptr) { return; } auto pMesh = pNode->GetMesh(); pMorphContext->pMesh = pMesh; auto lBlendShape = FbxBlendShape::Create(pContext->pScene, pMesh->GetNameOnly() + FbxString("BlendShape")); pMorphContext->lBlendShape = lBlendShape; pMesh->AddDeformer(lBlendShape); } AS_API(void) AsFbxMorphDisposeContext(AsFbxMorphContext** ppMorphContext) { if (ppMorphContext == nullptr) { return; } delete (*ppMorphContext); *ppMorphContext = nullptr; } AS_API(void) AsFbxMorphAddBlendShapeChannel(AsFbxContext* pContext, AsFbxMorphContext* pMorphContext, const char* channelName) { if (pContext == nullptr || pContext->pScene == nullptr) { return; } if (pMorphContext == nullptr) { return; } if (channelName == nullptr) { return; } auto lBlendShapeChannel = FbxBlendShapeChannel::Create(pContext->pScene, channelName); pMorphContext->lBlendShapeChannel = lBlendShapeChannel; if (pMorphContext->lBlendShape != nullptr) { pMorphContext->lBlendShape->AddBlendShapeChannel(lBlendShapeChannel); } } AS_API(void) AsFbxMorphAddBlendShapeChannelShape(AsFbxContext* pContext, AsFbxMorphContext* pMorphContext, float weight, const char* shapeName) { if (pContext == nullptr || pContext->pScene == nullptr) { return; } if (pMorphContext == nullptr) { return; } auto lShape = FbxShape::Create(pContext->pScene, shapeName); pMorphContext->lShape = lShape; if (pMorphContext->lBlendShapeChannel != nullptr) { pMorphContext->lBlendShapeChannel->AddTargetShape(lShape, weight); } } AS_API(void) AsFbxMorphCopyBlendShapeControlPoints(AsFbxMorphContext* pMorphContext) { if (pMorphContext == nullptr || pMorphContext->pMesh == nullptr || pMorphContext->lShape == nullptr) { return; } auto vectorCount = pMorphContext->pMesh->GetControlPointsCount(); auto srcControlPoints = pMorphContext->pMesh->GetControlPoints(); pMorphContext->lShape->InitControlPoints(vectorCount); for (int j = 0; j < vectorCount; j++) { pMorphContext->lShape->SetControlPointAt(FbxVector4(srcControlPoints[j]), j);; } } AS_API(void) AsFbxMorphSetBlendShapeVertex(AsFbxMorphContext* pMorphContext, uint32_t index, float x, float y, float z) { if (pMorphContext == nullptr || pMorphContext->lShape == nullptr) { return; } pMorphContext->lShape->SetControlPointAt(FbxVector4(x, y, z, 0), index); } AS_API(void) AsFbxMorphCopyBlendShapeControlPointsNormal(AsFbxMorphContext* pMorphContext) { if (pMorphContext == nullptr || pMorphContext->pMesh == nullptr || pMorphContext->lShape == nullptr) { return; } pMorphContext->lShape->InitNormals(pMorphContext->pMesh); } AS_API(void) AsFbxMorphSetBlendShapeVertexNormal(AsFbxMorphContext* pMorphContext, uint32_t index, float x, float y, float z) { if (pMorphContext == nullptr || pMorphContext->lShape == nullptr) { return; } pMorphContext->lShape->SetControlPointNormalAt(FbxVector4(x, y, z, 0), index); }
AssetStudio/AssetStudioFBXNative/api.cpp/0
{ "file_path": "AssetStudio/AssetStudioFBXNative/api.cpp", "repo_id": "AssetStudio", "token_count": 11222 }
76
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>net472;netstandard2.0;net5.0;net6.0</TargetFrameworks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <Version>0.16.0.0</Version> <AssemblyVersion>0.16.0.0</AssemblyVersion> <FileVersion>0.16.0.0</FileVersion> <Copyright>Copyright © Perfare 2018-2022; Copyright © hozuki 2020</Copyright> <DebugType>embedded</DebugType> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AssetStudio.PInvoke\AssetStudio.PInvoke.csproj" /> <ProjectReference Include="..\AssetStudio\AssetStudio.csproj" /> </ItemGroup> </Project>
AssetStudio/AssetStudioFBXWrapper/AssetStudioFBXWrapper.csproj/0
{ "file_path": "AssetStudio/AssetStudioFBXWrapper/AssetStudioFBXWrapper.csproj", "repo_id": "AssetStudio", "token_count": 235 }
77
using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace AssetStudioGUI { public sealed class DirectBitmap : IDisposable { public DirectBitmap(byte[] buff, int width, int height) { Width = width; Height = height; Bits = buff; m_handle = GCHandle.Alloc(Bits, GCHandleType.Pinned); m_bitmap = new Bitmap(Width, Height, Stride, PixelFormat.Format32bppArgb, m_handle.AddrOfPinnedObject()); } private void Dispose(bool disposing) { if (disposing) { m_bitmap.Dispose(); m_handle.Free(); } m_bitmap = null; } public void Dispose() { Dispose(true); } public int Height { get; } public int Width { get; } public int Stride => Width * 4; public byte[] Bits { get; } public Bitmap Bitmap => m_bitmap; private Bitmap m_bitmap; private readonly GCHandle m_handle; } }
AssetStudio/AssetStudioGUI/DirectBitmap.cs/0
{ "file_path": "AssetStudio/AssetStudioGUI/DirectBitmap.cs", "repo_id": "AssetStudio", "token_count": 552 }
78
using AssetStudio; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Windows.Forms; using System.Xml.Linq; using static AssetStudioGUI.Exporter; using Object = AssetStudio.Object; namespace AssetStudioGUI { internal enum ExportType { Convert, Raw, Dump } internal enum ExportFilter { All, Selected, Filtered } internal enum ExportListType { XML } internal static class Studio { public static AssetsManager assetsManager = new AssetsManager(); public static AssemblyLoader assemblyLoader = new AssemblyLoader(); public static List<AssetItem> exportableAssets = new List<AssetItem>(); public static List<AssetItem> visibleAssets = new List<AssetItem>(); internal static Action<string> StatusStripUpdate = x => { }; public static int ExtractFolder(string path, string savePath) { int extractedCount = 0; Progress.Reset(); var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories); for (int i = 0; i < files.Length; i++) { var file = files[i]; var fileOriPath = Path.GetDirectoryName(file); var fileSavePath = fileOriPath.Replace(path, savePath); extractedCount += ExtractFile(file, fileSavePath); Progress.Report(i + 1, files.Length); } return extractedCount; } public static int ExtractFile(string[] fileNames, string savePath) { int extractedCount = 0; Progress.Reset(); for (var i = 0; i < fileNames.Length; i++) { var fileName = fileNames[i]; extractedCount += ExtractFile(fileName, savePath); Progress.Report(i + 1, fileNames.Length); } return extractedCount; } public static int ExtractFile(string fileName, string savePath) { int extractedCount = 0; var reader = new FileReader(fileName); if (reader.FileType == FileType.BundleFile) extractedCount += ExtractBundleFile(reader, savePath); else if (reader.FileType == FileType.WebFile) extractedCount += ExtractWebDataFile(reader, savePath); else reader.Dispose(); return extractedCount; } private static int ExtractBundleFile(FileReader reader, string savePath) { StatusStripUpdate($"Decompressing {reader.FileName} ..."); var bundleFile = new BundleFile(reader); reader.Dispose(); if (bundleFile.fileList.Length > 0) { var extractPath = Path.Combine(savePath, reader.FileName + "_unpacked"); return ExtractStreamFile(extractPath, bundleFile.fileList); } return 0; } private static int ExtractWebDataFile(FileReader reader, string savePath) { StatusStripUpdate($"Decompressing {reader.FileName} ..."); var webFile = new WebFile(reader); reader.Dispose(); if (webFile.fileList.Length > 0) { var extractPath = Path.Combine(savePath, reader.FileName + "_unpacked"); return ExtractStreamFile(extractPath, webFile.fileList); } return 0; } private static int ExtractStreamFile(string extractPath, StreamFile[] fileList) { int extractedCount = 0; foreach (var file in fileList) { var filePath = Path.Combine(extractPath, file.path); var fileDirectory = Path.GetDirectoryName(filePath); if (!Directory.Exists(fileDirectory)) { Directory.CreateDirectory(fileDirectory); } if (!File.Exists(filePath)) { using (var fileStream = File.Create(filePath)) { file.stream.CopyTo(fileStream); } extractedCount += 1; } file.stream.Dispose(); } return extractedCount; } public static (string, List<TreeNode>) BuildAssetData() { StatusStripUpdate("Building asset list..."); string productName = null; var objectCount = assetsManager.assetsFileList.Sum(x => x.Objects.Count); var objectAssetItemDic = new Dictionary<Object, AssetItem>(objectCount); var containers = new List<(PPtr<Object>, string)>(); int i = 0; Progress.Reset(); foreach (var assetsFile in assetsManager.assetsFileList) { foreach (var asset in assetsFile.Objects) { var assetItem = new AssetItem(asset); objectAssetItemDic.Add(asset, assetItem); assetItem.UniqueID = " #" + i; var exportable = false; switch (asset) { case GameObject m_GameObject: assetItem.Text = m_GameObject.m_Name; break; case Texture2D m_Texture2D: if (!string.IsNullOrEmpty(m_Texture2D.m_StreamData?.path)) assetItem.FullSize = asset.byteSize + m_Texture2D.m_StreamData.size; assetItem.Text = m_Texture2D.m_Name; exportable = true; break; case AudioClip m_AudioClip: if (!string.IsNullOrEmpty(m_AudioClip.m_Source)) assetItem.FullSize = asset.byteSize + m_AudioClip.m_Size; assetItem.Text = m_AudioClip.m_Name; exportable = true; break; case VideoClip m_VideoClip: if (!string.IsNullOrEmpty(m_VideoClip.m_OriginalPath)) assetItem.FullSize = asset.byteSize + (long)m_VideoClip.m_ExternalResources.m_Size; assetItem.Text = m_VideoClip.m_Name; exportable = true; break; case Shader m_Shader: assetItem.Text = m_Shader.m_ParsedForm?.m_Name ?? m_Shader.m_Name; exportable = true; break; case Mesh _: case TextAsset _: case AnimationClip _: case Font _: case MovieTexture _: case Sprite _: assetItem.Text = ((NamedObject)asset).m_Name; exportable = true; break; case Animator m_Animator: if (m_Animator.m_GameObject.TryGet(out var gameObject)) { assetItem.Text = gameObject.m_Name; } exportable = true; break; case MonoBehaviour m_MonoBehaviour: if (m_MonoBehaviour.m_Name == "" && m_MonoBehaviour.m_Script.TryGet(out var m_Script)) { assetItem.Text = m_Script.m_ClassName; } else { assetItem.Text = m_MonoBehaviour.m_Name; } exportable = true; break; case PlayerSettings m_PlayerSettings: productName = m_PlayerSettings.productName; break; case AssetBundle m_AssetBundle: foreach (var m_Container in m_AssetBundle.m_Container) { var preloadIndex = m_Container.Value.preloadIndex; var preloadSize = m_Container.Value.preloadSize; var preloadEnd = preloadIndex + preloadSize; for (int k = preloadIndex; k < preloadEnd; k++) { containers.Add((m_AssetBundle.m_PreloadTable[k], m_Container.Key)); } } assetItem.Text = m_AssetBundle.m_Name; break; case ResourceManager m_ResourceManager: foreach (var m_Container in m_ResourceManager.m_Container) { containers.Add((m_Container.Value, m_Container.Key)); } break; case NamedObject m_NamedObject: assetItem.Text = m_NamedObject.m_Name; break; } if (assetItem.Text == "") { assetItem.Text = assetItem.TypeString + assetItem.UniqueID; } if (Properties.Settings.Default.displayAll || exportable) { exportableAssets.Add(assetItem); } Progress.Report(++i, objectCount); } } foreach ((var pptr, var container) in containers) { if (pptr.TryGet(out var obj)) { objectAssetItemDic[obj].Container = container; } } foreach (var tmp in exportableAssets) { tmp.SetSubItems(); } containers.Clear(); visibleAssets = exportableAssets; StatusStripUpdate("Building tree structure..."); var treeNodeCollection = new List<TreeNode>(); var treeNodeDictionary = new Dictionary<GameObject, GameObjectTreeNode>(); var assetsFileCount = assetsManager.assetsFileList.Count; int j = 0; Progress.Reset(); foreach (var assetsFile in assetsManager.assetsFileList) { var fileNode = new TreeNode(assetsFile.fileName); //RootNode foreach (var obj in assetsFile.Objects) { if (obj is GameObject m_GameObject) { if (!treeNodeDictionary.TryGetValue(m_GameObject, out var currentNode)) { currentNode = new GameObjectTreeNode(m_GameObject); treeNodeDictionary.Add(m_GameObject, currentNode); } foreach (var pptr in m_GameObject.m_Components) { if (pptr.TryGet(out var m_Component)) { objectAssetItemDic[m_Component].TreeNode = currentNode; if (m_Component is MeshFilter m_MeshFilter) { if (m_MeshFilter.m_Mesh.TryGet(out var m_Mesh)) { objectAssetItemDic[m_Mesh].TreeNode = currentNode; } } else if (m_Component is SkinnedMeshRenderer m_SkinnedMeshRenderer) { if (m_SkinnedMeshRenderer.m_Mesh.TryGet(out var m_Mesh)) { objectAssetItemDic[m_Mesh].TreeNode = currentNode; } } } } var parentNode = fileNode; if (m_GameObject.m_Transform != null) { if (m_GameObject.m_Transform.m_Father.TryGet(out var m_Father)) { if (m_Father.m_GameObject.TryGet(out var parentGameObject)) { if (!treeNodeDictionary.TryGetValue(parentGameObject, out var parentGameObjectNode)) { parentGameObjectNode = new GameObjectTreeNode(parentGameObject); treeNodeDictionary.Add(parentGameObject, parentGameObjectNode); } parentNode = parentGameObjectNode; } } } parentNode.Nodes.Add(currentNode); } } if (fileNode.Nodes.Count > 0) { treeNodeCollection.Add(fileNode); } Progress.Report(++j, assetsFileCount); } treeNodeDictionary.Clear(); objectAssetItemDic.Clear(); return (productName, treeNodeCollection); } public static Dictionary<string, SortedDictionary<int, TypeTreeItem>> BuildClassStructure() { var typeMap = new Dictionary<string, SortedDictionary<int, TypeTreeItem>>(); foreach (var assetsFile in assetsManager.assetsFileList) { if (typeMap.TryGetValue(assetsFile.unityVersion, out var curVer)) { foreach (var type in assetsFile.m_Types.Where(x => x.m_Type != null)) { var key = type.classID; if (type.m_ScriptTypeIndex >= 0) { key = -1 - type.m_ScriptTypeIndex; } curVer[key] = new TypeTreeItem(key, type.m_Type); } } else { var items = new SortedDictionary<int, TypeTreeItem>(); foreach (var type in assetsFile.m_Types.Where(x => x.m_Type != null)) { var key = type.classID; if (type.m_ScriptTypeIndex >= 0) { key = -1 - type.m_ScriptTypeIndex; } items[key] = new TypeTreeItem(key, type.m_Type); } typeMap.Add(assetsFile.unityVersion, items); } } return typeMap; } public static void ExportAssets(string savePath, List<AssetItem> toExportAssets, ExportType exportType) { ThreadPool.QueueUserWorkItem(state => { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); int toExportCount = toExportAssets.Count; int exportedCount = 0; int i = 0; Progress.Reset(); foreach (var asset in toExportAssets) { string exportPath; switch (Properties.Settings.Default.assetGroupOption) { case 0: //type name exportPath = Path.Combine(savePath, asset.TypeString); break; case 1: //container path if (!string.IsNullOrEmpty(asset.Container)) { exportPath = Path.Combine(savePath, Path.GetDirectoryName(asset.Container)); } else { exportPath = savePath; } break; case 2: //source file if (string.IsNullOrEmpty(asset.SourceFile.originalPath)) { exportPath = Path.Combine(savePath, asset.SourceFile.fileName + "_export"); } else { exportPath = Path.Combine(savePath, Path.GetFileName(asset.SourceFile.originalPath) + "_export", asset.SourceFile.fileName); } break; default: exportPath = savePath; break; } exportPath += Path.DirectorySeparatorChar; StatusStripUpdate($"[{exportedCount}/{toExportCount}] Exporting {asset.TypeString}: {asset.Text}"); try { switch (exportType) { case ExportType.Raw: if (ExportRawFile(asset, exportPath)) { exportedCount++; } break; case ExportType.Dump: if (ExportDumpFile(asset, exportPath)) { exportedCount++; } break; case ExportType.Convert: if (ExportConvertFile(asset, exportPath)) { exportedCount++; } break; } } catch (Exception ex) { MessageBox.Show($"Export {asset.Type}:{asset.Text} error\r\n{ex.Message}\r\n{ex.StackTrace}"); } Progress.Report(++i, toExportCount); } var statusText = exportedCount == 0 ? "Nothing exported." : $"Finished exporting {exportedCount} assets."; if (toExportCount > exportedCount) { statusText += $" {toExportCount - exportedCount} assets skipped (not extractable or files already exist)"; } StatusStripUpdate(statusText); if (Properties.Settings.Default.openAfterExport && exportedCount > 0) { OpenFolderInExplorer(savePath); } }); } public static void ExportAssetsList(string savePath, List<AssetItem> toExportAssets, ExportListType exportListType) { ThreadPool.QueueUserWorkItem(state => { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); Progress.Reset(); switch (exportListType) { case ExportListType.XML: var filename = Path.Combine(savePath, "assets.xml"); var doc = new XDocument( new XElement("Assets", new XAttribute("filename", filename), new XAttribute("createdAt", DateTime.UtcNow.ToString("s")), toExportAssets.Select( asset => new XElement("Asset", new XElement("Name", asset.Text), new XElement("Container", asset.Container), new XElement("Type", new XAttribute("id", (int)asset.Type), asset.TypeString), new XElement("PathID", asset.m_PathID), new XElement("Source", asset.SourceFile.fullName), new XElement("Size", asset.FullSize) ) ) ) ); doc.Save(filename); break; } var statusText = $"Finished exporting asset list with {toExportAssets.Count()} items."; StatusStripUpdate(statusText); if (Properties.Settings.Default.openAfterExport && toExportAssets.Count() > 0) { OpenFolderInExplorer(savePath); } }); } public static void ExportSplitObjects(string savePath, TreeNodeCollection nodes) { ThreadPool.QueueUserWorkItem(state => { var count = nodes.Cast<TreeNode>().Sum(x => x.Nodes.Count); int k = 0; Progress.Reset(); foreach (TreeNode node in nodes) { //遍历一级子节点 foreach (GameObjectTreeNode j in node.Nodes) { //收集所有子节点 var gameObjects = new List<GameObject>(); CollectNode(j, gameObjects); //跳过一些不需要导出的object if (gameObjects.All(x => x.m_SkinnedMeshRenderer == null && x.m_MeshFilter == null)) { Progress.Report(++k, count); continue; } //处理非法文件名 var filename = FixFileName(j.Text); //每个文件存放在单独的文件夹 var targetPath = $"{savePath}{filename}{Path.DirectorySeparatorChar}"; //重名文件处理 for (int i = 1; ; i++) { if (Directory.Exists(targetPath)) { targetPath = $"{savePath}{filename} ({i}){Path.DirectorySeparatorChar}"; } else { break; } } Directory.CreateDirectory(targetPath); //导出FBX StatusStripUpdate($"Exporting {filename}.fbx"); try { ExportGameObject(j.gameObject, targetPath); } catch (Exception ex) { MessageBox.Show($"Export GameObject:{j.Text} error\r\n{ex.Message}\r\n{ex.StackTrace}"); } Progress.Report(++k, count); StatusStripUpdate($"Finished exporting {filename}.fbx"); } } if (Properties.Settings.Default.openAfterExport) { OpenFolderInExplorer(savePath); } StatusStripUpdate("Finished"); }); } private static void CollectNode(GameObjectTreeNode node, List<GameObject> gameObjects) { gameObjects.Add(node.gameObject); foreach (GameObjectTreeNode i in node.Nodes) { CollectNode(i, gameObjects); } } public static void ExportAnimatorWithAnimationClip(AssetItem animator, List<AssetItem> animationList, string exportPath) { ThreadPool.QueueUserWorkItem(state => { Progress.Reset(); StatusStripUpdate($"Exporting {animator.Text}"); try { ExportAnimator(animator, exportPath, animationList); if (Properties.Settings.Default.openAfterExport) { OpenFolderInExplorer(exportPath); } Progress.Report(1, 1); StatusStripUpdate($"Finished exporting {animator.Text}"); } catch (Exception ex) { MessageBox.Show($"Export Animator:{animator.Text} error\r\n{ex.Message}\r\n{ex.StackTrace}"); StatusStripUpdate("Error in export"); } }); } public static void ExportObjectsWithAnimationClip(string exportPath, TreeNodeCollection nodes, List<AssetItem> animationList = null) { ThreadPool.QueueUserWorkItem(state => { var gameObjects = new List<GameObject>(); GetSelectedParentNode(nodes, gameObjects); if (gameObjects.Count > 0) { var count = gameObjects.Count; int i = 0; Progress.Reset(); foreach (var gameObject in gameObjects) { StatusStripUpdate($"Exporting {gameObject.m_Name}"); try { ExportGameObject(gameObject, exportPath, animationList); StatusStripUpdate($"Finished exporting {gameObject.m_Name}"); } catch (Exception ex) { MessageBox.Show($"Export GameObject:{gameObject.m_Name} error\r\n{ex.Message}\r\n{ex.StackTrace}"); StatusStripUpdate("Error in export"); } Progress.Report(++i, count); } if (Properties.Settings.Default.openAfterExport) { OpenFolderInExplorer(exportPath); } } else { StatusStripUpdate("No Object selected for export."); } }); } public static void ExportObjectsMergeWithAnimationClip(string exportPath, List<GameObject> gameObjects, List<AssetItem> animationList = null) { ThreadPool.QueueUserWorkItem(state => { var name = Path.GetFileName(exportPath); Progress.Reset(); StatusStripUpdate($"Exporting {name}"); try { ExportGameObjectMerge(gameObjects, exportPath, animationList); Progress.Report(1, 1); StatusStripUpdate($"Finished exporting {name}"); } catch (Exception ex) { MessageBox.Show($"Export Model:{name} error\r\n{ex.Message}\r\n{ex.StackTrace}"); StatusStripUpdate("Error in export"); } if (Properties.Settings.Default.openAfterExport) { OpenFolderInExplorer(Path.GetDirectoryName(exportPath)); } }); } public static void GetSelectedParentNode(TreeNodeCollection nodes, List<GameObject> gameObjects) { foreach (TreeNode i in nodes) { if (i is GameObjectTreeNode gameObjectTreeNode && i.Checked) { gameObjects.Add(gameObjectTreeNode.gameObject); } else { GetSelectedParentNode(i.Nodes, gameObjects); } } } public static TypeTree MonoBehaviourToTypeTree(MonoBehaviour m_MonoBehaviour) { if (!assemblyLoader.Loaded) { var openFolderDialog = new OpenFolderDialog(); openFolderDialog.Title = "Select Assembly Folder"; if (openFolderDialog.ShowDialog() == DialogResult.OK) { assemblyLoader.Load(openFolderDialog.Folder); } else { assemblyLoader.Loaded = true; } } return m_MonoBehaviour.ConvertToTypeTree(assemblyLoader); } public static string DumpAsset(Object obj) { var str = obj.Dump(); if (str == null && obj is MonoBehaviour m_MonoBehaviour) { var type = MonoBehaviourToTypeTree(m_MonoBehaviour); str = m_MonoBehaviour.Dump(type); } return str; } public static void OpenFolderInExplorer(string path) { var info = new ProcessStartInfo(path); info.UseShellExecute = true; Process.Start(info); } } }
AssetStudio/AssetStudioGUI/Studio.cs/0
{ "file_path": "AssetStudio/AssetStudioGUI/Studio.cs", "repo_id": "AssetStudio", "token_count": 17900 }
79
/*$ preserve start $*/ /* ========================================================================================== */ /* FMOD Studio - DSP header file. Copyright (c), Firelight Technologies Pty, Ltd. 2004-2016. */ /* */ /* Use this header if you are interested in delving deeper into the FMOD software mixing / */ /* DSP engine. In this header you can find parameter structures for FMOD system registered */ /* DSP effects and generators. */ /* */ /* ========================================================================================== */ using System; using System.Text; using System.Runtime.InteropServices; namespace FMOD { /*$ preserve end $*/ /* [STRUCTURE] [ [DESCRIPTION] Structure for FMOD_DSP_PROCESS_CALLBACK input and output buffers. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] FMOD_DSP_DESCRIPTION ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_BUFFER_ARRAY { public int numbuffers; /* [r/w] number of buffers */ public int[] buffernumchannels; /* [r/w] array of number of channels for each buffer */ public CHANNELMASK[] bufferchannelmask; /* [r/w] array of channel masks for each buffer */ public IntPtr[] buffers; /* [r/w] array of buffers */ public SPEAKERMODE speakermode; /* [r/w] speaker mode for all buffers in the array */ } /* [ENUM] [ [DESCRIPTION] Operation type for FMOD_DSP_PROCESS_CALLBACK. [REMARKS] [SEE_ALSO] FMOD_DSP_DESCRIPTION ] */ public enum DSP_PROCESS_OPERATION { PROCESS_PERFORM = 0, /* Process the incoming audio in 'inbufferarray' and output to 'outbufferarray'. */ PROCESS_QUERY /* The DSP is being queried for the expected output format and whether it needs to process audio or should be bypassed. The function should return any value other than FMOD_OK if audio can pass through unprocessed. If audio is to be processed, 'outbufferarray' must be filled with the expected output format, channel count and mask. */ } /* [STRUCTURE] [ [DESCRIPTION] Complex number structure used for holding FFT frequency domain-data for FMOD_FFTREAL and FMOD_IFFTREAL DSP callbacks. [REMARKS] [SEE_ALSO] FMOD_DSP_STATE_SYSTEMCALLBACKS ] */ [StructLayout(LayoutKind.Sequential)] public struct COMPLEX { public float real; /* Real component */ public float imag; /* Imaginary component */ } /* [ENUM] [ [DESCRIPTION] Flags for the FMOD_DSP_PAN_SUM_SURROUND_MATRIX callback. [REMARKS] This functionality is experimental, please contact [email protected] for more information. [SEE_ALSO] FMOD_DSP_STATE_PAN_CALLBACKS ] */ public enum DSP_PAN_SURROUND_FLAGS { DEFAULT = 0, ROTATION_NOT_BIASED = 1, } /* DSP callbacks */ public delegate RESULT DSP_CREATECALLBACK (ref DSP_STATE dsp_state); public delegate RESULT DSP_RELEASECALLBACK (ref DSP_STATE dsp_state); public delegate RESULT DSP_RESETCALLBACK (ref DSP_STATE dsp_state); public delegate RESULT DSP_SETPOSITIONCALLBACK (ref DSP_STATE dsp_state, uint pos); public delegate RESULT DSP_READCALLBACK (ref DSP_STATE dsp_state, IntPtr inbuffer, IntPtr outbuffer, uint length, int inchannels, ref int outchannels); public delegate RESULT DSP_SHOULDIPROCESS_CALLBACK (ref DSP_STATE dsp_state, bool inputsidle, uint length, CHANNELMASK inmask, int inchannels, SPEAKERMODE speakermode); public delegate RESULT DSP_PROCESS_CALLBACK (ref DSP_STATE dsp_state, uint length, ref DSP_BUFFER_ARRAY inbufferarray, ref DSP_BUFFER_ARRAY outbufferarray, bool inputsidle, DSP_PROCESS_OPERATION op); public delegate RESULT DSP_SETPARAM_FLOAT_CALLBACK (ref DSP_STATE dsp_state, int index, float value); public delegate RESULT DSP_SETPARAM_INT_CALLBACK (ref DSP_STATE dsp_state, int index, int value); public delegate RESULT DSP_SETPARAM_BOOL_CALLBACK (ref DSP_STATE dsp_state, int index, bool value); public delegate RESULT DSP_SETPARAM_DATA_CALLBACK (ref DSP_STATE dsp_state, int index, IntPtr data, uint length); public delegate RESULT DSP_GETPARAM_FLOAT_CALLBACK (ref DSP_STATE dsp_state, int index, ref float value, IntPtr valuestr); public delegate RESULT DSP_GETPARAM_INT_CALLBACK (ref DSP_STATE dsp_state, int index, ref int value, IntPtr valuestr); public delegate RESULT DSP_GETPARAM_BOOL_CALLBACK (ref DSP_STATE dsp_state, int index, ref bool value, IntPtr valuestr); public delegate RESULT DSP_GETPARAM_DATA_CALLBACK (ref DSP_STATE dsp_state, int index, ref IntPtr data, ref uint length, IntPtr valuestr); public delegate RESULT DSP_SYSTEM_REGISTER_CALLBACK (ref DSP_STATE dsp_state); public delegate RESULT DSP_SYSTEM_DEREGISTER_CALLBACK (ref DSP_STATE dsp_state); public delegate RESULT DSP_SYSTEM_MIX_CALLBACK (ref DSP_STATE dsp_state, int stage); public delegate RESULT DSP_SYSTEM_GETSAMPLERATE (ref DSP_STATE dsp_state, ref int rate); public delegate RESULT DSP_SYSTEM_GETBLOCKSIZE (ref DSP_STATE dsp_state, ref uint blocksize); public delegate RESULT DSP_SYSTEM_GETSPEAKERMODE (ref DSP_STATE dsp_state, ref int speakermode_mixer, ref int speakermode_output); public delegate RESULT DSP_DFT_FFTREAL (ref DSP_STATE dsp_state, int size, IntPtr signal, IntPtr dft, IntPtr window, int signalhop); public delegate RESULT DSP_DFT_IFFTREAL (ref DSP_STATE dsp_state, int size, IntPtr dft, IntPtr signal, IntPtr window, int signalhop); public delegate RESULT DSP_PAN_SUM_MONO_MATRIX (ref DSP_STATE dsp_state, int sourceSpeakerMode, float lowFrequencyGain, float overallGain, IntPtr matrix); public delegate RESULT DSP_PAN_SUM_STEREO_MATRIX (ref DSP_STATE dsp_state, int sourceSpeakerMode, float pan, float lowFrequencyGain, float overallGain, int matrixHop, IntPtr matrix); public delegate RESULT DSP_PAN_SUM_SURROUND_MATRIX (ref DSP_STATE dsp_state, int sourceSpeakerMode, int targetSpeakerMode, float direction, float extent, float rotation, float lowFrequencyGain, float overallGain, int matrixHop, IntPtr matrix, DSP_PAN_SURROUND_FLAGS flags); public delegate RESULT DSP_PAN_SUM_MONO_TO_SURROUND_MATRIX (ref DSP_STATE dsp_state, int targetSpeakerMode, float direction, float extent, float lowFrequencyGain, float overallGain, int matrixHop, IntPtr matrix); public delegate RESULT DSP_PAN_SUM_STEREO_TO_SURROUND_MATRIX(ref DSP_STATE dsp_state, int targetSpeakerMode, float direction, float extent, float rotation, float lowFrequencyGain, float overallGain, int matrixHop, IntPtr matrix); public delegate RESULT DSP_PAN_3D_GET_ROLLOFF_GAIN (ref DSP_STATE dsp_state, DSP_PAN_3D_ROLLOFF_TYPE rolloff, float distance, float mindistance, float maxdistance, out float gain); /* [ENUM] [ [DESCRIPTION] These definitions can be used for creating FMOD defined special effects or DSP units. [REMARKS] To get them to be active, first create the unit, then add it somewhere into the DSP network, either at the front of the network near the soundcard unit to affect the global output (by using System::getDSPHead), or on a single channel (using Channel::getDSPHead). [SEE_ALSO] System::createDSPByType ] */ public enum DSP_TYPE : int { UNKNOWN, /* This unit was created via a non FMOD plugin so has an unknown purpose. */ MIXER, /* This unit does nothing but take inputs and mix them together then feed the result to the soundcard unit. */ OSCILLATOR, /* This unit generates sine/square/saw/triangle or noise tones. */ LOWPASS, /* This unit filters sound using a high quality, resonant lowpass filter algorithm but consumes more CPU time. */ ITLOWPASS, /* This unit filters sound using a resonant lowpass filter algorithm that is used in Impulse Tracker, but with limited cutoff range (0 to 8060hz). */ HIGHPASS, /* This unit filters sound using a resonant highpass filter algorithm. */ ECHO, /* This unit produces an echo on the sound and fades out at the desired rate. */ FADER, /* This unit pans and scales the volume of a unit. */ FLANGE, /* This unit produces a flange effect on the sound. */ DISTORTION, /* This unit distorts the sound. */ NORMALIZE, /* This unit normalizes or amplifies the sound to a certain level. */ LIMITER, /* This unit limits the sound to a certain level. */ PARAMEQ, /* This unit attenuates or amplifies a selected frequency range. */ PITCHSHIFT, /* This unit bends the pitch of a sound without changing the speed of playback. */ CHORUS, /* This unit produces a chorus effect on the sound. */ VSTPLUGIN, /* This unit allows the use of Steinberg VST plugins */ WINAMPPLUGIN, /* This unit allows the use of Nullsoft Winamp plugins */ ITECHO, /* This unit produces an echo on the sound and fades out at the desired rate as is used in Impulse Tracker. */ COMPRESSOR, /* This unit implements dynamic compression (linked multichannel, wideband) */ SFXREVERB, /* This unit implements SFX reverb */ LOWPASS_SIMPLE, /* This unit filters sound using a simple lowpass with no resonance, but has flexible cutoff and is fast. */ DELAY, /* This unit produces different delays on individual channels of the sound. */ TREMOLO, /* This unit produces a tremolo / chopper effect on the sound. */ LADSPAPLUGIN, /* This unit allows the use of LADSPA standard plugins. */ SEND, /* This unit sends a copy of the signal to a return DSP anywhere in the DSP tree. */ RETURN, /* This unit receives signals from a number of send DSPs. */ HIGHPASS_SIMPLE, /* This unit filters sound using a simple highpass with no resonance, but has flexible cutoff and is fast. */ PAN, /* This unit pans the signal, possibly upmixing or downmixing as well. */ THREE_EQ, /* This unit is a three-band equalizer. */ FFT, /* This unit simply analyzes the signal and provides spectrum information back through getParameter. */ LOUDNESS_METER, /* This unit analyzes the loudness and true peak of the signal. */ ENVELOPEFOLLOWER, /* This unit tracks the envelope of the input/sidechain signal */ CONVOLUTIONREVERB, /* This unit implements convolution reverb. */ CHANNELMIX, /* This unit provides per signal channel gain, and output channel mapping to allow 1 multichannel signal made up of many groups of signals to map to a single output signal. */ TRANSCEIVER, /* This unit 'sends' and 'receives' from a selection of up to 32 different slots. It is like a send/return but it uses global slots rather than returns as the destination. It also has other features. Multiple transceivers can receive from a single channel, or multiple transceivers can send to a single channel, or a combination of both. */ } /* [ENUM] [ [DESCRIPTION] DSP parameter types. [REMARKS] [SEE_ALSO] FMOD_DSP_PARAMETER_DESC ] */ public enum DSP_PARAMETER_TYPE { FLOAT = 0, INT, BOOL, DATA, } /* [ENUM] [ [DESCRIPTION] DSP float parameter mappings. These determine how values are mapped across dials and automation curves. [REMARKS] FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE_AUTO generates a mapping based on range and units. For example, if the units are in Hertz and the range is with-in the audio spectrum, a Bark scale will be chosen. Logarithmic scales may also be generated for ranges above zero spanning several orders of magnitude. [SEE_ALSO] FMOD_DSP_PARAMETER_FLOAT_MAPPING ] */ public enum DSP_PARAMETER_FLOAT_MAPPING_TYPE { DSP_PARAMETER_FLOAT_MAPPING_TYPE_LINEAR = 0, /* Values mapped linearly across range. */ DSP_PARAMETER_FLOAT_MAPPING_TYPE_AUTO, /* A mapping is automatically chosen based on range and units. See remarks. */ DSP_PARAMETER_FLOAT_MAPPING_TYPE_PIECEWISE_LINEAR, /* Values mapped in a piecewise linear fashion defined by FMOD_DSP_PARAMETER_DESC_FLOAT::mapping.piecewiselinearmapping. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure to define a piecewise linear mapping. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE FMOD_DSP_PARAMETER_FLOAT_MAPPING ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_PARAMETER_FLOAT_MAPPING_PIECEWISE_LINEAR { public int numpoints; /* [w] The number of <position, value> pairs in the piecewise mapping (at least 2). */ public IntPtr pointparamvalues; /* [w] The values in the parameter's units for each point */ public IntPtr pointpositions; /* [w] The positions along the control's scale (e.g. dial angle) corresponding to each parameter value. The range of this scale is arbitrary and all positions will be relative to the minimum and maximum values (e.g. [0,1,3] is equivalent to [1,2,4] and [2,4,8]). If this array is zero, pointparamvalues will be distributed with equal spacing. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure to define a mapping for a DSP unit's float parameter. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE FMOD_DSP_PARAMETER_DESC_FLOAT ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_PARAMETER_FLOAT_MAPPING { public DSP_PARAMETER_FLOAT_MAPPING_TYPE type; public DSP_PARAMETER_FLOAT_MAPPING_PIECEWISE_LINEAR piecewiselinearmapping; /* [w] Only required for FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE_PIECEWISE_LINEAR type mapping. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure to define a float parameter for a DSP unit. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] System::createDSP DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_PARAMETER_DESC FMOD_DSP_PARAMETER_FLOAT_MAPPING ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_PARAMETER_DESC_FLOAT { public float min; /* [w] Minimum parameter value. */ public float max; /* [w] Maximum parameter value. */ public float defaultval; /* [w] Default parameter value. */ public DSP_PARAMETER_FLOAT_MAPPING mapping; /* [w] How the values are distributed across dials and automation curves (e.g. linearly, exponentially etc). */ } /* [STRUCTURE] [ [DESCRIPTION] Structure to define a int parameter for a DSP unit. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] System::createDSP DSP::setParameterInt DSP::getParameterInt FMOD_DSP_PARAMETER_DESC ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_PARAMETER_DESC_INT { public int min; /* [w] Minimum parameter value. */ public int max; /* [w] Maximum parameter value. */ public int defaultval; /* [w] Default parameter value. */ public bool goestoinf; /* [w] Whether the last value represents infiniy. */ public IntPtr valuenames; /* [w] Names for each value. There should be as many strings as there are possible values (max - min + 1). Optional. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure to define a boolean parameter for a DSP unit. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] System::createDSP DSP::setParameterBool DSP::getParameterBool FMOD_DSP_PARAMETER_DESC ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_PARAMETER_DESC_BOOL { public bool defaultval; /* [w] Default parameter value. */ public IntPtr valuenames; /* [w] Names for false and true, respectively. There should be two strings. Optional. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure to define a data parameter for a DSP unit. Use 0 or above for custom types. This parameter will be treated specially by the system if set to one of the FMOD_DSP_PARAMETER_DATA_TYPE values. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] System::createDSP DSP::setParameterData DSP::getParameterData FMOD_DSP_PARAMETER_DATA_TYPE FMOD_DSP_PARAMETER_DESC ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_PARAMETER_DESC_DATA { public int datatype; /* [w] The type of data for this parameter. Use 0 or above for custom types or set to one of the FMOD_DSP_PARAMETER_DATA_TYPE values. */ } /* [STRUCTURE] [ [DESCRIPTION] [REMARKS] Members marked with [w] mean the user sets the value before passing it to the function. Members marked with [r] mean FMOD sets the value to be used after the function exits. The step parameter tells the gui or application that the parameter has a certain granularity. For example in the example of cutoff frequency with a range from 100.0 to 22050.0 you might only want the selection to be in 10hz increments. For this you would simply use 10.0 as the step value. For a boolean, you can use min = 0.0, max = 1.0, step = 1.0. This way the only possible values are 0.0 and 1.0. Some applications may detect min = 0.0, max = 1.0, step = 1.0 and replace a graphical slider bar with a checkbox instead. A step value of 1.0 would simulate integer values only. A step value of 0.0 would mean the full floating point range is accessable. [SEE_ALSO] System::createDSP System::getDSP ] */ [StructLayout(LayoutKind.Explicit)] public struct DSP_PARAMETER_DESC_UNION { [FieldOffset(0)] public DSP_PARAMETER_DESC_FLOAT floatdesc; /* [w] Struct containing information about the parameter in floating point format. Use when type is FMOD_DSP_PARAMETER_TYPE_FLOAT. */ [FieldOffset(0)] public DSP_PARAMETER_DESC_INT intdesc; /* [w] Struct containing information about the parameter in integer format. Use when type is FMOD_DSP_PARAMETER_TYPE_INT. */ [FieldOffset(0)] public DSP_PARAMETER_DESC_BOOL booldesc; /* [w] Struct containing information about the parameter in boolean format. Use when type is FMOD_DSP_PARAMETER_TYPE_BOOL. */ [FieldOffset(0)] public DSP_PARAMETER_DESC_DATA datadesc; /* [w] Struct containing information about the parameter in data format. Use when type is FMOD_DSP_PARAMETER_TYPE_DATA. */ } [StructLayout(LayoutKind.Sequential)] public struct DSP_PARAMETER_DESC { public DSP_PARAMETER_TYPE type; /* [w] Type of this parameter. */ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public char[] name; /* [w] Name of the parameter to be displayed (ie "Cutoff frequency"). */ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public char[] label; /* [w] Short string to be put next to value to denote the unit type (ie "hz"). */ public string description; /* [w] Description of the parameter to be displayed as a help item / tooltip for this parameter. */ public DSP_PARAMETER_DESC_UNION desc; } /* [ENUM] [ [DESCRIPTION] Built-in types for the 'datatype' member of FMOD_DSP_PARAMETER_DESC_DATA. Data parameters of type other than FMOD_DSP_PARAMETER_DATA_TYPE_USER will be treated specially by the system. [REMARKS] [SEE_ALSO] FMOD_DSP_PARAMETER_DESC_DATA FMOD_DSP_PARAMETER_OVERALLGAIN FMOD_DSP_PARAMETER_3DATTRIBUTES FMOD_DSP_PARAMETER_3DATTRIBUTES_MULTI FMOD_DSP_PARAMETER_SIDECHAIN ] */ public enum DSP_PARAMETER_DATA_TYPE { DSP_PARAMETER_DATA_TYPE_USER = 0, /* The default data type. All user data types should be 0 or above. */ DSP_PARAMETER_DATA_TYPE_OVERALLGAIN = -1, /* The data type for FMOD_DSP_PARAMETER_OVERALLGAIN parameters. There should a maximum of one per DSP. */ DSP_PARAMETER_DATA_TYPE_3DATTRIBUTES = -2, /* The data type for FMOD_DSP_PARAMETER_3DATTRIBUTES parameters. There should a maximum of one per DSP. */ DSP_PARAMETER_DATA_TYPE_SIDECHAIN = -3, /* The data type for FMOD_DSP_PARAMETER_SIDECHAIN parameters. There should a maximum of one per DSP. */ DSP_PARAMETER_DATA_TYPE_FFT = -4, /* The data type for FMOD_DSP_PARAMETER_FFT parameters. There should a maximum of one per DSP. */ DSP_PARAMETER_DATA_TYPE_3DATTRIBUTES_MULTI = -5, /* The data type for FMOD_DSP_PARAMETER_3DATTRIBUTES_MULTI parameters. There should a maximum of one per DSP. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure for data parameters of type FMOD_DSP_PARAMETER_DATA_TYPE_OVERALLGAIN. A parameter of this type is used in effects that affect the overgain of the signal in a predictable way. This parameter is read by the system to determine the effect's gain for voice virtualization. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] FMOD_DSP_PARAMETER_DATA_TYPE FMOD_DSP_PARAMETER_DESC ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_PARAMETER_OVERALLGAIN { public float linear_gain; /* [r] The overall linear gain of the effect on the direct signal path */ public float linear_gain_additive; /* [r] Additive gain, for parallel signal paths */ } /* [STRUCTURE] [ [DESCRIPTION] Structure for data parameters of type FMOD_DSP_PARAMETER_DATA_TYPE_3DATTRIBUTES. A parameter of this type is used in effects that respond to a sound's 3D position. The system will set this parameter automatically if a sound's position changes. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] FMOD_DSP_PARAMETER_DATA_TYPE FMOD_DSP_PARAMETER_DESC ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_PARAMETER_3DATTRIBUTES { public _3D_ATTRIBUTES relative; /* [w] The position of the sound relative to the listener. */ public _3D_ATTRIBUTES absolute; /* [w] The position of the sound in world coordinates. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure for data parameters of type FMOD_DSP_PARAMETER_DATA_TYPE_3DATTRIBUTES. A parameter of this type is used in effects that respond to a sound's 3D position. The system will set this parameter automatically if a sound's position changes. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] FMOD_DSP_PARAMETER_DATA_TYPE FMOD_DSP_PARAMETER_DESC ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_PARAMETER_3DATTRIBUTES_MULTI { public int numlisteners; /* [w] The number of listeners. */ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)] public _3D_ATTRIBUTES[] relative; /* [w] The position of the sound relative to the listeners. */ public _3D_ATTRIBUTES absolute; /* [w] The position of the sound in world coordinates. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure for data parameters of type FMOD_DSP_PARAMETER_DATA_TYPE_SIDECHAIN. A parameter of this type is declared for effects which support sidechaining. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] FMOD_DSP_PARAMETER_DATA_TYPE FMOD_DSP_PARAMETER_DESC ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_PARAMETER_SIDECHAIN { public int sidechainenable; /* [r/w] Whether sidechains are enabled. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure for data parameters of type FMOD_DSP_PARAMETER_DATA_TYPE_FFT. A parameter of this type is declared for the FMOD_DSP_TYPE_FFT effect. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. Notes on the spectrum data member. Values inside the float buffer are typically between 0 and 1.0. Each top level array represents one PCM channel of data. Address data as spectrum[channel][bin]. A bin is 1 fft window entry. Only read/display half of the buffer typically for analysis as the 2nd half is usually the same data reversed due to the nature of the way FFT works. [SEE_ALSO] FMOD_DSP_PARAMETER_DATA_TYPE FMOD_DSP_PARAMETER_DESC FMOD_DSP_PARAMETER_DATA_TYPE_FFT FMOD_DSP_TYPE FMOD_DSP_FFT ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_PARAMETER_FFT { public int length; /* [r] Number of entries in this spectrum window. Divide this by the output rate to get the hz per entry. */ public int numchannels; /* [r] Number of channels in spectrum. */ [MarshalAs(UnmanagedType.ByValArray,SizeConst=32)] private IntPtr[] spectrum_internal; /* [r] Per channel spectrum arrays. See remarks for more. */ public float[][] spectrum { get { var buffer = new float[numchannels][]; for (int i = 0; i < numchannels; ++i) { buffer[i] = new float[length]; Marshal.Copy(spectrum_internal[i], buffer[i], 0, length); } return buffer; } } } /* [STRUCTURE] [ [DESCRIPTION] When creating a DSP unit, declare one of these and provide the relevant callbacks and name for FMOD to use when it creates and uses a DSP unit of this type. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. There are 2 different ways to change a parameter in this architecture. One is to use DSP::setParameterFloat / DSP::setParameterInt / DSP::setParameterBool / DSP::setParameterData. This is platform independant and is dynamic, so new unknown plugins can have their parameters enumerated and used. The other is to use DSP::showConfigDialog. This is platform specific and requires a GUI, and will display a dialog box to configure the plugin. [SEE_ALSO] System::createDSP DSP::setParameterFloat DSP::setParameterInt DSP::setParameterBool DSP::setParameterData FMOD_DSP_STATE FMOD_DSP_CREATE_CALLBACK FMOD_DSP_RELEASE_CALLBACK FMOD_DSP_RESET_CALLBACK FMOD_DSP_READ_CALLBACK FMOD_DSP_PROCESS_CALLBACK FMOD_DSP_SETPOSITION_CALLBACK FMOD_DSP_PARAMETER_DESC FMOD_DSP_SETPARAM_FLOAT_CALLBACK FMOD_DSP_SETPARAM_INT_CALLBACK FMOD_DSP_SETPARAM_BOOL_CALLBACK FMOD_DSP_SETPARAM_DATA_CALLBACK FMOD_DSP_GETPARAM_FLOAT_CALLBACK FMOD_DSP_GETPARAM_INT_CALLBACK FMOD_DSP_GETPARAM_BOOL_CALLBACK FMOD_DSP_GETPARAM_DATA_CALLBACK FMOD_DSP_SHOULDIPROCESS_CALLBACK FMOD_DSP_SYSTEM_REGISTER_CALLBACK FMOD_DSP_SYSTEM_DEREGISTER_CALLBACK FMOD_DSP_SYSTEM_MIX_CALLBACK ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_DESCRIPTION { public uint pluginsdkversion; /* [w] The plugin SDK version this plugin is built for. set to this to FMOD_PLUGIN_SDK_VERSION defined above. */ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public char[] name; /* [w] Name of the unit to be displayed in the network. */ public uint version; /* [w] Plugin writer's version number. */ public int numinputbuffers; /* [w] Number of input buffers to process. Use 0 for DSPs that only generate sound and 1 for effects that process incoming sound. */ public int numoutputbuffers; /* [w] Number of audio output buffers. Only one output buffer is currently supported. */ public DSP_CREATECALLBACK create; /* [w] Create callback. This is called when DSP unit is created. Can be null. */ public DSP_RELEASECALLBACK release; /* [w] Release callback. This is called just before the unit is freed so the user can do any cleanup needed for the unit. Can be null. */ public DSP_RESETCALLBACK reset; /* [w] Reset callback. This is called by the user to reset any history buffers that may need resetting for a filter, when it is to be used or re-used for the first time to its initial clean state. Use to avoid clicks or artifacts. */ public DSP_READCALLBACK read; /* [w] Read callback. Processing is done here. Can be null. */ public DSP_PROCESS_CALLBACK process; /* [w] Process callback. Can be specified instead of the read callback if any channel format changes occur between input and output. This also replaces shouldiprocess and should return an error if the effect is to be bypassed. Can be null. */ public DSP_SETPOSITIONCALLBACK setposition; /* [w] Setposition callback. This is called if the unit wants to update its position info but not process data. Can be null. */ public int numparameters; /* [w] Number of parameters used in this filter. The user finds this with DSP::getNumParameters */ public IntPtr paramdesc; /* [w] Variable number of parameter structures. */ public DSP_SETPARAM_FLOAT_CALLBACK setparameterfloat; /* [w] This is called when the user calls DSP.setParameterFloat. Can be null. */ public DSP_SETPARAM_INT_CALLBACK setparameterint; /* [w] This is called when the user calls DSP.setParameterInt. Can be null. */ public DSP_SETPARAM_BOOL_CALLBACK setparameterbool; /* [w] This is called when the user calls DSP.setParameterBool. Can be null. */ public DSP_SETPARAM_DATA_CALLBACK setparameterdata; /* [w] This is called when the user calls DSP.setParameterData. Can be null. */ public DSP_GETPARAM_FLOAT_CALLBACK getparameterfloat; /* [w] This is called when the user calls DSP.getParameterFloat. Can be null. */ public DSP_GETPARAM_INT_CALLBACK getparameterint; /* [w] This is called when the user calls DSP.getParameterInt. Can be null. */ public DSP_GETPARAM_BOOL_CALLBACK getparameterbool; /* [w] This is called when the user calls DSP.getParameterBool. Can be null. */ public DSP_GETPARAM_DATA_CALLBACK getparameterdata; /* [w] This is called when the user calls DSP.getParameterData. Can be null. */ public DSP_SHOULDIPROCESS_CALLBACK shouldiprocess; /* [w] This is called before processing. You can detect if inputs are idle and return FMOD_OK to process, or any other error code to avoid processing the effect. Use a count down timer to allow effect tails to process before idling! */ public IntPtr userdata; /* [w] Optional. Specify 0 to ignore. This is user data to be attached to the DSP unit during creation. Access via DSP::getUserData. */ public DSP_SYSTEM_REGISTER_CALLBACK sys_register; /* [w] Register callback. This is called when DSP unit is loaded/registered. Useful for 'global'/per system object init for plugin. Can be null. */ public DSP_SYSTEM_DEREGISTER_CALLBACK sys_deregister; /* [w] Deregister callback. This is called when DSP unit is unloaded/deregistered. Useful as 'global'/per system object shutdown for plugin. Can be null. */ public DSP_SYSTEM_MIX_CALLBACK sys_mix; /* [w] System mix stage callback. This is called when the mixer starts to execute or is just finishing executing. Useful for 'global'/per system object once a mix update calls for a plugin. Can be null. */ } /* [STRUCTURE] [ [DESCRIPTION] Struct containing DFT callbacks for plugins, to enable a plugin to perform optimized time-frequency domain conversion. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] FMOD_DSP_STATE_SYSTEMCALLBACKS ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_STATE_DFTCALLBACKS { public DSP_DFT_FFTREAL fftreal; /* [r] Callback for performing an FFT on a real signal. */ public DSP_DFT_IFFTREAL inversefftreal; /* [r] Callback for performing an inverse FFT to get a real signal. */ } /* [STRUCTURE] [ [DESCRIPTION] Struct containing panning helper callbacks for plugins. [REMARKS] These are experimental, please contact [email protected] for more information. [SEE_ALSO] FMOD_DSP_STATE_SYSTEMCALLBACKS FMOD_PAN_SURROUND_FLAGS ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_STATE_PAN_CALLBACKS { public DSP_PAN_SUM_MONO_MATRIX summonomatrix; public DSP_PAN_SUM_STEREO_MATRIX sumstereomatrix; public DSP_PAN_SUM_SURROUND_MATRIX sumsurroundmatrix; public DSP_PAN_SUM_MONO_TO_SURROUND_MATRIX summonotosurroundmatrix; public DSP_PAN_SUM_STEREO_TO_SURROUND_MATRIX sumstereotosurroundmatrix; public DSP_PAN_3D_GET_ROLLOFF_GAIN getrolloffgain; } /* [STRUCTURE] [ [DESCRIPTION] Struct containing System level callbacks for plugins, to enable a plugin to query information about the system or allocate memory using FMOD's (and therefore possibly the game's) allocators. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] FMOD_DSP_STATE FMOD_DSP_STATE_DFTCALLBACKS FMOD_DSP_STATE_PAN_CALLBACKS ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_STATE_SYSTEMCALLBACKS { MEMORY_ALLOC_CALLBACK alloc; /* [r] Memory allocation callback. Use this for all dynamic memory allocation within the plugin. */ MEMORY_REALLOC_CALLBACK realloc; /* [r] Memory reallocation callback. */ MEMORY_FREE_CALLBACK free; /* [r] Memory free callback. */ DSP_SYSTEM_GETSAMPLERATE getsamplerate; /* [r] Callback for getting the system samplerate. */ DSP_SYSTEM_GETBLOCKSIZE getblocksize; /* [r] Callback for getting the system's block size. DSPs will be requested to process blocks of varying length up to this size.*/ IntPtr dft; /* [r] Struct containing callbacks for performing FFTs and inverse FFTs. */ IntPtr pancallbacks; /* [r] Pointer to a structure of callbacks for calculating pan, up-mix and down-mix matrices. */ DSP_SYSTEM_GETSPEAKERMODE getspeakermode; /* [r] Callback for getting the system's speaker modes. One is the mixer's default speaker mode, the other is the output mode the system is downmixing or upmixing to.*/ } /* [STRUCTURE] [ [DESCRIPTION] DSP plugin structure that is passed into each callback. [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. 'systemobject' is an integer that relates to the System object that created the DSP or registered the DSP plugin. If only 1 System object is created then it should be 0. A second object would be 1 and so on. FMOD_DSP_STATE_SYSTEMCALLBACKS::getsamplerate and FMOD_DSP_STATE_SYSTEMCALLBACKS::getblocksize could return different results so it could be relevant to plugin developers to monitor which object is being used. [SEE_ALSO] FMOD_DSP_DESCRIPTION FMOD_DSP_STATE_SYSTEMCALLBACKS ] */ [StructLayout(LayoutKind.Sequential)] public struct DSP_STATE { public IntPtr instance; /* [r] Handle to the DSP hand the user created. Not to be modified. C++ users cast to FMOD::DSP to use. */ public IntPtr plugindata; /* [r/w] Plugin writer created data the output author wants to attach to this object. */ public uint channelmask; /* [r] Specifies which speakers the DSP effect is active on */ public int source_speakermode; /* [r] Specifies which speaker mode the signal originated for information purposes, ie in case panning needs to be done differently. */ public IntPtr sidechaindata; /* [r] The mixed result of all incoming sidechains is stored at this pointer address. */ public int sidechainchannels; /* [r] The number of channels of pcm data stored within the sidechain buffer. */ public IntPtr callbacks; /* [r] Struct containing callbacks for system level functionality. */ public int systemobject; /* [r] FMOD::System object index, relating to the System object that created this DSP. */ } /* [STRUCTURE] [ [DESCRIPTION] DSP metering info used for retrieving metering info [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value. Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] FMOD_SPEAKER ] */ [StructLayout(LayoutKind.Sequential)] public class DSP_METERING_INFO { public int numsamples; /* [r] The number of samples considered for this metering info. */ [MarshalAs(UnmanagedType.ByValArray, SizeConst=32)] public float[] peaklevel; /* [r] The peak level per channel. */ [MarshalAs(UnmanagedType.ByValArray, SizeConst=32)] public float[] rmslevel; /* [r] The rms level per channel. */ public short numchannels; /* [r] Number of channels. */ } /* ============================================================================================================== FMOD built in effect parameters. Use DSP::setParameter with these enums for the 'index' parameter. ============================================================================================================== */ /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_OSCILLATOR filter. [REMARKS] [SEE_ALSO] DSP::setParameter DSP::getParameter FMOD_DSP_TYPE ] */ public enum DSP_OSCILLATOR { TYPE, /* Waveform type. 0 = sine. 1 = square. 2 = sawup. 3 = sawdown. 4 = triangle. 5 = noise. */ RATE /* Frequency of the sinewave in hz. 1.0 to 22000.0. Default = 220.0. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_LOWPASS filter. [REMARKS] [SEE_ALSO] DSP::setParameter DSP::getParameter FMOD_DSP_TYPE ] */ public enum DSP_LOWPASS { CUTOFF, /* Lowpass cutoff frequency in hz. 1.0 to 22000.0. Default = 5000.0. */ RESONANCE /* Lowpass resonance Q value. 1.0 to 10.0. Default = 1.0. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_ITLOWPASS filter. This is different to the default FMOD_DSP_TYPE_ITLOWPASS filter in that it uses a different quality algorithm and is the filter used to produce the correct sounding playback in .IT files. FMOD Ex's .IT playback uses this filter. [REMARKS] Note! This filter actually has a limited cutoff frequency below the specified maximum, due to its limited design, so for a more open range filter use FMOD_DSP_LOWPASS or if you don't mind not having resonance, FMOD_DSP_LOWPASS_SIMPLE. The effective maximum cutoff is about 8060hz. [SEE_ALSO] DSP::setParameter DSP::getParameter FMOD_DSP_TYPE ] */ public enum DSP_ITLOWPASS { CUTOFF, /* Lowpass cutoff frequency in hz. 1.0 to 22000.0. Default = 5000.0/ */ RESONANCE /* Lowpass resonance Q value. 0.0 to 127.0. Default = 1.0. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_HIGHPASS filter. [REMARKS] [SEE_ALSO] DSP::setParameter DSP::getParameter FMOD_DSP_TYPE ] */ public enum DSP_HIGHPASS { CUTOFF, /* (Type:float) - Highpass cutoff frequency in hz. 1.0 to output 22000.0. Default = 5000.0. */ RESONANCE /* (Type:float) - Highpass resonance Q value. 1.0 to 10.0. Default = 1.0. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_ECHO filter. [REMARKS] Note. Every time the delay is changed, the plugin re-allocates the echo buffer. This means the echo will dissapear at that time while it refills its new buffer. Larger echo delays result in larger amounts of memory allocated. [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE ] */ public enum DSP_ECHO { DELAY, /* (Type:float) - Echo delay in ms. 10 to 5000. Default = 500. */ FEEDBACK, /* (Type:float) - Echo decay per delay. 0 to 100. 100.0 = No decay, 0.0 = total decay (ie simple 1 line delay). Default = 50.0. */ DRYLEVEL, /* (Type:float) - Original sound volume in dB. -80.0 to 10.0. Default = 0. */ WETLEVEL /* (Type:float) - Volume of echo signal to pass to output in dB. -80.0 to 10.0. Default = 0. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_DELAY filter. [REMARKS] Note. Every time MaxDelay is changed, the plugin re-allocates the delay buffer. This means the delay will dissapear at that time while it refills its new buffer. A larger MaxDelay results in larger amounts of memory allocated. Channel delays above MaxDelay will be clipped to MaxDelay and the delay buffer will not be resized. [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE ] */ public enum DSP_DELAY { CH0, /* Channel #0 Delay in ms. 0 to 10000. Default = 0. */ CH1, /* Channel #1 Delay in ms. 0 to 10000. Default = 0. */ CH2, /* Channel #2 Delay in ms. 0 to 10000. Default = 0. */ CH3, /* Channel #3 Delay in ms. 0 to 10000. Default = 0. */ CH4, /* Channel #4 Delay in ms. 0 to 10000. Default = 0. */ CH5, /* Channel #5 Delay in ms. 0 to 10000. Default = 0. */ CH6, /* Channel #6 Delay in ms. 0 to 10000. Default = 0. */ CH7, /* Channel #7 Delay in ms. 0 to 10000. Default = 0. */ CH8, /* Channel #8 Delay in ms. 0 to 10000. Default = 0. */ CH9, /* Channel #9 Delay in ms. 0 to 10000. Default = 0. */ CH10, /* Channel #10 Delay in ms. 0 to 10000. Default = 0. */ CH11, /* Channel #11 Delay in ms. 0 to 10000. Default = 0. */ CH12, /* Channel #12 Delay in ms. 0 to 10000. Default = 0. */ CH13, /* Channel #13 Delay in ms. 0 to 10000. Default = 0. */ CH14, /* Channel #14 Delay in ms. 0 to 10000. Default = 0. */ CH15, /* Channel #15 Delay in ms. 0 to 10000. Default = 0. */ MAXDELAY, /* Maximum delay in ms. 0 to 1000. Default = 10. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_FLANGE filter. [REMARKS] Flange is an effect where the signal is played twice at the same time, and one copy slides back and forth creating a whooshing or flanging effect. As there are 2 copies of the same signal, by default each signal is given 50% mix, so that the total is not louder than the original unaffected signal. Flange depth is a percentage of a 10ms shift from the original signal. Anything above 10ms is not considered flange because to the ear it begins to 'echo' so 10ms is the highest value possible. [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE ] */ public enum DSP_FLANGE { MIX, /* (Type:float) - Percentage of wet signal in mix. 0 to 100. Default = 50. */ DEPTH, /* (Type:float) - Flange depth (percentage of 40ms delay). 0.01 to 1.0. Default = 1.0. */ RATE /* (Type:float) - Flange speed in hz. 0.0 to 20.0. Default = 0.1. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_TREMOLO filter. [REMARKS] The tremolo effect varies the amplitude of a sound. Depending on the settings, this unit can produce a tremolo, chopper or auto-pan effect. The shape of the LFO (low freq. oscillator) can morphed between sine, triangle and sawtooth waves using the FMOD_DSP_TREMOLO_SHAPE and FMOD_DSP_TREMOLO_SKEW parameters. FMOD_DSP_TREMOLO_DUTY and FMOD_DSP_TREMOLO_SQUARE are useful for a chopper-type effect where the first controls the on-time duration and second controls the flatness of the envelope. FMOD_DSP_TREMOLO_SPREAD varies the LFO phase between channels to get an auto-pan effect. This works best with a sine shape LFO. The LFO can be synchronized using the FMOD_DSP_TREMOLO_PHASE parameter which sets its instantaneous phase. [SEE_ALSO] DSP::setParameterFloat DSP::getParameter FMOD_DSP_TYPE ] */ public enum DSP_TREMOLO { FREQUENCY, /* LFO frequency in Hz. 0.1 to 20. Default = 4. */ DEPTH, /* Tremolo depth. 0 to 1. Default = 0. */ SHAPE, /* LFO shape morph between triangle and sine. 0 to 1. Default = 0. */ SKEW, /* Time-skewing of LFO cycle. -1 to 1. Default = 0. */ DUTY, /* LFO on-time. 0 to 1. Default = 0.5. */ SQUARE, /* Flatness of the LFO shape. 0 to 1. Default = 0. */ PHASE, /* Instantaneous LFO phase. 0 to 1. Default = 0. */ SPREAD /* Rotation / auto-pan effect. -1 to 1. Default = 0. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_DISTORTION filter. [REMARKS] [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE ] */ public enum DSP_DISTORTION { LEVEL /* Distortion value. 0.0 to 1.0. Default = 0.5. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_NORMALIZE filter. [REMARKS] Normalize amplifies the sound based on the maximum peaks within the signal. For example if the maximum peaks in the signal were 50% of the bandwidth, it would scale the whole sound by 2. The lower threshold value makes the normalizer ignores peaks below a certain point, to avoid over-amplification if a loud signal suddenly came in, and also to avoid amplifying to maximum things like background hiss. Because FMOD is a realtime audio processor, it doesn't have the luxury of knowing the peak for the whole sound (ie it can't see into the future), so it has to process data as it comes in. To avoid very sudden changes in volume level based on small samples of new data, fmod fades towards the desired amplification which makes for smooth gain control. The fadetime parameter can control this. [SEE_ALSO] DSP::setParameterFloat DSP::getParameter FMOD_DSP_TYPE ] */ public enum DSP_NORMALIZE { FADETIME, /* Time to ramp the silence to full in ms. 0.0 to 20000.0. Default = 5000.0. */ THRESHHOLD, /* Lower volume range threshold to ignore. 0.0 to 1.0. Default = 0.1. Raise higher to stop amplification of very quiet signals. */ MAXAMP /* Maximum amplification allowed. 1.0 to 100000.0. Default = 20.0. 1.0 = no amplifaction, higher values allow more boost. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_LIMITER filter. [REMARKS] [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE ] */ public enum DSP_LIMITER { RELEASETIME, /* (Type:float) - Time to ramp the silence to full in ms. 1.0 to 1000.0. Default = 10.0. */ CEILING, /* (Type:float) - Maximum level of the output signal in dB. -12.0 to 0.0. Default = 0.0. */ MAXIMIZERGAIN, /* (Type:float) - Maximum amplification allowed in dB. 0.0 to 12.0. Default = 0.0. 0.0 = no amplifaction, higher values allow more boost. */ MODE, /* (Type:float) - Channel processing mode. 0 or 1. Default = 0. 0 = Independent (limiter per channel), 1 = Linked. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_PARAMEQ filter. [REMARKS] Parametric EQ is a bandpass filter that attenuates or amplifies a selected frequency and its neighbouring frequencies. To create a multi-band EQ create multiple FMOD_DSP_TYPE_PARAMEQ units and set each unit to different frequencies, for example 1000hz, 2000hz, 4000hz, 8000hz, 16000hz with a range of 1 octave each. When a frequency has its gain set to 1.0, the sound will be unaffected and represents the original signal exactly. [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE ] */ public enum DSP_PARAMEQ { CENTER, /* Frequency center. 20.0 to 22000.0. Default = 8000.0. */ BANDWIDTH, /* Octave range around the center frequency to filter. 0.2 to 5.0. Default = 1.0. */ GAIN /* Frequency Gain. 0.05 to 3.0. Default = 1.0. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_PITCHSHIFT filter. [REMARKS] This pitch shifting unit can be used to change the pitch of a sound without speeding it up or slowing it down. It can also be used for time stretching or scaling, for example if the pitch was doubled, and the frequency of the sound was halved, the pitch of the sound would sound correct but it would be twice as slow. Warning! This filter is very computationally expensive! Similar to a vocoder, it requires several overlapping FFT and IFFT's to produce smooth output, and can require around 440mhz for 1 stereo 48khz signal using the default settings. Reducing the signal to mono will half the cpu usage, as will the overlap count. Reducing this will lower audio quality, but what settings to use are largely dependant on the sound being played. A noisy polyphonic signal will need higher overlap and fft size compared to a speaking voice for example. This pitch shifter is based on the pitch shifter code at http://www.dspdimension.com, written by Stephan M. Bernsee. The original code is COPYRIGHT 1999-2003 Stephan M. Bernsee <[email protected]>. 'maxchannels' dictates the amount of memory allocated. By default, the maxchannels value is 0. If FMOD is set to stereo, the pitch shift unit will allocate enough memory for 2 channels. If it is 5.1, it will allocate enough memory for a 6 channel pitch shift, etc. If the pitch shift effect is only ever applied to the global mix (ie it was added with System::addDSP), then 0 is the value to set as it will be enough to handle all speaker modes. When the pitch shift is added to a channel (ie Channel::addDSP) then the channel count that comes in could be anything from 1 to 8 possibly. It is only in this case where you might want to increase the channel count above the output's channel count. If a channel pitch shift is set to a lower number than the sound's channel count that is coming in, it will not pitch shift the sound. [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE ] */ public enum DSP_PITCHSHIFT { PITCH, /* Pitch value. 0.5 to 2.0. Default = 1.0. 0.5 = one octave down, 2.0 = one octave up. 1.0 does not change the pitch. */ FFTSIZE, /* FFT window size. 256, 512, 1024, 2048, 4096. Default = 1024. Increase this to reduce 'smearing'. This effect is a warbling sound similar to when an mp3 is encoded at very low bitrates. */ OVERLAP, /* Window overlap. 1 to 32. Default = 4. Increase this to reduce 'tremolo' effect. Increasing it by a factor of 2 doubles the CPU usage. */ MAXCHANNELS /* Maximum channels supported. 0 to 16. 0 = same as fmod's default output polyphony, 1 = mono, 2 = stereo etc. See remarks for more. Default = 0. It is suggested to leave at 0! */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_CHORUS filter. [REMARKS] Chorous is an effect where the sound is more 'spacious' due to 1 to 3 versions of the sound being played along side the original signal but with the pitch of each copy modulating on a sine wave. This is a highly configurable chorus unit. It supports 3 taps, small and large delay times and also feedback. This unit also could be used to do a simple echo, or a flange effect. [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE ] */ public enum DSP_CHORUS { MIX, /* (Type:float) - Volume of original signal to pass to output. 0.0 to 100.0. Default = 50.0. */ RATE, /* (Type:float) - Chorus modulation rate in Hz. 0.0 to 20.0. Default = 0.8 Hz. */ DEPTH, /* (Type:float) - Chorus modulation depth. 0.0 to 100.0. Default = 3.0. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_ITECHO filter. This is effectively a software based echo filter that emulates the DirectX DMO echo effect. Impulse tracker files can support this, and FMOD will produce the effect on ANY platform, not just those that support DirectX effects! [REMARKS] Note. Every time the delay is changed, the plugin re-allocates the echo buffer. This means the echo will dissapear at that time while it refills its new buffer. Larger echo delays result in larger amounts of memory allocated. As this is a stereo filter made mainly for IT playback, it is targeted for stereo signals. With mono signals only the FMOD_DSP_ITECHO_LEFTDELAY is used. For multichannel signals (>2) there will be no echo on those channels. [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE System::addDSP ] */ public enum DSP_ITECHO { WETDRYMIX, /* (Type:float) - Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from 0.0 through 100.0 (all wet). Default = 50. */ FEEDBACK, /* (Type:float) - Percentage of output fed back into input, in the range from 0.0 through 100.0. Default = 50. */ LEFTDELAY, /* (Type:float) - Delay for left channel, in milliseconds, in the range from 1.0 through 2000.0. Default = 500 ms. */ RIGHTDELAY, /* (Type:float) - Delay for right channel, in milliseconds, in the range from 1.0 through 2000.0. Default = 500 ms. */ PANDELAY /* (Type:float) - Value that specifies whether to swap left and right delays with each successive echo. Ranges from 0.0 (equivalent to FALSE) to 1.0 (equivalent to TRUE), meaning no swap. Default = 0. CURRENTLY NOT SUPPORTED. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_COMPRESSOR unit. This is a multichannel software limiter that is uniform across the whole spectrum. [REMARKS] The limiter is not guaranteed to catch every peak above the threshold level, because it cannot apply gain reduction instantaneously - the time delay is determined by the attack time. However setting the attack time too short will distort the sound, so it is a compromise. High level peaks can be avoided by using a short attack time - but not too short, and setting the threshold a few decibels below the critical level. [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat DSP::setParameterBool DSP::getParameterBool FMOD_DSP_TYPE ] */ public enum DSP_COMPRESSOR { THRESHOLD, /* (Type:float) - Threshold level (dB) in the range from -80 through 0. The default value is 0. */ RATIO, /* (Type:float) - Compression Ratio (dB/dB) in the range from 1 to 50. The default value is 2.5. */ ATTACK, /* (Type:float) - Attack time (milliseconds), in the range from 0.1 through 1000. The default value is 20. */ RELEASE, /* (Type:float) - Release time (milliseconds), in the range from 10 through 5000. The default value is 100 */ GAINMAKEUP, /* (Type:float) - Make-up gain (dB) applied after limiting, in the range from 0 through 30. The default value is 0. */ USESIDECHAIN,/* (Type:bool) - Whether to analyse the sidechain signal instead of the input signal. The default value is false */ LINKED /* (Type:bool) - FALSE = Independent (compressor per channel), TRUE = Linked. The default value is TRUE. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_SFXREVERB unit. [REMARKS] This is a high quality I3DL2 based reverb. On top of the I3DL2 property set, "Dry Level" is also included to allow the dry mix to be changed. These properties can be set with presets in FMOD_REVERB_PRESETS. [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE FMOD_REVERB_PRESETS ] */ public enum DSP_SFXREVERB { DECAYTIME, /* (Type:float) - Decay Time : Reverberation decay time at low-frequencies in milliseconds. Ranges from 100.0 to 20000.0. Default is 1500. */ EARLYDELAY, /* (Type:float) - Early Delay : Delay time of first reflection in milliseconds. Ranges from 0.0 to 300.0. Default is 20. */ LATEDELAY, /* (Type:float) - Reverb Delay : Late reverberation delay time relative to first reflection in milliseconds. Ranges from 0.0 to 100.0. Default is 40. */ HFREFERENCE, /* (Type:float) - HF Reference : Reference frequency for high-frequency decay in Hz. Ranges from 20.0 to 20000.0. Default is 5000. */ HFDECAYRATIO, /* (Type:float) - Decay HF Ratio : High-frequency decay time relative to decay time in percent. Ranges from 10.0 to 100.0. Default is 50. */ DIFFUSION, /* (Type:float) - Diffusion : Reverberation diffusion (echo density) in percent. Ranges from 0.0 to 100.0. Default is 100. */ DENSITY, /* (Type:float) - Density : Reverberation density (modal density) in percent. Ranges from 0.0 to 100.0. Default is 100. */ LOWSHELFFREQUENCY, /* (Type:float) - Low Shelf Frequency : Transition frequency of low-shelf filter in Hz. Ranges from 20.0 to 1000.0. Default is 250. */ LOWSHELFGAIN, /* (Type:float) - Low Shelf Gain : Gain of low-shelf filter in dB. Ranges from -36.0 to 12.0. Default is 0. */ HIGHCUT, /* (Type:float) - High Cut : Cutoff frequency of low-pass filter in Hz. Ranges from 20.0 to 20000.0. Default is 20000. */ EARLYLATEMIX, /* (Type:float) - Early/Late Mix : Blend ratio of late reverb to early reflections in percent. Ranges from 0.0 to 100.0. Default is 50. */ WETLEVEL, /* (Type:float) - Wet Level : Reverb signal level in dB. Ranges from -80.0 to 20.0. Default is -6. */ DRYLEVEL /* (Type:float) - Dry Level : Dry signal level in dB. Ranges from -80.0 to 20.0. Default is 0. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_LOWPASS_SIMPLE filter. This is a very simple low pass filter, based on two single-pole RC time-constant modules. The emphasis is on speed rather than accuracy, so this should not be used for task requiring critical filtering. [REMARKS] [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE ] */ public enum DSP_LOWPASS_SIMPLE { CUTOFF /* Lowpass cutoff frequency in hz. 10.0 to 22000.0. Default = 5000.0 */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_SEND DSP. [REMARKS] [SEE_ALSO] DSP::setParameterInt DSP::getParameterInt DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE ] */ public enum DSP_SEND { RETURNID, /* (Type:int) - ID of the Return DSP this send is connected to (integer values only). -1 indicates no connected Return DSP. Default = -1. */ LEVEL, /* (Type:float) - Send level. 0.0 to 1.0. Default = 1.0 */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_RETURN DSP. [REMARKS] [SEE_ALSO] DSP::setParameterInt DSP::getParameterInt FMOD_DSP_TYPE ] */ public enum DSP_RETURN { ID, /* (Type:int) - ID of this Return DSP. Read-only. Default = -1. */ INPUT_SPEAKER_MODE /* (Type:int) - Input speaker mode of this return. Default = FMOD_SPEAKERMODE_DEFAULT. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_HIGHPASS_SIMPLE filter. This is a very simple single-order high pass filter. The emphasis is on speed rather than accuracy, so this should not be used for task requiring critical filtering. [REMARKS] [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE ] */ public enum DSP_HIGHPASS_SIMPLE { CUTOFF /* (Type:float) - Highpass cutoff frequency in hz. 10.0 to 22000.0. Default = 1000.0 */ } /* [ENUM] [ [DESCRIPTION] Parameter values for the FMOD_DSP_PAN_SURROUND_FROM_STEREO_MODE parameter of the FMOD_DSP_TYPE_PAN DSP. [REMARKS] [SEE_ALSO] FMOD_DSP_PAN ] */ public enum DSP_PAN_SURROUND_FROM_STEREO_MODE_TYPE { DISTRIBUTED, DISCRETE } /* [ENUM] [ [DESCRIPTION] Parameter values for the FMOD_DSP_PAN_MODE parameter of the FMOD_DSP_TYPE_PAN DSP. [REMARKS] [SEE_ALSO] FMOD_DSP_PAN ] */ public enum DSP_PAN_MODE_TYPE { MONO, STEREO, SURROUND } /* [ENUM] [ [DESCRIPTION] Parameter values for the FMOD_DSP_PAN_3D_ROLLOFF parameter of the FMOD_DSP_TYPE_PAN DSP. [REMARKS] [SEE_ALSO] FMOD_DSP_PAN ] */ public enum DSP_PAN_3D_ROLLOFF_TYPE { LINEARSQUARED, LINEAR, INVERSE, INVERSETAPERED, CUSTOM } /* [ENUM] [ [DESCRIPTION] Parameter values for the FMOD_DSP_PAN_3D_EXTENT_MODE parameter of the FMOD_DSP_TYPE_PAN DSP. [REMARKS] [SEE_ALSO] FMOD_DSP_PAN ] */ public enum DSP_PAN_3D_EXTENT_MODE_TYPE { AUTO, USER, OFF } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_PAN DSP. [REMARKS] [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat DSP::setParameterInt DSP::getParameterInt DSP::setParameterData DSP::getParameterData FMOD_DSP_TYPE ] */ public enum DSP_PAN { MODE, /* (Type:int) - Panner mode. FMOD_DSP_PAN_MODE_MONO for mono down-mix, FMOD_DSP_PAN_MODE_STEREO for stereo panning or FMOD_DSP_PAN_MODE_SURROUND for surround panning. Default = FMOD_DSP_PAN_MODE_SURROUND */ STEREO_POSITION, /* (Type:float) - Stereo pan position STEREO_POSITION_MIN to STEREO_POSITION_MAX. Default = 0.0. */ SURROUND_DIRECTION, /* (Type:float) - Surround pan direction ROTATION_MIN to ROTATION_MAX. Default = 0.0. */ SURROUND_EXTENT, /* (Type:float) - Surround pan extent EXTENT_MIN to EXTENT_MAX. Default = 360.0. */ SURROUND_ROTATION, /* (Type:float) - Surround pan rotation ROTATION_MIN to ROTATION_MAX. Default = 0.0. */ SURROUND_LFE_LEVEL, /* (Type:float) - Surround pan LFE level SURROUND_LFE_LEVEL_MIN to SURROUND_LFE_LEVEL_MAX. Default = 0.0. */ SURROUND_FROM_STEREO_MODE, /* (Type:int) - Stereo-To-Surround Mode FMOD_DSP_PAN_SURROUND_FROM_STEREO_MODE_DISTRIBUTED to FMOD_DSP_PAN_SURROUND_FROM_STEREO_MODE_DISCRETE. Default = FMOD_DSP_PAN_SURROUND_FROM_STEREO_MODE_DISCRETE. */ SURROUND_STEREO_SEPARATION, /* (Type:float) - Stereo-To-Surround Stereo Separation. ROTATION_MIN to ROTATION_MAX. Default = 60.0. */ SURROUND_STEREO_AXIS, /* (Type:float) - Stereo-To-Surround Stereo Axis. ROTATION_MIN to ROTATION_MAX. Default = 0.0. */ ENABLED_SURROUND_SPEAKERS, /* (Type:int) - Surround Speakers Enabled. 0 to 0xFFF. Default = 0xFFF. */ _3D_POSITION, /* (Type:data) - 3D Position data of type FMOD_DSP_PARAMETER_DATA_TYPE_3DPOS */ _3D_ROLLOFF, /* (Type:int) - 3D Rolloff FMOD_DSP_PAN_3D_ROLLOFF_LINEARSQUARED to FMOD_DSP_PAN_3D_ROLLOFF_CUSTOM. Default = FMOD_DSP_PAN_3D_ROLLOFF_LINEARSQUARED. */ _3D_MIN_DISTANCE, /* (Type:float) - 3D Min Distance 0.0 to GAME_UNITS_MAX. Default = 1.0. */ _3D_MAX_DISTANCE, /* (Type:float) - 3D Max Distance 0.0 to GAME_UNITS_MAX. Default = 20.0. */ _3D_EXTENT_MODE, /* (Type:int) - 3D Extent Mode FMOD_DSP_PAN_3D_EXTENT_MODE_AUTO to FMOD_DSP_PAN_3D_EXTENT_MODE_OFF. Default = FMOD_DSP_PAN_3D_EXTENT_MODE_AUTO. */ _3D_SOUND_SIZE, /* (Type:float) - 3D Sound Size 0.0 to GAME_UNITS_MAX. Default = 0.0. */ _3D_MIN_EXTENT, /* (Type:float) - 3D Min Extent EXTENT_MIN to EXTENT_MAX. Default = 0.0. */ _3D_PAN_BLEND, /* (Type:float) - 3D Pan Blend PAN_BLEND_MIN to PAN_BLEND_MAX. Default = 0.0. */ LFE_UPMIX_ENABLED, /* (Type:int) - LFE Upmix Enabled 0 to 1. Default = 0. */ OVERALL_GAIN, /* (Type:data) - Overall Gain data of type FMOD_DSP_PARAMETER_DATA_TYPE_OVERALLGAIN */ SURROUND_SPEAKER_MODE /* (Type:int) - Surround speaker mode. Target speaker mode for surround panning. Default = FMOD_SPEAKERMODE_DEFAULT. */ } /* [ENUM] [ [DESCRIPTION] Parameter values for the FMOD_DSP_THREE_EQ_CROSSOVERSLOPE parameter of the FMOD_DSP_TYPE_THREE_EQ DSP. [REMARKS] [SEE_ALSO] FMOD_DSP_THREE_EQ ] */ public enum DSP_THREE_EQ_CROSSOVERSLOPE_TYPE { _12DB, _24DB, _48DB } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_THREE_EQ filter. [REMARKS] [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat DSP::setParameterInt DSP::getParameterInt FMOD_DSP_TYPE FMOD_DSP_THREE_EQ_CROSSOVERSLOPE_TYPE ] */ public enum DSP_THREE_EQ { LOWGAIN, /* (Type:float) - Low frequency gain in dB. -80.0 to 10.0. Default = 0. */ MIDGAIN, /* (Type:float) - Mid frequency gain in dB. -80.0 to 10.0. Default = 0. */ HIGHGAIN, /* (Type:float) - High frequency gain in dB. -80.0 to 10.0. Default = 0. */ LOWCROSSOVER, /* (Type:float) - Low-to-mid crossover frequency in Hz. 10.0 to 22000.0. Default = 400.0. */ HIGHCROSSOVER, /* (Type:float) - Mid-to-high crossover frequency in Hz. 10.0 to 22000.0. Default = 4000.0. */ CROSSOVERSLOPE /* (Type:int) - Crossover Slope. 0 = 12dB/Octave, 1 = 24dB/Octave, 2 = 48dB/Octave. Default = 1 (24dB/Octave). */ } /* [ENUM] [ [DESCRIPTION] List of windowing methods for the FMOD_DSP_TYPE_FFT unit. Used in spectrum analysis to reduce leakage / transient signals intefering with the analysis. This is a problem with analysis of continuous signals that only have a small portion of the signal sample (the fft window size). Windowing the signal with a curve or triangle tapers the sides of the fft window to help alleviate this problem. [REMARKS] Cyclic signals such as a sine wave that repeat their cycle in a multiple of the window size do not need windowing. I.e. If the sine wave repeats every 1024, 512, 256 etc samples and the FMOD fft window is 1024, then the signal would not need windowing. Not windowing is the same as FMOD_DSP_FFT_WINDOW_RECT, which is the default. If the cycle of the signal (ie the sine wave) is not a multiple of the window size, it will cause frequency abnormalities, so a different windowing method is needed. FMOD_DSP_FFT_WINDOW_RECT. <img src="..\static\overview\rectangle.gif"></img> FMOD_DSP_FFT_WINDOW_TRIANGLE. <img src="..\static\overview\triangle.gif"></img> FMOD_DSP_FFT_WINDOW_HAMMING. <img src="..\static\overview\hamming.gif"></img> FMOD_DSP_FFT_WINDOW_HANNING. <img src="..\static\overview\hanning.gif"></img> FMOD_DSP_FFT_WINDOW_BLACKMAN. <img src="..\static\overview\blackman.gif"></img> FMOD_DSP_FFT_WINDOW_BLACKMANHARRIS. <img src="..\static\overview\blackmanharris.gif"></img> [SEE_ALSO] FMOD_DSP_FFT ] */ public enum DSP_FFT_WINDOW { RECT, /* w[n] = 1.0 */ TRIANGLE, /* w[n] = TRI(2n/N) */ HAMMING, /* w[n] = 0.54 - (0.46 * COS(n/N) ) */ HANNING, /* w[n] = 0.5 * (1.0 - COS(n/N) ) */ BLACKMAN, /* w[n] = 0.42 - (0.5 * COS(n/N) ) + (0.08 * COS(2.0 * n/N) ) */ BLACKMANHARRIS /* w[n] = 0.35875 - (0.48829 * COS(1.0 * n/N)) + (0.14128 * COS(2.0 * n/N)) - (0.01168 * COS(3.0 * n/N)) */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_FFT dsp effect. [REMARKS] Set the attributes for the spectrum analysis with FMOD_DSP_FFT_WINDOWSIZE and FMOD_DSP_FFT_WINDOWTYPE, and retrieve the results with FMOD_DSP_FFT_SPECTRUM and FMOD_DSP_FFT_DOMINANT_FREQ. FMOD_DSP_FFT_SPECTRUM stores its data in the FMOD_DSP_PARAMETER_DATA_TYPE_FFT. You will need to cast to this structure to get the right data. [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat DSP::setParameterInt DSP::getParameterInt DSP::setParameterData DSP::getParameterData FMOD_DSP_TYPE FMOD_DSP_FFT_WINDOW ] */ public enum DSP_FFT { WINDOWSIZE, /* (Type:int) - [r/w] Must be a power of 2 between 128 and 16384. 128, 256, 512, 1024, 2048, 4096, 8192, 16384 are accepted. Default = 2048. */ WINDOWTYPE, /* (Type:int) - [r/w] Refer to FMOD_DSP_FFT_WINDOW enumeration. Default = FMOD_DSP_FFT_WINDOW_HAMMING. */ SPECTRUMDATA, /* (Type:data) - [r] Returns the current spectrum values between 0 and 1 for each 'fft bin'. Cast data to FMOD_DSP_PARAMETER_DATA_TYPE_FFT. Divide the niquist rate by the window size to get the hz value per entry. */ DOMINANT_FREQ /* (Type:float) - [r] Returns the dominant frequencies for each channel. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_ENVELOPEFOLLOWER unit. This is a simple envelope follower for tracking the signal level. [REMARKS] This unit does not affect the incoming signal [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat DSP::setParameterBool DSP::getParameterBool FMOD_DSP_TYPE ] */ public enum DSP_ENVELOPEFOLLOWER { ATTACK, /* (Type:float) - Attack time (milliseconds), in the range from 0.1 through 1000. The default value is 20. */ RELEASE, /* (Type:float) - Release time (milliseconds), in the range from 10 through 5000. The default value is 100 */ ENVELOPE, /* (Type:float) - Current value of the envelope, in the range 0 to 1. Read-only. */ USESIDECHAIN /* (Type:bool) - Whether to analyse the sidechain signal instead of the input signal. The default value is false */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_CHORUS filter. [REMARKS] Convolution Reverb reverb IR. [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat DSP::setParameterData DSP::getParameterData FMOD_DSP_TYPE ] */ public enum DSP_CONVOLUTION_REVERB { IR, /* (Type:data) - [w] 16-bit reverb IR (short*) with an extra sample prepended to the start which specifies the number of channels. */ WET, /* (Type:float) - [r/w] Volume of echo signal to pass to output in dB. -80.0 to 10.0. Default = 0. */ DRY /* (Type:float) - [r/w] Original sound volume in dB. -80.0 to 10.0. Default = 0. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_CHANNELMIX_OUTPUTGROUPING parameter for FMOD_DSP_TYPE_CHANNELMIX effect. [REMARKS] [SEE_ALSO] DSP::setParameterInt DSP::getParameterInt FMOD_DSP_TYPE ] */ public enum DSP_CHANNELMIX_OUTPUT { DEFAULT, /* Output channel count = input channel count. Mapping: See FMOD_SPEAKER enumeration. */ ALLMONO, /* Output channel count = 1. Mapping: Mono, Mono, Mono, Mono, Mono, Mono, ... (each channel all the way up to FMOD_MAX_CHANNEL_WIDTH channels are treated as if they were mono) */ ALLSTEREO, /* Output channel count = 2. Mapping: Left, Right, Left, Right, Left, Right, ... (each pair of channels is treated as stereo all the way up to FMOD_MAX_CHANNEL_WIDTH channels) */ ALLQUAD, /* Output channel count = 4. Mapping: Repeating pattern of Front Left, Front Right, Surround Left, Surround Right. */ ALL5POINT1, /* Output channel count = 6. Mapping: Repeating pattern of Front Left, Front Right, Center, LFE, Surround Left, Surround Right. */ ALL7POINT1, /* Output channel count = 8. Mapping: Repeating pattern of Front Left, Front Right, Center, LFE, Surround Left, Surround Right, Back Left, Back Right. */ ALLLFE /* Output channel count = 6. Mapping: Repeating pattern of LFE in a 5.1 output signal. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_CHANNELMIX filter. [REMARKS] For FMOD_DSP_CHANNELMIX_OUTPUTGROUPING, this value will set the output speaker format for the DSP, and also map the incoming channels to the outgoing channels in a round-robin fashion. Use this for example play a 32 channel input signal as if it were a repeating group of output signals. Ie. FMOD_DSP_CHANNELMIX_OUTPUT_ALLMONO = all incoming channels are mixed to a mono output. FMOD_DSP_CHANNELMIX_OUTPUT_ALLSTEREO = all incoming channels are mixed to a stereo output, ie even incoming channels 0,2,4,6,etc are mixed to left, and odd incoming channels 1,3,5,7,etc are mixed to right. FMOD_DSP_CHANNELMIX_OUTPUT_ALL5POINT1 = all incoming channels are mixed to a 5.1 output. If there are less than 6 coming in, it will just fill the first n channels in the 6 output channels. If there are more, then it will repeat the input pattern to the output like it did with the stereo case, ie 12 incoming channels are mapped as 0-5 mixed to the 5.1 output and 6 to 11 mapped to the 5.1 output. FMOD_DSP_CHANNELMIX_OUTPUT_ALLLFE = all incoming channels are mixed to a 5.1 output but via the LFE channel only. [SEE_ALSO] DSP::setParameterInt DSP::getParameterInt DSP::setParameterFloat DSP::getParameterFloat FMOD_DSP_TYPE ] */ public enum DSP_CHANNELMIX { OUTPUTGROUPING, /* (Type:int) - Refer to FMOD_DSP_CHANNELMIX_OUTPUT enumeration. Default = FMOD_DSP_CHANNELMIX_OUTPUT_DEFAULT. See remarks. */ GAIN_CH0, /* (Type:float) - Channel #0 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH1, /* (Type:float) - Channel #1 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH2, /* (Type:float) - Channel #2 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH3, /* (Type:float) - Channel #3 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH4, /* (Type:float) - Channel #4 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH5, /* (Type:float) - Channel #5 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH6, /* (Type:float) - Channel #6 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH7, /* (Type:float) - Channel #7 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH8, /* (Type:float) - Channel #8 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH9, /* (Type:float) - Channel #9 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH10, /* (Type:float) - Channel #10 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH11, /* (Type:float) - Channel #11 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH12, /* (Type:float) - Channel #12 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH13, /* (Type:float) - Channel #13 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH14, /* (Type:float) - Channel #14 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH15, /* (Type:float) - Channel #15 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH16, /* (Type:float) - Channel #16 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH17, /* (Type:float) - Channel #17 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH18, /* (Type:float) - Channel #18 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH19, /* (Type:float) - Channel #19 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH20, /* (Type:float) - Channel #20 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH21, /* (Type:float) - Channel #21 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH22, /* (Type:float) - Channel #22 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH23, /* (Type:float) - Channel #23 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH24, /* (Type:float) - Channel #24 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH25, /* (Type:float) - Channel #25 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH26, /* (Type:float) - Channel #26 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH27, /* (Type:float) - Channel #27 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH28, /* (Type:float) - Channel #28 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH29, /* (Type:float) - Channel #29 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH30, /* (Type:float) - Channel #30 gain in dB. -80.0 to 10.0. Default = 0. */ GAIN_CH31 /* (Type:float) - Channel #31 gain in dB. -80.0 to 10.0. Default = 0. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TRANSCEIVER_SPEAKERMODE parameter for FMOD_DSP_TYPE_TRANSCEIVER effect. [REMARKS] The speaker mode of a transceiver buffer (of which there are up to 32 of) is determined automatically depending on the signal flowing through the transceiver effect, or it can be forced. Use a smaller fixed speaker mode buffer to save memory. Only relevant for transmitter dsps, as they control the format of the transceiver channel's buffer. If multiple transceivers transmit to a single buffer in different speaker modes, it will allocate memory for each speaker mode. This uses more memory than a single speaker mode. If there are multiple receivers reading from a channel with multiple speaker modes, it will read them all and mix them together. If the system's speaker mode is stereo or mono, it will not create a 3rd buffer, it will just use the mono/stereo speaker mode buffer. [SEE_ALSO] DSP::setParameterInt DSP::getParameterInt FMOD_DSP_TYPE ] */ public enum DSP_TRANSCEIVER_SPEAKERMODE { AUTO = -1, /* A transmitter will use whatever signal channel count coming in to the transmitter, to determine which speaker mode is allocated for the transceiver channel. */ MONO = 0, /* A transmitter will always downmix to a mono channel buffer. */ STEREO, /* A transmitter will always upmix or downmix to a stereo channel buffer. */ SURROUND, /* A transmitter will always upmix or downmix to a surround channel buffer. Surround is the speaker mode of the system above stereo, so could be quad/surround/5.1/7.1. */ } /* [ENUM] [ [DESCRIPTION] Parameter types for the FMOD_DSP_TYPE_TRANSCEIVER filter. [REMARKS] The transceiver only transmits and receives to a global array of 32 channels. The transceiver can be set to receiver mode (like a return) and can receive the signal at a variable gain (FMOD_DSP_TRANSCEIVER_GAIN). The transceiver can also be set to transmit to a chnnel (like a send) and can transmit the signal with a variable gain (FMOD_DSP_TRANSCEIVER_GAIN). The FMOD_DSP_TRANSCEIVER_TRANSMITSPEAKERMODE is only applicable to the transmission format, not the receive format. This means this parameter is ignored in 'receive mode'. This allows receivers to receive at the speaker mode of the user's choice. Receiving from a mono channel, is cheaper than receiving from a surround channel for example. The 3 speaker modes FMOD_DSP_TRANSCEIVER_SPEAKERMODE_MONO, FMOD_DSP_TRANSCEIVER_SPEAKERMODE_STEREO, FMOD_DSP_TRANSCEIVER_SPEAKERMODE_SURROUND are stored as seperate buffers in memory for a tranmitter channel. To save memory, use 1 common speaker mode for a transmitter. The transceiver is double buffered to avoid desyncing of transmitters and receivers. This means there will be a 1 block delay on a receiver, compared to the data sent from a transmitter. Multiple transmitters sending to the same channel will be mixed together. [SEE_ALSO] DSP::setParameterFloat DSP::getParameterFloat DSP::setParameterInt DSP::getParameterInt DSP::setParameterBool DSP::getParameterBool FMOD_DSP_TYPE ] */ public enum DSP_TRANSCEIVER { TRANSMIT, /* (Type:bool) - [r/w] - FALSE = Transceiver is a 'receiver' (like a return) and accepts data from a channel. TRUE = Transceiver is a 'transmitter' (like a send). Default = FALSE. */ GAIN, /* (Type:float) - [r/w] - Gain to receive or transmit at in dB. -80.0 to 10.0. Default = 0. */ CHANNEL, /* (Type:int) - [r/w] - Integer to select current global slot, shared by all Transceivers, that can be transmitted to or received from. 0 to 31. Default = 0.*/ TRANSMITSPEAKERMODE /* (Type:int) - [r/w] - Speaker mode (transmitter mode only). Specifies either 0 (Auto) Default = 0.*/ } /*$ preserve start $*/ } /*$ preserve end $*/
AssetStudio/AssetStudioUtility/FMOD Studio API/fmod_dsp.cs/0
{ "file_path": "AssetStudio/AssetStudioUtility/FMOD Studio API/fmod_dsp.cs", "repo_id": "AssetStudio", "token_count": 39282 }
80
using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using System.IO; namespace AssetStudio { public static class Texture2DExtensions { public static Image<Bgra32> ConvertToImage(this Texture2D m_Texture2D, bool flip) { var converter = new Texture2DConverter(m_Texture2D); var buff = BigArrayPool<byte>.Shared.Rent(m_Texture2D.m_Width * m_Texture2D.m_Height * 4); try { if (converter.DecodeTexture2D(buff)) { var image = Image.LoadPixelData<Bgra32>(buff, m_Texture2D.m_Width, m_Texture2D.m_Height); if (flip) { image.Mutate(x => x.Flip(FlipMode.Vertical)); } return image; } return null; } finally { BigArrayPool<byte>.Shared.Return(buff); } } public static MemoryStream ConvertToStream(this Texture2D m_Texture2D, ImageFormat imageFormat, bool flip) { var image = ConvertToImage(m_Texture2D, flip); if (image != null) { using (image) { return image.ConvertToStream(imageFormat); } } return null; } } }
AssetStudio/AssetStudioUtility/Texture2DExtensions.cs/0
{ "file_path": "AssetStudio/AssetStudioUtility/Texture2DExtensions.cs", "repo_id": "AssetStudio", "token_count": 805 }
81
#ifndef ASTC_H #define ASTC_H #include <stdint.h> int decode_astc(const uint8_t *, const long, const long, const int, const int, uint32_t *); #endif /* end of include guard: ASTC_H */
AssetStudio/Texture2DDecoderNative/astc.h/0
{ "file_path": "AssetStudio/Texture2DDecoderNative/astc.h", "repo_id": "AssetStudio", "token_count": 74 }
82
#ifndef ETC_H #define ETC_H #include <stdint.h> int decode_etc1(const uint8_t *, const long, const long, uint32_t *); int decode_etc2(const uint8_t *, const long, const long, uint32_t *); int decode_etc2a1(const uint8_t *, const long, const long, uint32_t *); int decode_etc2a8(const uint8_t *, const long, const long, uint32_t *); int decode_eacr(const uint8_t *, const long, const long, uint32_t *); int decode_eacr_signed(const uint8_t *, const long, const long, uint32_t *); int decode_eacrg(const uint8_t *, const long, const long, uint32_t *); int decode_eacrg_signed(const uint8_t *, const long, const long, uint32_t *); #endif /* end of include guard: ETC_H */
AssetStudio/Texture2DDecoderNative/etc.h/0
{ "file_path": "AssetStudio/Texture2DDecoderNative/etc.h", "repo_id": "AssetStudio", "token_count": 262 }
83
# 什么是协程 说到协程,我们先了解什么是异步,异步简单说来就是,我要发起一个调用,但是这个被调用方(可能是其它线程,也可能是IO)出结果需要一段时间,我不想让这个调用阻塞住调用方的整个线程,因此传给被调用方一个回调函数,被调用方运行完成后回调这个回调函数就能通知调用方继续往下执行。举个例子: 下面的代码,主线程一直循环,每循环一次sleep 1毫秒,计数加一,每10000次打印一次。 ```csharp private static void Main() { int loopCount = 0; while (true) { int temp = watcherValue; Thread.Sleep(1); ++loopCount; if (loopCount % 10000 == 0) { Console.WriteLine($"loop count: {loopCount}"); } } } ``` 这时我需要加个功能,在程序一开始,我希望在5秒钟之后打印出loopCount的值。看到5秒后我们可以想到Sleep方法,它会阻塞线程一定时间然后继续执行。我们显然不能在主线程中Sleep,因为会破坏掉每10000次计数打印一次的逻辑。 ```csharp // example2_1 class Program { private static int loopCount = 0; private static void Main() { OneThreadSynchronizationContext _ = OneThreadSynchronizationContext.Instance; WaitTimeAsync(5000, WaitTimeFinishCallback); while (true) { OneThreadSynchronizationContext.Instance.Update(); Thread.Sleep(1); ++loopCount; if (loopCount % 10000 == 0) { Console.WriteLine($"loop count: {loopCount}"); } } } private static void WaitTimeAsync(int waitTime, Action action) { Thread thread = new Thread(()=>WaitTime(waitTime, action)); thread.Start(); } private static void WaitTimeFinishCallback() { Console.WriteLine($"WaitTimeAsync finsih loopCount的值是: {loopCount}"); } /// <summary> /// 在另外的线程等待 /// </summary> private static void WaitTime(int waitTime, Action action) { Thread.Sleep(waitTime); // 将action扔回主线程执行 OneThreadSynchronizationContext.Instance.Post((o)=>action(), null); } } ``` 我们在这里设计了一个WaitTimeAsync方法,WaitTimeAsync其实就是一个典型的异步方法,它从主线程发起调用,传入了一个WaitTimeFinishCallback回调方法做参数,开启了一个线程,线程Sleep一定时间后,将传过来的回调扔回到主线程执行。OneThreadSynchronizationContext是一个跨线程队列,任何线程可以往里面扔委托,OneThreadSynchronizationContext的Update方法在主线程中调用,会将这些委托取出来放到主线程执行。为什么回调方法需要扔回到主线程执行呢?因为回调方法中读取了loopCount,loopCount在主线程中也有读写,所以要么加锁,要么永远保证只在主线程中读写。加锁是个不好的做法,代码中到处是锁会导致阅读跟维护困难,很容易产生多线程bug。这种将逻辑打包成委托然后扔回另外一个线程是多线程开发中常用的技巧。 我们可能又有个新需求,WaitTimeFinishCallback执行完成之后,再想等3秒,再打印一下loopCount。 ```csharp private static void WaitTimeAsync(int waitTime, Action action) { Thread thread = new Thread(()=>WaitTime(waitTime, action)); thread.Start(); } private static void WaitTimeFinishCallback() { Console.WriteLine($"WaitTimeAsync finsih loopCount的值是: {loopCount}"); WaitTimeAsync(3000, WaitTimeFinishCallback2); } private static void WaitTimeFinishCallback2() { Console.WriteLine($"WaitTimeAsync finsih loopCount的值是: {loopCount}"); } ``` 我们这时还可能改需求,需要在程序启动5秒后,接下来4秒,再接下来3秒,打印loopCount,也就是上面的逻辑中间再插入一个3秒等待。 ```csharp private static void WaitTimeAsync(int waitTime, Action action) { Thread thread = new Thread(()=>WaitTime(waitTime, action)); thread.Start(); } private static void WaitTimeFinishCallback() { Console.WriteLine($"WaitTimeAsync finsih loopCount的值是: {loopCount}"); WaitTimeAsync(4000, WaitTimeFinishCallback3); } private static void WaitTimeFinishCallback3() { Console.WriteLine($"WaitTimeAsync finsih loopCount的值是: {loopCount}"); WaitTimeAsync(3000, WaitTimeFinishCallback2); } private static void WaitTimeFinishCallback2() { Console.WriteLine($"WaitTimeAsync finsih loopCount的值是: {loopCount}"); } ``` 这样中间插入一段代码,显得非常麻烦。这里可以回答什么是协程了,其实这一串串回调就是协程。
ET/Book/2.1CSharp的协程.md/0
{ "file_path": "ET/Book/2.1CSharp的协程.md", "repo_id": "ET", "token_count": 3165 }
84
# Actor Location ### Actor Location Actor模型只需要知道对方的InstanceId就能发送消息,十分方便,但是有时候我们可能无法知道对方的InstanceId,或者是一个Actor的InstanceId会发生变化。这种场景很常见,比如:很多游戏是分线的,一个玩家可能从1线换到2线,还有的游戏是分场景的,一个场景一个进程,玩家从场景1进入到场景2。因为做了进程迁移,玩家对象的InstanceId也就变化了。ET提供了给这类对象发送消息的机制,叫做Actor Location机制。其原理比较简单: 1. 因为InstanceId是变化的,对象的Entity.Id是不变的,所以我们首先可以想到使用Entity.Id来发送actor消息 2. 提供一个位置进程(Location Server),Actor对象可以将自己的Entity.Id跟InstanceId作为kv存到位置进程中。发送Actor消息前先去位置进程查询到Actor对象的InstanceId再发送actor消息。 3. Actor对象在一个进程创建时或者迁移到一个新的进程时,都需要把自己的Id跟InstanceId注册到Location Server上去 4. 因为Actor对象是可以迁移的,消息发过去有可能Actor已经迁移到其它进程上去了,所以发送Actor Location消息需要提供一种可靠机制 5. ActorLocationSender提供两种方法,Send跟Call,Send一个消息也需要接受者返回一个消息,只有收到返回消息才会发送下一个消息。 6. Actor对象如果迁移走了,这时会返回Actor不存在的错误,发送者收到这个错误会等待1秒,然后重新去获取Actor的InstanceId,然后重新发送,目前会尝试5次,5次过后,抛出异常,报告错误 7. ActorLocationSender发送消息不会每次都去查询Location Server,因为对象迁移毕竟比较少见,只有第一次去查询,之后缓存InstanceId,以后发送失败再重新查询。 8. Actor对象在迁移过程中,有可能其它进程发送过来消息,这时会发生错误,所以location server提供了一种Lock的机制。对象在传送前,删掉在本进程的信息,然后在location server上加上锁,一旦锁上后,其它的对该key的请求会进行队列。 9. 传送前因为对方删除了本进程的actor,所以其它进程会发送失败,这时候他们会进行重试。重试的时候会重新请求location server,这时候会发现被锁了,于是一直等待 10. 传送完成后,要unlock location server上的锁,并且更新新的地址,然后响应其它的location请求。其它发给这个actor的请求继续进行下去。 注意,Actor模型是纯粹的服务端消息通信机制,跟客户端是没什么关系的,很多用ET的新人看到ET客户端消息也有Actor接口,以为这是客户端跟服务端通信的机制,其实不是的。ET客户端使用这个Actor完全是因为Gate需要对客户端消息进行转发,我们可以正好利用服务端actor模型来进行转发,所以客户端有些消息也是继承了actor的接口。假如我们客户端不使用actor接口会怎么样呢?比如,Frame_ClickMap这个消息 ```protobuf message Frame_ClickMap // IActorLocationMessage { int64 ActorId = 93; int64 Id = 94; float X = 1; float Y = 2; float Z = 3; } ``` 我们可能就不需要ActorId这个字段,消息发送到Gate,gate看到是Frame_ClickMap消息,它需要转发给Map上的Unit,转发还好办,gate可以从session中获取对应的map的unit的位置,然后转发,问题来了,Frame_ClickMap消息到了map,map怎么知道消息需要给哪个对象呢?这时候有几种设计: 1. 在转发的底层协议中带上unit的Id,需要比较复杂的底层协议支持。 2. 用一个消息对Frame_ClickMap消息包装一下,包装的消息带上Unit的Id,用消息包装意味着更大的消耗,增加GC。 个人感觉这两种都很差,不好用,而且就算分发给unit对象处理了,怎么解决消息重入的问题呢?unit对象仍然需要挂上一个消息处理队列,然后收到消息扔到队列里面。这不跟actor模型重复了吗?目前ET在客户端发给unit的消息做了个设计,消息做成actor消息,gate收到发现是actor消息,直接发到对应的actor上,解决的可以说很漂亮。其实客户端仍然是使用session.send跟call发送消息,发送的时候也不知道消息是actor消息,只有到了gate,gate才进行了判断,参考OuterMessageDispatcher.cs ### Actor Location消息的处理 ActorLocation消息发送 ```csharp // 从Game.Scene上获取ActorLocationSenderComponent,然后通过Entity.Id获取ActorLocationSender ActorLocationSender actorLocationSender = Game.Scene.GetComponent<ActorLocationSenderComponent>().Get(unitId); // 通过ActorLocationSender来发送消息 actorLocationSender.Send(actorLocationMessage); // 发送Rpc消息 IResponse response = await actorLocationSender.Call(actorLocationRequest); ``` ActorLocation消息的处理跟Actor消息几乎一样,不同的是继承的两个抽象类不同,注意actorlocation的抽象类多了个Location ```csharp // 处理send过来的消息, 需要继承AMActorLocationHandler抽象类,抽象类第一个泛型参数是Actor的类型,第二个参数是消息的类型 [ActorMessageHandler(AppType.Map)] public class Frame_ClickMapHandler : AMActorLocationHandler<Unit, Frame_ClickMap> { protected override ETTask Run(Unit unit, Frame_ClickMap message) { Vector3 target = new Vector3(message.X, message.Y, message.Z); unit.GetComponent<UnitPathComponent>().MoveTo(target).Coroutine(); } } // 处理Rpc消息, 需要继承AMActorRpcHandler抽象类,抽象类第一个泛型参数是Actor的类型,第二个参数是消息的类型,第三个参数是返回消息的类型 [ActorMessageHandler(AppType.Map)] public class C2M_TestActorRequestHandler : AMActorLocationRpcHandler<Unit, C2M_TestActorRequest, M2C_TestActorResponse> { protected override async ETTask Run(Unit unit, C2M_TestActorRequest message, Action<M2C_TestActorResponse> reply) { reply(new M2C_TestActorResponse(){Info = "actor rpc response"}); await ETTask.CompletedTask; } } ``` ### ET的actor跟actor location的比喻 中国有很多城市(进程),城市中有很多人(entity对象)居住,每个人都有身份证号码(Entity.Id)。一个人每到一个市都需要办理居住证,分配到唯一的居住证号码(InstanceId),居住证号码的格式是2个字节市编号+4个字节时间+2个字节递增。身份证号码是永远不会变化的,但是居住证号码每到一个城市都变化的。 现在有个中国邮政(actor)。假设小明要发信给女朋友小红 1. 小红为了收信,自己必须挂载一个邮箱(MailboxComponent),小红收到消息就会处理。注意这里处理是一个个进行处理的。有可能小红会同时收到很多人的信。但是她必须一封一封的信看,比方说小明跟小宝都发了信给小红,小红先收到小明的信,再收到了小宝的信。小红先读小明的信,小明信中让小红给外婆打个电话(产生协程)再给自己回信,注意这期间小红也不能读下一封信,必须打完电话后才能读小宝的信。当然小红自己可以选择不处理完成就开始读小宝的信,做法是小红开一个新的协程来处理小明的信。 2. 假设小明知道小红的居住证号码,那么邮政(actor)可以根据居住证号码头两位找到小红居住的城市(进程),然后再根据小红的居住证编号,找到小红,把消息投递到小红的邮箱(MailboxComponent)中。这种是最简单的原生的actor模型 3. ET还支持了一套actor location机制。假设小明不知道小红的居住证号码,但是他知道小红的身份证号码,怎么办呢?邮政开发了一套高级邮政(actor location)想了一个办法,如果一个人经常搬家,它还想收到信,那他到一个新的城市都必须把自己的居住证跟身份证上报到中央政府(location server),这样高级邮政能够通过身份证号码来发送邮件。方法就是去中央政府拿到小红的居住证号码,再利用actor机制发送。 4. 假设小红之前在广州市,小明用小红的身份证给小红发信件了。 高级邮政获取了小红的居住证号码,给小红发信。发信的这个过程中,小红搬家了,从广州搬到了深圳,这时小红在中央政府上报了自己新的居住证。 高级邮政的信送到到广州的时候发现,小红不在广州。那么高级邮政会再次去中央政府获取小红的居住证,重新发送,有可能成功有可能再次失败,这个过程会重复几次,如果一直不成功则告诉小明,信件发送失败了。 5. 高级邮政发信比较贵,而且人搬家的次数并不多,一般小明用高级邮政发信后会记住小红的居住证,下次再发的时候直接用居住证发信,发送失败了再使用高级邮政发信。 6. 高级邮政的信都是有回执的,有两种回执,一种回执没有内容,只表示小红收到了信,一种回执带了小红的回信。小明在发信的时候可以选择使用哪种回执形式。小明给小红不能同时发送两封信,必须等小红的回执到了,小明才能继续发信。
ET/Book/5.5Actor Location-ZH.md/0
{ "file_path": "ET/Book/5.5Actor Location-ZH.md", "repo_id": "ET", "token_count": 5906 }
85
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.Loader; namespace ET { public class CodeLoader: Singleton<CodeLoader>, ISingletonAwake { private AssemblyLoadContext assemblyLoadContext; private Assembly assembly; public void Awake() { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly ass in assemblies) { if (ass.GetName().Name == "Model") { this.assembly = ass; break; } } Assembly hotfixAssembly = this.LoadHotfix(); World.Instance.AddSingleton<CodeTypes, Assembly[]>(new[] { typeof (World).Assembly, typeof(Init).Assembly, this.assembly, hotfixAssembly }); IStaticMethod start = new StaticMethod(this.assembly, "ET.Entry", "Start"); start.Run(); } private Assembly LoadHotfix() { assemblyLoadContext?.Unload(); GC.Collect(); assemblyLoadContext = new AssemblyLoadContext("Hotfix", true); byte[] dllBytes = File.ReadAllBytes("./Hotfix.dll"); byte[] pdbBytes = File.ReadAllBytes("./Hotfix.pdb"); Assembly hotfixAssembly = assemblyLoadContext.LoadFromStream(new MemoryStream(dllBytes), new MemoryStream(pdbBytes)); return hotfixAssembly; } public void Reload() { Assembly hotfixAssembly = this.LoadHotfix(); CodeTypes codeTypes = World.Instance.AddSingleton<CodeTypes, Assembly[]>(new[] { typeof (World).Assembly, typeof(Init).Assembly, this.assembly, hotfixAssembly }); codeTypes.CreateCode(); Log.Debug($"reload dll finish!"); } } }
ET/DotNet/Loader/CodeLoader.cs/0
{ "file_path": "ET/DotNet/Loader/CodeLoader.cs", "repo_id": "ET", "token_count": 818 }
86
using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace ET.Analyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class ClassDeclarationInHotfixAnalyzer: DiagnosticAnalyzer { private const string Title = "Hotfix程序集中 只能声明含有BaseAttribute子类特性的类或静态类"; private const string MessageFormat = "Hotfix程序集中 只能声明含有BaseAttribute子类特性的类或静态类 类: {0}"; private const string Description = "Hotfix程序集中 只能声明含有BaseAttribute子类特性的类或静态类."; private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticIds.ClassDeclarationInHotfixAnalyzerRuleId, Title, MessageFormat, DiagnosticCategories.Hotfix, DiagnosticSeverity.Error, true, Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { if (!AnalyzerGlobalSetting.EnableAnalyzer) { return; } context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); context.RegisterCompilationStartAction((analysisContext => { if (AnalyzerHelper.IsAssemblyNeedAnalyze(analysisContext.Compilation.AssemblyName,AnalyzeAssembly.AllHotfix)) { analysisContext.RegisterSemanticModelAction((this.AnalyzeSemanticModel)); } } )); } private void AnalyzeSemanticModel(SemanticModelAnalysisContext analysisContext) { foreach (var classDeclarationSyntax in analysisContext.SemanticModel.SyntaxTree.GetRoot().DescendantNodes<ClassDeclarationSyntax>()) { var classTypeSymbol = analysisContext.SemanticModel.GetDeclaredSymbol(classDeclarationSyntax); if (classTypeSymbol!=null) { Analyzer(analysisContext, classTypeSymbol); } } } private void Analyzer(SemanticModelAnalysisContext context, INamedTypeSymbol namedTypeSymbol) { if (namedTypeSymbol.IsStatic) { return; } if (!this.CheckIsTypeOrBaseTypeHasBaseAttributeInherit(namedTypeSymbol)) { foreach (SyntaxReference? declaringSyntaxReference in namedTypeSymbol.DeclaringSyntaxReferences) { Diagnostic diagnostic = Diagnostic.Create(Rule, declaringSyntaxReference.GetSyntax()?.GetLocation(), namedTypeSymbol.Name); //Diagnostic diagnostic = Diagnostic.Create(Rule, declaringSyntaxReference.GetSyntax()?.GetLocation(), context.SemanticModel.SyntaxTree.FilePath); context.ReportDiagnostic(diagnostic); } } } /// <summary> /// 检查该类或其基类是否有BaseAttribute的子类特性标记 /// </summary> private bool CheckIsTypeOrBaseTypeHasBaseAttributeInherit(INamedTypeSymbol namedTypeSymbol) { INamedTypeSymbol? typeSymbol = namedTypeSymbol; while (typeSymbol != null) { if (typeSymbol.HasBaseAttribute(Definition.BaseAttribute)) { return true; } typeSymbol = typeSymbol.BaseType; } return false; } } }
ET/Share/Analyzer/Analyzer/ClassDeclarationInHotfixAnalyzer.cs/0
{ "file_path": "ET/Share/Analyzer/Analyzer/ClassDeclarationInHotfixAnalyzer.cs", "repo_id": "ET", "token_count": 1760 }
87
using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace ET.Analyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class StaticFieldDeclarationAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>ImmutableArray.Create(StaticFieldDeclarationAnalyzerRule.Rule); public override void Initialize(AnalysisContext context) { if (!AnalyzerGlobalSetting.EnableAnalyzer) { return; } context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); context.RegisterSymbolAction(this.Analyzer, SymbolKind.NamedType); } private void Analyzer(SymbolAnalysisContext context) { if (!AnalyzerHelper.IsAssemblyNeedAnalyze(context.Compilation.AssemblyName, AnalyzeAssembly.All)) { return; } if (!(context.Symbol is INamedTypeSymbol namedTypeSymbol)) { return; } foreach (ISymbol? memberSymbol in namedTypeSymbol.GetMembers()) { if (memberSymbol is IFieldSymbol { IsConst: false,IsStatic:true } or IPropertySymbol { IsStatic: true }) { bool hasAttr = memberSymbol.GetAttributes().Any(x => x.AttributeClass?.ToString() == Definition.StaticFieldAttribute); if (!hasAttr) { ReportDiagnostic(memberSymbol); } } } void ReportDiagnostic(ISymbol symbol) { foreach (SyntaxReference? declaringSyntaxReference in symbol.DeclaringSyntaxReferences) { Diagnostic diagnostic = Diagnostic.Create(StaticFieldDeclarationAnalyzerRule.Rule, declaringSyntaxReference.GetSyntax()?.GetLocation(), symbol.Name); context.ReportDiagnostic(diagnostic); } } } } }
ET/Share/Analyzer/Analyzer/StaticFieldDeclarationAnalyzer.cs/0
{ "file_path": "ET/Share/Analyzer/Analyzer/StaticFieldDeclarationAnalyzer.cs", "repo_id": "ET", "token_count": 1059 }
88
## 目录介绍 ./cmake/: 用于Android和IOS构建的cmake文件 ./Include/: 用于P/Invoke的头文件 ./Source/: 用于P/Invoke的Cpp文件 CmakeLists.txt: CmakeLists文件 其余批处理文件皆为一键生成对应平台动态/静态链接库的入口,直接执行即可 比如要编译linux版本的动态链接库,则需要通过在Linux上通过命令行来执行sh文件 ## 编译步骤 clone [recastnavigation](https://github.com/recastnavigation/recastnavigation) 仓库到本地 将本目录直接复制粘贴到Clone的recastnavigation目录 ![image](https://user-images.githubusercontent.com/35335061/149318618-bc62a6b1-2afa-41df-a5ea-83655bb1625f.png) 随后执行批处理程序即可
ET/Share/Libs/RecastDll/Readme.md/0
{ "file_path": "ET/Share/Libs/RecastDll/Readme.md", "repo_id": "ET", "token_count": 409 }
89
using System.Collections.Generic; using System.Linq; using System.Text; using ET.Analyzer; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace ET.Generator; [Generator(LanguageNames.CSharp)] public class ETGetComponentGenerator : ISourceGenerator { public void Initialize(GeneratorInitializationContext context) { //context.RegisterForSyntaxNotifications(SyntaxContextReceiver.Create); } public void Execute(GeneratorExecutionContext context) { if (context.SyntaxContextReceiver is not SyntaxContextReceiver receiver || receiver.ComponentOfDatas.Count==0 ) { return; } foreach (var kv in receiver.ComponentOfDatas) { GenerateCSFiles(context, kv.Key,kv.Value); } } private void GenerateCSFiles(GeneratorExecutionContext context,string nameSpace, List<ComponentOfData> componentOfDatas) { StringBuilder contenSb = new StringBuilder(); foreach (var componentOfData in componentOfDatas) { GenerateGetComponentCode(context, componentOfData, contenSb); } string? assemblyName = context.Compilation.AssemblyName?.Replace(".", "_"); string code = $$""" namespace {{nameSpace}} { public static class {{assemblyName}}ETGetComponentExtension { {{contenSb}} } } """; context.AddSource($"ETGetComponentGenerator.{nameSpace}.g.cs", code); } private void GenerateGetComponentCode(GeneratorExecutionContext context,ComponentOfData componentOfData,StringBuilder contenSb) { string getComponentName = componentOfData.ComponentName; string parentEntityName = componentOfData.ParentEntityName; contenSb.AppendLine($$""" public static {{getComponentName}} Get{{getComponentName}} (this {{parentEntityName}} self) { return self.GetComponent<{{getComponentName}}>(); } """); } struct ComponentOfData { public string ComponentName; public string ParentEntityName; } class SyntaxContextReceiver: ISyntaxContextReceiver { internal static ISyntaxContextReceiver Create() { return new SyntaxContextReceiver(); } public Dictionary<string, List<ComponentOfData>> ComponentOfDatas = new(); public void OnVisitSyntaxNode(GeneratorSyntaxContext context) { SyntaxNode node = context.Node; if (node is not ClassDeclarationSyntax classDeclarationSyntax) { return; } if (classDeclarationSyntax.AttributeLists.Count==0) { return; } var classTypeSymbol = context.SemanticModel.GetDeclaredSymbol(classDeclarationSyntax) as INamedTypeSymbol; if (classTypeSymbol==null) { return; } // 筛选出含有 ComponentOf标签的 var componentOfAttrData = classTypeSymbol.GetFirstAttribute(Definition.ComponentOfAttribute); if (componentOfAttrData==null) { return; } // 忽略无Type参数的 if (componentOfAttrData.ConstructorArguments[0].Value is not INamedTypeSymbol parentEntityTypeSymbol) { return; } string? nameSpace = classTypeSymbol.GetNameSpace(); if (nameSpace==null) { return; } if (!ComponentOfDatas.ContainsKey(nameSpace)) { ComponentOfDatas.Add(nameSpace,new()); } this.ComponentOfDatas[nameSpace].Add(new ComponentOfData() { ComponentName = classTypeSymbol.Name, ParentEntityName = parentEntityTypeSymbol.Name, }); } } }
ET/Share/Share.SourceGenerator/Generator/ETGetComponentGenerator.cs/0
{ "file_path": "ET/Share/Share.SourceGenerator/Generator/ETGetComponentGenerator.cs", "repo_id": "ET", "token_count": 1787 }
90
# YIUI-ET ET7.2 [详细查看7.2分支](https://github.com/LiShengYang-yiyi/YIUI/tree/YIUI-ET7.2) ET8.0 [详细查看8.0分支](https://github.com/LiShengYang-yiyi/YIUI/tree/YIUI-ET8.0) ET8.1 [详细查看8.1分支](https://github.com/LiShengYang-yiyi/YIUI/tree/YIUI-ET8.1) # YIUI视频教程 [YIUI视频教程](https://www.bilibili.com/video/BV1cz4y1s7QS) 0. 总览 1. 安装 2. 初始化项目 3. 主入口 4. Demo资源 5. 登录界面 6. CDE绑定功能 7. 加载界面 8. 主界面 9. 商店界面 10. 无限循环列表 11. 英雄界面 12. UI上显示3D模型 13. 红点系统 14. 多语言 # ET接入YIUI视频教程 [ET接入YIUI视频教程](https://www.bilibili.com/video/BV1s44y1F7aZ) 0. 准备工作 1. 接入YIUI框架 2. ET Core 文件的补充 3. ET.shl 添加YIUI项目 4. ET YIUI 程序集关联 5. ET 生成器 分析器修改 6. Loader 添加YIUI程序集 7. YIUI初始化设置 8. YooAsset设置 9. 拷贝直接使用YIUI原生预制Demo 10. 代码启动YIUI框架 11. 打包设置 #[YIUI-ET7.2 视频介绍](https://www.bilibili.com/video/BV1KC4y1d7NZ)
ET/Store/YIUI.md/0
{ "file_path": "ET/Store/YIUI.md", "repo_id": "ET", "token_count": 780 }
91
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1 &1386170326414932 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 224438795553994780} - component: {fileID: 1431576037130298801} - component: {fileID: 1431576037130298803} - component: {fileID: 114905074804487618} m_Layer: 5 m_Name: UILSLobby m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &224438795553994780 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1386170326414932} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: - {fileID: 4771239781044397799} m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 0, y: 0} m_Pivot: {x: 0.5, y: 0.5} --- !u!223 &1431576037130298801 Canvas: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1386170326414932} m_Enabled: 1 serializedVersion: 3 m_RenderMode: 1 m_Camera: {fileID: 0} m_PlaneDistance: 100 m_PixelPerfect: 0 m_ReceivesEvents: 1 m_OverrideSorting: 0 m_OverridePixelPerfect: 0 m_SortingBucketNormalizedSize: 0 m_AdditionalShaderChannelsFlag: 0 m_SortingLayerID: 0 m_SortingOrder: 0 m_TargetDisplay: 0 --- !u!114 &1431576037130298803 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1386170326414932} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: dc42784cf147c0c48a680349fa168899, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreReversedGraphics: 1 m_BlockingObjects: 0 m_BlockingMask: serializedVersion: 2 m_Bits: 4294967295 --- !u!114 &114905074804487618 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1386170326414932} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 502d8cafd6a5a0447ab1db9a24cdcb10, type: 3} m_Name: m_EditorClassIdentifier: data: - key: EnterMap gameObject: {fileID: 899722670427233733} - key: Replay gameObject: {fileID: 8953588741749063052} - key: ReplayPath gameObject: {fileID: 4395569874077604387} --- !u!1 &899722670427233733 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 1109878335635189875} - component: {fileID: 1111846559939914969} - component: {fileID: 1003519326168939849} - component: {fileID: 7768120852135991652} m_Layer: 5 m_Name: Match m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &1109878335635189875 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 899722670427233733} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: - {fileID: 6091551359588390577} m_Father: {fileID: 4771239781044397799} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.5, y: 0.5} m_AnchorMax: {x: 0.5, y: 0.5} m_AnchoredPosition: {x: 0, y: 53} m_SizeDelta: {x: 263.5, y: 62.299988} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &1111846559939914969 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 899722670427233733} m_CullTransparentMesh: 0 --- !u!114 &1003519326168939849 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 899722670427233733} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 m_FillCenter: 1 m_FillMethod: 4 m_FillAmount: 1 m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 m_PixelsPerUnitMultiplier: 1 --- !u!114 &7768120852135991652 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 899722670427233733} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: m_Mode: 3 m_WrapAround: 0 m_SelectOnUp: {fileID: 0} m_SelectOnDown: {fileID: 0} m_SelectOnLeft: {fileID: 0} m_SelectOnRight: {fileID: 0} m_Transition: 1 m_Colors: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed m_SelectedTrigger: Selected m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 1003519326168939849} m_OnClick: m_PersistentCalls: m_Calls: [] --- !u!1 &3318750498554037093 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4771239781044397799} - component: {fileID: 7279718688677780413} - component: {fileID: 1396409096631843897} m_Layer: 5 m_Name: Panel m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &4771239781044397799 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 3318750498554037093} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: - {fileID: 8175113987340912499} - {fileID: 1109878335635189875} - {fileID: 4874256544544303799} m_Father: {fileID: 224438795553994780} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 0, y: 0} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &7279718688677780413 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 3318750498554037093} m_CullTransparentMesh: 1 --- !u!114 &1396409096631843897 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 3318750498554037093} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 0.392} m_RaycastTarget: 0 m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 m_FillCenter: 1 m_FillMethod: 4 m_FillAmount: 1 m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 m_PixelsPerUnitMultiplier: 1 --- !u!1 &3479259119195873563 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 2076769517444835984} - component: {fileID: 138414179539499625} - component: {fileID: 1071148689110842223} m_Layer: 5 m_Name: Placeholder m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &2076769517444835984 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 3479259119195873563} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 2768584574692861273} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: -0.5} m_SizeDelta: {x: -20, y: -13} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &138414179539499625 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 3479259119195873563} m_CullTransparentMesh: 1 --- !u!114 &1071148689110842223 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 3479259119195873563} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.23584908, g: 0.23584908, b: 0.23584908, a: 0.5} m_RaycastTarget: 1 m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 20 m_FontStyle: 2 m_BestFit: 0 m_MinSize: 2 m_MaxSize: 40 m_Alignment: 3 m_AlignByGeometry: 0 m_RichText: 1 m_HorizontalOverflow: 0 m_VerticalOverflow: 0 m_LineSpacing: 1 m_Text: Enter text... --- !u!1 &3693083160201062571 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 736899194757976890} - component: {fileID: 7106128318160646470} - component: {fileID: 8168496817488904769} m_Layer: 5 m_Name: Text m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &736899194757976890 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 3693083160201062571} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 7621972986425101864} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 0, y: 0} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &7106128318160646470 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 3693083160201062571} m_CullTransparentMesh: 0 --- !u!114 &8168496817488904769 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 3693083160201062571} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 1 m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 20 m_FontStyle: 0 m_BestFit: 0 m_MinSize: 2 m_MaxSize: 40 m_Alignment: 4 m_AlignByGeometry: 0 m_RichText: 1 m_HorizontalOverflow: 0 m_VerticalOverflow: 0 m_LineSpacing: 1 m_Text: Replay --- !u!1 &4395569874077604387 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 2768584574692861273} - component: {fileID: 3859870581258374020} - component: {fileID: 2564991462387735650} - component: {fileID: 1888676198012664535} m_Layer: 5 m_Name: ReplayPath m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &2768584574692861273 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 4395569874077604387} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: - {fileID: 2076769517444835984} - {fileID: 2859361732101890305} m_Father: {fileID: 4874256544544303799} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.5, y: 0.5} m_AnchorMax: {x: 0.5, y: 0.5} m_AnchoredPosition: {x: 120.31, y: -61.570007} m_SizeDelta: {x: 240.62952, y: 57.15} m_Pivot: {x: 1, y: 0.5} --- !u!222 &3859870581258374020 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 4395569874077604387} m_CullTransparentMesh: 1 --- !u!114 &2564991462387735650 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 4395569874077604387} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Sprite: {fileID: 10911, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 m_FillCenter: 1 m_FillMethod: 4 m_FillAmount: 1 m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 m_PixelsPerUnitMultiplier: 1 --- !u!114 &1888676198012664535 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 4395569874077604387} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: d199490a83bb2b844b9695cbf13b01ef, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: m_Mode: 3 m_WrapAround: 0 m_SelectOnUp: {fileID: 0} m_SelectOnDown: {fileID: 0} m_SelectOnLeft: {fileID: 0} m_SelectOnRight: {fileID: 0} m_Transition: 1 m_Colors: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed m_SelectedTrigger: Selected m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 2564991462387735650} m_TextComponent: {fileID: 6858719830969498837} m_Placeholder: {fileID: 1071148689110842223} m_ContentType: 0 m_InputType: 0 m_AsteriskChar: 42 m_KeyboardType: 0 m_LineType: 0 m_HideMobileInput: 0 m_CharacterValidation: 0 m_CharacterLimit: 0 m_OnSubmit: m_PersistentCalls: m_Calls: [] m_OnDidEndEdit: m_PersistentCalls: m_Calls: [] m_OnValueChanged: m_PersistentCalls: m_Calls: [] m_CaretColor: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_CustomCaretColor: 0 m_SelectionColor: {r: 0.65882355, g: 0.80784315, b: 1, a: 0.7529412} m_Text: m_CaretBlinkRate: 0.85 m_CaretWidth: 1 m_ReadOnly: 0 m_ShouldActivateOnSelect: 1 --- !u!1 &4567620429296564010 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4874256544544303799} m_Layer: 5 m_Name: GameObject m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &4874256544544303799 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 4567620429296564010} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: - {fileID: 2768584574692861273} - {fileID: 7621972986425101864} m_Father: {fileID: 4771239781044397799} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 0, y: 0} m_Pivot: {x: 0.5, y: 0.5} --- !u!1 &5394418754133166232 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 8175113987340912499} - component: {fileID: 3576686515681475339} - component: {fileID: 8589881667938238871} m_Layer: 5 m_Name: Image m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &8175113987340912499 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 5394418754133166232} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 4771239781044397799} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 0, y: 0} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &3576686515681475339 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 5394418754133166232} m_CullTransparentMesh: 1 --- !u!114 &8589881667938238871 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 5394418754133166232} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.5754717, g: 0.31216627, b: 0.31216627, a: 1} m_RaycastTarget: 0 m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 m_FillCenter: 1 m_FillMethod: 4 m_FillAmount: 1 m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 m_PixelsPerUnitMultiplier: 1 --- !u!1 &6310363376444861169 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 6091551359588390577} - component: {fileID: 6089323556358314843} - component: {fileID: 6197011583270449923} m_Layer: 5 m_Name: Text m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &6091551359588390577 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 6310363376444861169} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 1109878335635189875} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 0, y: 0} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &6089323556358314843 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 6310363376444861169} m_CullTransparentMesh: 0 --- !u!114 &6197011583270449923 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 6310363376444861169} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 1 m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 20 m_FontStyle: 0 m_BestFit: 0 m_MinSize: 2 m_MaxSize: 40 m_Alignment: 4 m_AlignByGeometry: 0 m_RichText: 1 m_HorizontalOverflow: 0 m_VerticalOverflow: 0 m_LineSpacing: 1 m_Text: Match --- !u!1 &6941100451382580996 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 2859361732101890305} - component: {fileID: 8906366112307339978} - component: {fileID: 6858719830969498837} m_Layer: 5 m_Name: Text m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &2859361732101890305 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 6941100451382580996} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 2768584574692861273} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: -0.5} m_SizeDelta: {x: -20, y: -13} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &8906366112307339978 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 6941100451382580996} m_CullTransparentMesh: 1 --- !u!114 &6858719830969498837 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 6941100451382580996} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0, g: 0, b: 0, a: 1} m_RaycastTarget: 1 m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 20 m_FontStyle: 0 m_BestFit: 0 m_MinSize: 2 m_MaxSize: 40 m_Alignment: 3 m_AlignByGeometry: 0 m_RichText: 0 m_HorizontalOverflow: 1 m_VerticalOverflow: 0 m_LineSpacing: 1 m_Text: --- !u!1 &8953588741749063052 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7621972986425101864} - component: {fileID: 2846390290717257282} - component: {fileID: 2794544952984314283} - component: {fileID: 4259866312124243016} m_Layer: 5 m_Name: Replay m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &7621972986425101864 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 8953588741749063052} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_ConstrainProportionsScale: 0 m_Children: - {fileID: 736899194757976890} m_Father: {fileID: 4874256544544303799} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.5, y: 0.5} m_AnchorMax: {x: 0.5, y: 0.5} m_AnchoredPosition: {x: 0, y: -135} m_SizeDelta: {x: 133.3943, y: 62.300003} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &2846390290717257282 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 8953588741749063052} m_CullTransparentMesh: 0 --- !u!114 &2794544952984314283 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 8953588741749063052} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 m_FillCenter: 1 m_FillMethod: 4 m_FillAmount: 1 m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 m_PixelsPerUnitMultiplier: 1 --- !u!114 &4259866312124243016 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 8953588741749063052} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: m_Mode: 3 m_WrapAround: 0 m_SelectOnUp: {fileID: 0} m_SelectOnDown: {fileID: 0} m_SelectOnLeft: {fileID: 0} m_SelectOnRight: {fileID: 0} m_Transition: 1 m_Colors: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed m_SelectedTrigger: Selected m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 2794544952984314283} m_OnClick: m_PersistentCalls: m_Calls: []
ET/Unity/Assets/Bundles/UI/LockStep/UILSLobby.prefab/0
{ "file_path": "ET/Unity/Assets/Bundles/UI/LockStep/UILSLobby.prefab", "repo_id": "ET", "token_count": 13814 }
92
fileFormatVersion: 2 guid: 03fee2b7103050f478a689d2785db7e9 DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Config/Excel/StartConfig/Benchmark/[email protected]/0
{ "file_path": "ET/Unity/Assets/Config/Excel/StartConfig/Benchmark/[email protected]", "repo_id": "ET", "token_count": 63 }
93
fileFormatVersion: 2 guid: f35157653367b5340a880c68a61520c8 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Config/Excel/StartConfig/Release.meta/0
{ "file_path": "ET/Unity/Assets/Config/Excel/StartConfig/Release.meta", "repo_id": "ET", "token_count": 68 }
94
fileFormatVersion: 2 guid: 83ff7a714531dec43b3e6cd79d76d4b7 PluginImporter: externalObjects: {} serializedVersion: 2 iconMap: {} executionOrder: {} defineConstraints: [] isPreloaded: 0 isOverridable: 0 isExplicitlyReferenced: 0 validateReferences: 1 platformData: - first: : Any second: enabled: 0 settings: Exclude Android: 1 Exclude Editor: 0 Exclude Linux64: 0 Exclude OSXUniversal: 0 Exclude Win: 0 Exclude Win64: 0 Exclude iOS: 1 - first: Android: Android second: enabled: 0 settings: CPU: ARMv7 - first: Any: second: enabled: 0 settings: {} - first: Editor: Editor second: enabled: 1 settings: CPU: AnyCPU DefaultValueInitialized: true OS: AnyOS - first: Standalone: Linux64 second: enabled: 1 settings: CPU: AnyCPU - first: Standalone: OSXUniversal second: enabled: 1 settings: CPU: AnyCPU - first: Standalone: Win second: enabled: 1 settings: CPU: x86 - first: Standalone: Win64 second: enabled: 1 settings: CPU: x86_64 - first: Windows Store Apps: WindowsStoreApps second: enabled: 0 settings: CPU: AnyCPU - first: iPhone: iOS second: enabled: 0 settings: AddToEmbeddedBinaries: false CPU: AnyCPU CompileFlags: FrameworkDependencies: userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Plugins/MongoDB/SharpCompress.dll.meta/0
{ "file_path": "ET/Unity/Assets/Plugins/MongoDB/SharpCompress.dll.meta", "repo_id": "ET", "token_count": 775 }
95
fileFormatVersion: 2 guid: 0b731199ac3348e458e1ff49f04702cd folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Plugins/MongoDB/runtimes/osx.meta/0
{ "file_path": "ET/Unity/Assets/Plugins/MongoDB/runtimes/osx.meta", "repo_id": "ET", "token_count": 68 }
96
fileFormatVersion: 2 guid: 313955cd6271f5c4985cba4adc30fc8e NativeFormatImporter: externalObjects: {} mainObjectFileID: 11400000 userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Res/UniversalRenderPipelineAsset.asset.meta/0
{ "file_path": "ET/Unity/Assets/Res/UniversalRenderPipelineAsset.asset.meta", "repo_id": "ET", "token_count": 76 }
97
using System; namespace ET { /// <summary> /// 组件类父级实体类型约束 /// 父级实体类型唯一的 标记指定父级实体类型[ComponentOf(typeof(parentType)] /// 不唯一则标记[ComponentOf] /// </summary> [AttributeUsage(AttributeTargets.Class)] public class ComponentOfAttribute : Attribute { public Type Type; public ComponentOfAttribute(Type type = null) { this.Type = type; } } }
ET/Unity/Assets/Scripts/Core/Analyzer/ComponentOfAttribute.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Analyzer/ComponentOfAttribute.cs", "repo_id": "ET", "token_count": 253 }
98
using System; namespace ET { /// <summary> /// 唯一Id标签 /// 使用此标签标记的类 会检测类内部的 const int 字段成员是否唯一 /// 可以指定唯一Id的最小值 最大值区间 /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = false)] public class UniqueIdAttribute : Attribute { public int Min; public int Max; public UniqueIdAttribute(int min = int.MinValue, int max = int.MaxValue) { this.Min = min; this.Max = max; } } }
ET/Unity/Assets/Scripts/Core/Analyzer/UniqueIdAttribute.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Analyzer/UniqueIdAttribute.cs", "repo_id": "ET", "token_count": 303 }
99