hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
88bfefd00901175cdc9137ed3ac2de634e1796b6
18,247
h
C
aws-cpp-sdk-mediastore-data/include/aws/mediastore-data/model/GetObjectRequest.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-mediastore-data/include/aws/mediastore-data/model/GetObjectRequest.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-mediastore-data/include/aws/mediastore-data/model/GetObjectRequest.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/mediastore-data/MediaStoreData_EXPORTS.h> #include <aws/mediastore-data/MediaStoreDataRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace MediaStoreData { namespace Model { /** */ class AWS_MEDIASTOREDATA_API GetObjectRequest : public MediaStoreDataRequest { public: GetObjectRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "GetObject"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The path (including the file name) where the object is stored in the * container. Format: &lt;folder name&gt;/&lt;folder name&gt;/&lt;file name&gt;</p> * <p>For example, to upload the file <code>mlaw.avi</code> to the folder path * <code>premium\canada</code> in the container <code>movies</code>, enter the path * <code>premium/canada/mlaw.avi</code>.</p> <p>Do not include the container name * in this path.</p> <p>If the path includes any folders that don't exist yet, the * service creates them. For example, suppose you have an existing * <code>premium/usa</code> subfolder. If you specify <code>premium/canada</code>, * the service creates a <code>canada</code> subfolder in the <code>premium</code> * folder. You then have two subfolders, <code>usa</code> and <code>canada</code>, * in the <code>premium</code> folder. </p> <p>There is no correlation between the * path to the source and the path (folders) in the container in AWS Elemental * MediaStore.</p> <p>For more information about folders and how they exist in a * container, see the <a * href="http://docs.aws.amazon.com/mediastore/latest/ug/">AWS Elemental MediaStore * User Guide</a>.</p> <p>The file name is the name that is assigned to the file * that you upload. The file can have the same name inside and outside of AWS * Elemental MediaStore, or it can have the same name. The file name can include or * omit an extension. </p> */ inline const Aws::String& GetPath() const{ return m_path; } /** * <p>The path (including the file name) where the object is stored in the * container. Format: &lt;folder name&gt;/&lt;folder name&gt;/&lt;file name&gt;</p> * <p>For example, to upload the file <code>mlaw.avi</code> to the folder path * <code>premium\canada</code> in the container <code>movies</code>, enter the path * <code>premium/canada/mlaw.avi</code>.</p> <p>Do not include the container name * in this path.</p> <p>If the path includes any folders that don't exist yet, the * service creates them. For example, suppose you have an existing * <code>premium/usa</code> subfolder. If you specify <code>premium/canada</code>, * the service creates a <code>canada</code> subfolder in the <code>premium</code> * folder. You then have two subfolders, <code>usa</code> and <code>canada</code>, * in the <code>premium</code> folder. </p> <p>There is no correlation between the * path to the source and the path (folders) in the container in AWS Elemental * MediaStore.</p> <p>For more information about folders and how they exist in a * container, see the <a * href="http://docs.aws.amazon.com/mediastore/latest/ug/">AWS Elemental MediaStore * User Guide</a>.</p> <p>The file name is the name that is assigned to the file * that you upload. The file can have the same name inside and outside of AWS * Elemental MediaStore, or it can have the same name. The file name can include or * omit an extension. </p> */ inline bool PathHasBeenSet() const { return m_pathHasBeenSet; } /** * <p>The path (including the file name) where the object is stored in the * container. Format: &lt;folder name&gt;/&lt;folder name&gt;/&lt;file name&gt;</p> * <p>For example, to upload the file <code>mlaw.avi</code> to the folder path * <code>premium\canada</code> in the container <code>movies</code>, enter the path * <code>premium/canada/mlaw.avi</code>.</p> <p>Do not include the container name * in this path.</p> <p>If the path includes any folders that don't exist yet, the * service creates them. For example, suppose you have an existing * <code>premium/usa</code> subfolder. If you specify <code>premium/canada</code>, * the service creates a <code>canada</code> subfolder in the <code>premium</code> * folder. You then have two subfolders, <code>usa</code> and <code>canada</code>, * in the <code>premium</code> folder. </p> <p>There is no correlation between the * path to the source and the path (folders) in the container in AWS Elemental * MediaStore.</p> <p>For more information about folders and how they exist in a * container, see the <a * href="http://docs.aws.amazon.com/mediastore/latest/ug/">AWS Elemental MediaStore * User Guide</a>.</p> <p>The file name is the name that is assigned to the file * that you upload. The file can have the same name inside and outside of AWS * Elemental MediaStore, or it can have the same name. The file name can include or * omit an extension. </p> */ inline void SetPath(const Aws::String& value) { m_pathHasBeenSet = true; m_path = value; } /** * <p>The path (including the file name) where the object is stored in the * container. Format: &lt;folder name&gt;/&lt;folder name&gt;/&lt;file name&gt;</p> * <p>For example, to upload the file <code>mlaw.avi</code> to the folder path * <code>premium\canada</code> in the container <code>movies</code>, enter the path * <code>premium/canada/mlaw.avi</code>.</p> <p>Do not include the container name * in this path.</p> <p>If the path includes any folders that don't exist yet, the * service creates them. For example, suppose you have an existing * <code>premium/usa</code> subfolder. If you specify <code>premium/canada</code>, * the service creates a <code>canada</code> subfolder in the <code>premium</code> * folder. You then have two subfolders, <code>usa</code> and <code>canada</code>, * in the <code>premium</code> folder. </p> <p>There is no correlation between the * path to the source and the path (folders) in the container in AWS Elemental * MediaStore.</p> <p>For more information about folders and how they exist in a * container, see the <a * href="http://docs.aws.amazon.com/mediastore/latest/ug/">AWS Elemental MediaStore * User Guide</a>.</p> <p>The file name is the name that is assigned to the file * that you upload. The file can have the same name inside and outside of AWS * Elemental MediaStore, or it can have the same name. The file name can include or * omit an extension. </p> */ inline void SetPath(Aws::String&& value) { m_pathHasBeenSet = true; m_path = std::move(value); } /** * <p>The path (including the file name) where the object is stored in the * container. Format: &lt;folder name&gt;/&lt;folder name&gt;/&lt;file name&gt;</p> * <p>For example, to upload the file <code>mlaw.avi</code> to the folder path * <code>premium\canada</code> in the container <code>movies</code>, enter the path * <code>premium/canada/mlaw.avi</code>.</p> <p>Do not include the container name * in this path.</p> <p>If the path includes any folders that don't exist yet, the * service creates them. For example, suppose you have an existing * <code>premium/usa</code> subfolder. If you specify <code>premium/canada</code>, * the service creates a <code>canada</code> subfolder in the <code>premium</code> * folder. You then have two subfolders, <code>usa</code> and <code>canada</code>, * in the <code>premium</code> folder. </p> <p>There is no correlation between the * path to the source and the path (folders) in the container in AWS Elemental * MediaStore.</p> <p>For more information about folders and how they exist in a * container, see the <a * href="http://docs.aws.amazon.com/mediastore/latest/ug/">AWS Elemental MediaStore * User Guide</a>.</p> <p>The file name is the name that is assigned to the file * that you upload. The file can have the same name inside and outside of AWS * Elemental MediaStore, or it can have the same name. The file name can include or * omit an extension. </p> */ inline void SetPath(const char* value) { m_pathHasBeenSet = true; m_path.assign(value); } /** * <p>The path (including the file name) where the object is stored in the * container. Format: &lt;folder name&gt;/&lt;folder name&gt;/&lt;file name&gt;</p> * <p>For example, to upload the file <code>mlaw.avi</code> to the folder path * <code>premium\canada</code> in the container <code>movies</code>, enter the path * <code>premium/canada/mlaw.avi</code>.</p> <p>Do not include the container name * in this path.</p> <p>If the path includes any folders that don't exist yet, the * service creates them. For example, suppose you have an existing * <code>premium/usa</code> subfolder. If you specify <code>premium/canada</code>, * the service creates a <code>canada</code> subfolder in the <code>premium</code> * folder. You then have two subfolders, <code>usa</code> and <code>canada</code>, * in the <code>premium</code> folder. </p> <p>There is no correlation between the * path to the source and the path (folders) in the container in AWS Elemental * MediaStore.</p> <p>For more information about folders and how they exist in a * container, see the <a * href="http://docs.aws.amazon.com/mediastore/latest/ug/">AWS Elemental MediaStore * User Guide</a>.</p> <p>The file name is the name that is assigned to the file * that you upload. The file can have the same name inside and outside of AWS * Elemental MediaStore, or it can have the same name. The file name can include or * omit an extension. </p> */ inline GetObjectRequest& WithPath(const Aws::String& value) { SetPath(value); return *this;} /** * <p>The path (including the file name) where the object is stored in the * container. Format: &lt;folder name&gt;/&lt;folder name&gt;/&lt;file name&gt;</p> * <p>For example, to upload the file <code>mlaw.avi</code> to the folder path * <code>premium\canada</code> in the container <code>movies</code>, enter the path * <code>premium/canada/mlaw.avi</code>.</p> <p>Do not include the container name * in this path.</p> <p>If the path includes any folders that don't exist yet, the * service creates them. For example, suppose you have an existing * <code>premium/usa</code> subfolder. If you specify <code>premium/canada</code>, * the service creates a <code>canada</code> subfolder in the <code>premium</code> * folder. You then have two subfolders, <code>usa</code> and <code>canada</code>, * in the <code>premium</code> folder. </p> <p>There is no correlation between the * path to the source and the path (folders) in the container in AWS Elemental * MediaStore.</p> <p>For more information about folders and how they exist in a * container, see the <a * href="http://docs.aws.amazon.com/mediastore/latest/ug/">AWS Elemental MediaStore * User Guide</a>.</p> <p>The file name is the name that is assigned to the file * that you upload. The file can have the same name inside and outside of AWS * Elemental MediaStore, or it can have the same name. The file name can include or * omit an extension. </p> */ inline GetObjectRequest& WithPath(Aws::String&& value) { SetPath(std::move(value)); return *this;} /** * <p>The path (including the file name) where the object is stored in the * container. Format: &lt;folder name&gt;/&lt;folder name&gt;/&lt;file name&gt;</p> * <p>For example, to upload the file <code>mlaw.avi</code> to the folder path * <code>premium\canada</code> in the container <code>movies</code>, enter the path * <code>premium/canada/mlaw.avi</code>.</p> <p>Do not include the container name * in this path.</p> <p>If the path includes any folders that don't exist yet, the * service creates them. For example, suppose you have an existing * <code>premium/usa</code> subfolder. If you specify <code>premium/canada</code>, * the service creates a <code>canada</code> subfolder in the <code>premium</code> * folder. You then have two subfolders, <code>usa</code> and <code>canada</code>, * in the <code>premium</code> folder. </p> <p>There is no correlation between the * path to the source and the path (folders) in the container in AWS Elemental * MediaStore.</p> <p>For more information about folders and how they exist in a * container, see the <a * href="http://docs.aws.amazon.com/mediastore/latest/ug/">AWS Elemental MediaStore * User Guide</a>.</p> <p>The file name is the name that is assigned to the file * that you upload. The file can have the same name inside and outside of AWS * Elemental MediaStore, or it can have the same name. The file name can include or * omit an extension. </p> */ inline GetObjectRequest& WithPath(const char* value) { SetPath(value); return *this;} /** * <p>The range bytes of an object to retrieve. For more information about the * <code>Range</code> header, see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35</a>. * AWS Elemental MediaStore ignores this header for partially uploaded objects that * have streaming upload availability.</p> */ inline const Aws::String& GetRange() const{ return m_range; } /** * <p>The range bytes of an object to retrieve. For more information about the * <code>Range</code> header, see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35</a>. * AWS Elemental MediaStore ignores this header for partially uploaded objects that * have streaming upload availability.</p> */ inline bool RangeHasBeenSet() const { return m_rangeHasBeenSet; } /** * <p>The range bytes of an object to retrieve. For more information about the * <code>Range</code> header, see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35</a>. * AWS Elemental MediaStore ignores this header for partially uploaded objects that * have streaming upload availability.</p> */ inline void SetRange(const Aws::String& value) { m_rangeHasBeenSet = true; m_range = value; } /** * <p>The range bytes of an object to retrieve. For more information about the * <code>Range</code> header, see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35</a>. * AWS Elemental MediaStore ignores this header for partially uploaded objects that * have streaming upload availability.</p> */ inline void SetRange(Aws::String&& value) { m_rangeHasBeenSet = true; m_range = std::move(value); } /** * <p>The range bytes of an object to retrieve. For more information about the * <code>Range</code> header, see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35</a>. * AWS Elemental MediaStore ignores this header for partially uploaded objects that * have streaming upload availability.</p> */ inline void SetRange(const char* value) { m_rangeHasBeenSet = true; m_range.assign(value); } /** * <p>The range bytes of an object to retrieve. For more information about the * <code>Range</code> header, see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35</a>. * AWS Elemental MediaStore ignores this header for partially uploaded objects that * have streaming upload availability.</p> */ inline GetObjectRequest& WithRange(const Aws::String& value) { SetRange(value); return *this;} /** * <p>The range bytes of an object to retrieve. For more information about the * <code>Range</code> header, see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35</a>. * AWS Elemental MediaStore ignores this header for partially uploaded objects that * have streaming upload availability.</p> */ inline GetObjectRequest& WithRange(Aws::String&& value) { SetRange(std::move(value)); return *this;} /** * <p>The range bytes of an object to retrieve. For more information about the * <code>Range</code> header, see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35</a>. * AWS Elemental MediaStore ignores this header for partially uploaded objects that * have streaming upload availability.</p> */ inline GetObjectRequest& WithRange(const char* value) { SetRange(value); return *this;} private: Aws::String m_path; bool m_pathHasBeenSet; Aws::String m_range; bool m_rangeHasBeenSet; }; } // namespace Model } // namespace MediaStoreData } // namespace Aws
59.630719
146
0.686469
[ "object", "model" ]
88c4da1f206b2cf7703820573b713ec62ea28a70
2,417
c
C
AudioKit/Core/Sporth/ugens/render.c
ethi1989/AudioKit
97acc8da6dfb75408b2276998073de7a4511d480
[ "MIT" ]
350
2015-08-16T21:49:01.000Z
2021-08-28T21:42:44.000Z
AudioKit/Core/Sporth/ugens/render.c
ethi1989/AudioKit
97acc8da6dfb75408b2276998073de7a4511d480
[ "MIT" ]
37
2015-09-03T14:16:12.000Z
2021-05-17T21:26:23.000Z
AudioKit/Core/Sporth/ugens/render.c
ethi1989/AudioKit
97acc8da6dfb75408b2276998073de7a4511d480
[ "MIT" ]
41
2015-08-16T23:01:11.000Z
2021-12-27T12:46:15.000Z
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "plumber.h" typedef struct { plumbing pipes; plumber_ftentry ft[256]; } sporth_render_d; int sporth_render(sporth_stack *stack, void *ud) { plumber_data *pd = ud; sporth_render_d *rend; FILE *tmp, *fp; plumber_ftentry *old_ftmap; const char *filename; int rc = PLUMBER_OK; switch(pd->mode){ case PLUMBER_CREATE: rend = malloc(sizeof(sporth_render_d)); plumber_add_ugen(pd, SPORTH_RENDER, rend); if(sporth_check_args(stack, "s") != SPORTH_OK) { plumber_print(pd, "Not enough arguments for render.\n"); return PLUMBER_NOTOK; } filename = sporth_stack_pop_string(stack); fp = fopen(filename, "r"); if(fp == NULL) { plumber_print(pd, "There was an issue opening the file \"%s\"\n", filename); return PLUMBER_NOTOK; } tmp = pd->fp; old_ftmap = pd->ftmap; pd->fp = fp; pd->ftmap = rend->ft; plumber_ftmap_init(pd); plumbing_init(&rend->pipes); rc = plumbing_parse(pd, &rend->pipes); fclose(fp); pd->fp = tmp; pd->ftmap = old_ftmap; return rc; case PLUMBER_INIT: rend = pd->last->ud; old_ftmap = pd->ftmap; pd->ftmap = rend->ft; filename = sporth_stack_pop_string(stack); plumbing_compute(pd, &rend->pipes, PLUMBER_INIT); pd->ftmap = old_ftmap; break; case PLUMBER_COMPUTE: rend = pd->last->ud; old_ftmap = pd->ftmap; pd->ftmap = rend->ft; plumbing_compute(pd, &rend->pipes, PLUMBER_COMPUTE); pd->ftmap = old_ftmap; break; case PLUMBER_DESTROY: rend = pd->last->ud; old_ftmap = pd->ftmap; pd->ftmap = rend->ft; plumbing_compute(pd, &rend->pipes, PLUMBER_DESTROY); plumbing_destroy(&rend->pipes); plumber_ftmap_destroy(pd); pd->ftmap = old_ftmap; free(rend); break; default: printf("Error: Unknown mode!"); break; } return PLUMBER_OK; }
28.435294
72
0.511378
[ "render" ]
88cf4c7ef29ea4683d84f985bca950a50ff9c15d
1,280
h
C
src/cpp-ethereum/test/tools/libtesteth/Stats.h
nccproject/ncc
068ccc82a73d28136546095261ad8ccef7e541a3
[ "MIT" ]
42
2021-01-04T01:59:21.000Z
2021-05-14T14:35:04.000Z
src/cpp-ethereum/test/tools/libtesteth/Stats.h
estxcoin/estcore
4398b1d944373fe25668469966fa2660da454279
[ "MIT" ]
2
2021-01-04T02:08:47.000Z
2021-01-04T02:36:08.000Z
src/cpp-ethereum/test/tools/libtesteth/Stats.h
estxcoin/estcore
4398b1d944373fe25668469966fa2660da454279
[ "MIT" ]
15
2021-01-04T02:00:21.000Z
2021-01-06T02:06:43.000Z
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <chrono> #include <vector> #include "TestHelper.h" namespace dev { namespace test { class Stats: public Listener { public: using clock = std::chrono::high_resolution_clock; struct Item { clock::duration duration; int64_t gasUsed; std::string name; }; static Stats& get(); ~Stats() final; void suiteStarted(std::string const& _name) override; void testStarted(std::string const& _name) override; void testFinished(int64_t _gasUsed) override; private: clock::time_point m_tp; std::string m_currentSuite; std::string m_currentTest; std::vector<Item> m_stats; }; } }
21.694915
70
0.749219
[ "vector" ]
88d0500fc86791876a796cb7878920d710daed32
2,407
h
C
Forward_Model/source/loop.h
sjbradshaw/HYDRAD
4d5eb698570d8a631995be8bff52138dd4f4ef5e
[ "MIT" ]
6
2021-03-23T01:44:48.000Z
2022-02-09T16:50:05.000Z
Forward_Model/source/loop.h
sjbradshaw/HYDRAD
4d5eb698570d8a631995be8bff52138dd4f4ef5e
[ "MIT" ]
7
2021-03-23T01:56:34.000Z
2022-03-25T20:59:28.000Z
Forward_Model/source/loop.h
sjbradshaw/HYDRAD
4d5eb698570d8a631995be8bff52138dd4f4ef5e
[ "MIT" ]
2
2022-03-10T13:37:52.000Z
2022-03-30T16:25:30.000Z
// **** // * // * Loop class definition // * // * (c) Dr. Stephen J. Bradshaw // * // * Date last modified: 02/14/2017 // * // **** #include "strand.h" class CLoop { private: // The directory from which to read the data for the strands comprising the loop char szWorkingDirectory[256]; // The number of strands comprising the loop and the range of profiles to use as individual strands int iNumStrands, iStrandRange[3]; // Array of pointers to individual strands PPSTRAND ppStrand; // Function to initialise the Loop object void Initialise( char *pszWorkingDirectory, int iFrom, int iTo, int iStep, double fdH ); // Function to free all allocated memory void FreeAll( void ); public: // Constructor CLoop( char *pszWorkingDirectory, int iFrom, int iTo, int iStep, double fdH ); // Destructor ~CLoop( void ); // Function to the return a string pointing to the working directory name char *pGetWorkingDirectory( void ); // Functions to return the number of strands and the range of profiles used as individual strands int GetNumStrands( void ); void GetStrandRange( int *piStrandRange ); // Function to return the timestamp for a specified strand double GetTimeStamp( int iStrand ); // Function to return the number of grid cells for a specified strand int GetNumCells( int iStrand ); // Function to return the diameter of a specified strand double GetDiameter( int iStrand ); // Function to return the length of a specified strand double GetLength( int iStrand ); // Function to return the physical properties of a specified grid cell in a specified strand void GetPHYData( int iStrand, int iCell, PPHYDATA pStrandPHYData ); // Function to return the number of elements for which the non-equilibrium ionisation state exists for a specified strand int GetNumNEQElements( int iStrand ); // Function to return the atomic number of the specified element in the list for a specified strand int GetAtomicNumber( int iStrand, int iElement ); // Function to return the non-equilibrium ion population fraction of the specified ion / element for a specified cell / strand double GetNEQ( int iStrand, int iCell, int iElement, int iIon ); }; typedef CLoop* PLOOP;
31.671053
131
0.681346
[ "object" ]
88d0c0fe132be83f83adc600e1bd1c4f13b3183b
4,951
h
C
mindspore/ccsrc/frontend/optimizer/ad/kpynative.h
PowerOlive/mindspore
bda20724a94113cedd12c3ed9083141012da1f15
[ "Apache-2.0" ]
1
2022-02-23T09:13:43.000Z
2022-02-23T09:13:43.000Z
mindspore/ccsrc/frontend/optimizer/ad/kpynative.h
zimo-geek/mindspore
665ec683d4af85c71b2a1f0d6829356f2bc0e1ff
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/frontend/optimizer/ad/kpynative.h
zimo-geek/mindspore
665ec683d4af85c71b2a1f0d6829356f2bc0e1ff
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_AD_KPYNATIVE_H_ #define MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_AD_KPYNATIVE_H_ #include <memory> #include <vector> #include "ir/anf.h" #include "ir/func_graph.h" namespace mindspore { namespace ad { class KPynativeCell { public: virtual ~KPynativeCell() = default; virtual void UpdateOutputNodeOfTopCell(const AnfNodePtr &output_node) = 0; // Grad for cell which may have user passed front propagate FuncGraph. // c_node: CNode with contains the construct function graph of cell (index 0) and the formal input parameters of that // cell. op_args: the arguments list of each input parameters. // out: the op result. // fprop_fg: user defined back propagate cnode which output is the bprop_fg. // Should have prototype: (sens_input1, sens_input2, ...) bprop_fg(input1, input2, ..., out, dout) virtual bool KPynativeWithFProp(const CNodePtr &c_node, const ValuePtrList &op_args, const ValuePtr &out, const FuncGraphPtr &fprop_fg) = 0; }; using KPynativeCellPtr = std::shared_ptr<KPynativeCell>; // bprop_fg: user defined back propagate funcgraph or back propagate funcgraph of primitive, it will be passed after // just parsed. will have prototype: // (sens_input1, sens_input2, ...) bprop_fg(input1, input2, ..., out, dout) // c_node: CNode with contains the prim (index 0) and the formal input parameters of that prim. // op_args: the arguments list of each input parameters. // out: the op result. // return: the returned funcgraph should have the same prototype. FuncGraphPtr OptimizeBPropFuncGraph(const FuncGraphPtr &bprop_fg, const CNodePtr &c_node, const ValuePtrList &op_args, const ValuePtr &out); // Start building back propagate funcgraph for this cell. // cell_inputs: the input parameter list of this cell except the weights; KPynativeCellPtr GradPynativeCellBegin(const AnfNodePtrList &cell_inputs, const std::vector<ValuePtr> &input_param_values); // Return the back propagate funcgraph for this cell. // weights: weights parameters used in this cell. // grad_inputs: return sensitivity for input parameters; // grad_weights: return sensitivity for weights; // has_sens_arg: caller will pass sens args; // return: the returned funcgraph will have prototype: // if has_sens_arg is true // (sens_input1, sens_input2, ..., sens_weight0, sens_weight1, ) bprop_fg(input1, input2, ..., weight0, weight1, ..., // sens_out) // else: // (sens_input1, sens_input2, ..., sens_weight0, sens_weight1, ) bprop_fg(input1, input2, ..., weight0, weight1, ...) // if build_formal_param is true // each cnode in primal funcgraph is replaced by formal cnode // else: // each cnode in primal funcgraph is replaced by value node FuncGraphPtr GradPynativeCellEnd(const KPynativeCellPtr &k_cell, const AnfNodePtrList &weights, const std::vector<size_t> &grad_position, bool grad_inputs, bool grad_weights, bool has_sens_arg = false, bool build_formal_param = false); // Grad for each operation. // c_node: CNode with contains the prim (index 0) and the formal input parameters of that prim. // op_args: the arguments list of each input parameters. // out: the op result. bool GradPynativeOp(const KPynativeCellPtr &k_cell, const CNodePtr &c_node, const ValuePtrList &op_args, const ValuePtr &out); // Grad for cell which may have user defined back propagate function. // c_node: CNode with contains the construct function graph of cell (index 0) and the formal input parameters of that // cell. op_args: the arguments list of each input parameters. // out: the op result. // bprop_fg: user defined back propagate funcgraph, it should be passed after just parsed. // Should have prototype: (sens_input1, sens_input2, ...) bprop_fg(input1, input2, ..., out, dout) bool GradPynativeWithBProp(const KPynativeCellPtr &k_cell, const CNodePtr &c_node, const ValuePtrList &op_args, const ValuePtr &out, const FuncGraphPtr &bprop_fg); // Clear all static resources that used in grad process void ClearKPynativeCellStaticRes(); } // namespace ad } // namespace mindspore #endif // MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_AD_GRAD_H_
50.010101
120
0.727328
[ "vector" ]
88d2781329d41a1cf2026208fc4206a6721ec876
9,107
h
C
Gems/Atom/RHI/DX12/Code/Source/RHI/DescriptorContext.h
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/Atom/RHI/DX12/Code/Source/RHI/DescriptorContext.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/Atom/RHI/DX12/Code/Source/RHI/DescriptorContext.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <RHI/DescriptorPool.h> #include <AzCore/Memory/SystemAllocator.h> #include <Atom/RHI.Reflect/BufferViewDescriptor.h> #include <Atom/RHI.Reflect/ImageViewDescriptor.h> #include <Atom/RHI.Reflect/SamplerState.h> #include <Atom/RHI/Buffer.h> #include <Atom/RHI/Image.h> #include <AzCore/std/containers/unordered_map.h> #include <RHI/ShaderResourceGroup.h> namespace AZ { namespace DX12 { class Buffer; class Image; class PlatformLimitsDescriptor; //! Manages pools of descriptors. class DescriptorContext { public: AZ_CLASS_ALLOCATOR(DescriptorContext, AZ::SystemAllocator, 0); DescriptorContext() = default; void Init(ID3D12DeviceX* device, RHI::ConstPtr<PlatformLimitsDescriptor> platformLimitsDescriptor); void CreateConstantBufferView( const Buffer& buffer, const RHI::BufferViewDescriptor& bufferViewDescriptor, DescriptorHandle& constantBufferView); void CreateShaderResourceView( const Buffer& buffer, const RHI::BufferViewDescriptor& bufferViewDescriptor, DescriptorHandle& shaderResourceView); void CreateUnorderedAccessView( const Buffer& buffer, const RHI::BufferViewDescriptor& bufferViewDescriptor, DescriptorHandle& unorderedAccessView, DescriptorHandle& unorderedAccessViewClear); void CreateShaderResourceView( const Image& image, const RHI::ImageViewDescriptor& imageViewDescriptor, DescriptorHandle& shaderResourceView); void CreateUnorderedAccessView( const Image& image, const RHI::ImageViewDescriptor& imageViewDescriptor, DescriptorHandle& unorderedAccessView, DescriptorHandle& unorderedAccessViewClear); void CreateRenderTargetView( const Image& image, const RHI::ImageViewDescriptor& imageViewDescriptor, DescriptorHandle& renderTargetView); void CreateDepthStencilView( const Image& image, const RHI::ImageViewDescriptor& imageViewDescriptor, DescriptorHandle& depthStencilView, DescriptorHandle& depthStencilReadView); void CreateSampler( const RHI::SamplerState& samplerState, DescriptorHandle& samplerHandle); void ReleaseDescriptor(DescriptorHandle descriptorHandle); //! Creates a GPU-visible descriptor table. //! @param descriptorHeapType The descriptor heap to allocate from. //! @param descriptorCount The number of descriptors to allocate. //! @param srg Shader resource group with which the descriptor table is associated with DescriptorTable CreateDescriptorTable( D3D12_DESCRIPTOR_HEAP_TYPE descriptorHeapType, uint32_t descriptorCount, ShaderResourceGroup* srg); //! Releases a GPU-visible descriptor table. //! @param descriptorHeapType The descriptor heap to allocate from. //! @param srg Shader resource group with which the descriptor table is associated with void ReleaseDescriptorTable(DescriptorTable descriptorTable, ShaderResourceGroup* srg); //! Performs a gather of disjoint CPU-side descriptors and copies to a contiguous GPU-side descriptor table. //! @param gpuDestinationTable The destination descriptor table that the descriptors will be uploaded to. //! This must be the table specifically for a given range of descriptors, so if //! the user created a table with multiple ranges, they are required to partition //! that table and call this method multiple times with each range partition. //! //! @param cpuSourceDescriptors The CPU descriptors being gathered and copied to the destination table. //! The number of elements must match the size of the destination table. //! @param heapType The type of heap being updated. void UpdateDescriptorTableRange( DescriptorTable gpuDestinationTable, const DescriptorHandle* cpuSourceDescriptors, D3D12_DESCRIPTOR_HEAP_TYPE heapType); DescriptorHandle GetNullHandleSRV(D3D12_SRV_DIMENSION dimension) const; DescriptorHandle GetNullHandleUAV(D3D12_UAV_DIMENSION dimension) const; DescriptorHandle GetNullHandleCBV() const; DescriptorHandle GetNullHandleSampler() const; D3D12_CPU_DESCRIPTOR_HANDLE GetCpuPlatformHandle(DescriptorHandle handle) const; D3D12_GPU_DESCRIPTOR_HANDLE GetGpuPlatformHandle(DescriptorHandle handle) const; D3D12_CPU_DESCRIPTOR_HANDLE GetCpuPlatformHandleForTable(DescriptorTable descTable) const; D3D12_GPU_DESCRIPTOR_HANDLE GetGpuPlatformHandleForTable(DescriptorTable descTable) const; void SetDescriptorHeaps(ID3D12GraphicsCommandList* commandList) const; void GarbageCollect(); ID3D12DeviceX* GetDevice(); //! Since we are only allowed one shader visible CbvSrvUav heap of a limited size in certain hardware, it is possible that //! it can get fragmented by constant alloc/de-alloc of descriptor tables related to direct views or unbounded resource views within a SRG. We use two //! heaps to ping pong during compaction as fragmentation can occur many times. It copies static handles directly and for all the //! dynamic handles we re-update the new heap by copying over the handles from the 'non-shader visible' heap. RHI::ResultCode CompactDescriptorHeap(); private: void CopyDescriptor(DescriptorHandle dst, DescriptorHandle src); void CreateNullDescriptors(); void CreateNullDescriptorsSRV(); void CreateNullDescriptorsUAV(); void CreateNullDescriptorsCBV(); void CreateNullDescriptorsSampler(); DescriptorPool& GetPool(uint32_t type, uint32_t flag); const DescriptorPool& GetPool(uint32_t type, uint32_t flag) const; //! Allocates a Descriptor table which describes a contiguous range of descriptor handles DescriptorTable AllocateTable(D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flags, uint32_t count); //! Allocates a single descriptor handle DescriptorHandle AllocateHandle(D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flags, uint32_t count); bool IsShaderVisibleCbvSrvUavHeap(uint32_t type, uint32_t flag) const; static const uint32_t NumHeapFlags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE + 1; static const uint32_t s_descriptorCountMax[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES][NumHeapFlags]; RHI::Ptr<ID3D12DeviceX> m_device; DescriptorPool m_pools[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES][NumHeapFlags]; AZStd::unordered_map<D3D12_SRV_DIMENSION, DescriptorHandle> m_nullDescriptorsSRV; AZStd::unordered_map<D3D12_UAV_DIMENSION, DescriptorHandle> m_nullDescriptorsUAV; DescriptorHandle m_nullDescriptorCBV; DescriptorHandle m_nullSamplerDescriptor; RHI::ConstPtr<PlatformLimitsDescriptor> m_platformLimitsDescriptor; // Use 2 heaps below in order to ping-pong between shader visible CbvSrvUav heap when one of them fragments and run out of memory. static const uint32_t MaxShaderVisibleCbvSrvUavHeaps = 2; DescriptorPoolShaderVisibleCbvSrvUav m_shaderVisibleCbvSrvUavPools[MaxShaderVisibleCbvSrvUavHeaps]; //This pool stores a copy of static handles that can later be used to recreate the compacted shader visible CbvSrvUav heap. DescriptorPool m_backupStaticHandles; //Boolean to dictate when compaction was in progress bool m_compactionInProgress = false; //Boolean to dictate if we should support compaction for shader visible CbvSrvUav heap bool m_allowDescriptorHeapCompaction = false; //Map to store active SRGs and the number of associated descriptor tables. This is used to recreate the new compacted heap when we switch heaps AZStd::unordered_map<ShaderResourceGroup*, uint32_t> m_srgAllocations; AZStd::mutex m_srgMapMutex; //Index that holds the currently active shader visible CbvSrvUav heap uint32_t m_currentHeapIndex = 0; }; } }
48.700535
162
0.686175
[ "3d" ]
88d9582563ca9cfea5ae6557533c21ab145a4cda
6,883
h
C
core/src/dc1dmodelling.h
baender/gimli
eb9a2204669cf11209b9577472f61ac70217a191
[ "Apache-2.0" ]
1
2022-03-27T18:37:08.000Z
2022-03-27T18:37:08.000Z
core/src/dc1dmodelling.h
baender/gimli
eb9a2204669cf11209b9577472f61ac70217a191
[ "Apache-2.0" ]
null
null
null
core/src/dc1dmodelling.h
baender/gimli
eb9a2204669cf11209b9577472f61ac70217a191
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * Copyright (C) 2009-2020 by the GIMLi development team * * Thomas Günther thomas@resistivity.net * * Carsten Rücker carsten@resistivity.net * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * ******************************************************************************/ #ifndef _GIMLI_DC1DMODELLING__H #define _GIMLI_DC1DMODELLING__H #include "gimli.h" #include "mesh.h" #include "meshgenerators.h" #include "modellingbase.h" #include "vectortemplates.h" namespace GIMLI{ //! DC (direct current) 1D modelling /*! Classical DC 1D forward operator for given resistivities and thicknesses DC1dModelling(nlayers, ab2, mn2, verbose) DC1dModelling(nlayers, am, an, bm, bn, verbose) DC1dModelling(nlayers, dataContainer, verbose) */ class DLLEXPORT DC1dModelling : public ModellingBase { public: /*! General constructor using AM, AN, BM, BN, distances * (as stored internally). */ DC1dModelling(size_t nlayers, const RVector & am, const RVector & an, const RVector & bm, const RVector & bn, bool verbose=false); /*! constructor for classical Schlumberger sounding */ DC1dModelling(size_t nlayers, const RVector & ab2, const RVector & mn2, bool verbose=false); /*! constructor using a data container */ DC1dModelling(size_t nlayers, DataContainer & data, bool verbose=false); virtual ~DC1dModelling() { } /*! Returns an RVector of the 1dc response for * model = [thickness_ 0, ..., thickness_(n-1), rho_0 .. rho_n]. * For n = nlayers. */ RVector response(const RVector & model); RVector rhoa(const RVector & rho, const RVector & thk); RVector kern1d(const RVector & lam, const RVector & rho, const RVector & h); RVector pot1d(const RVector & R, const RVector & rho, const RVector & thk); inline RVector getK() { return k_; } inline RVector geometricFactor() { return k_; } template < class Vec > Vec rhoaT(const Vec & rho, const RVector & thk){ Vec tmp; tmp = pot1dT<Vec>(am_, rho, thk); tmp -= pot1dT<Vec>(an_, rho, thk); tmp -= pot1dT<Vec>(bm_, rho, thk); tmp += pot1dT<Vec>(bn_, rho, thk); return tmp * k_ + rho[ 0 ]; } template < class Vec > Vec kern1dT(const RVector & lam, const Vec & rho, const RVector & h){ size_t nr = rho.size(); size_t nl = lam.size(); Vec z(nl, rho[ nr - 1 ]); Vec p(nl); RVector th(nl); for (int i = nr - 2; i >= 0; i--) { p = (z - rho[ i ]) / (z + rho[ i ]); th = tanh(lam * h[ i ]); z = (z + toComplex(th) * rho[ i ]) / (z * th + rho[ i ]) * rho[ i ]; } Vec ehl(p * RVector(exp(-2.0 * lam * h[0]))); return ehl / (1.0 - ehl) * rho[0] / 2.0 / PI ; } template < class Vec > Vec pot1dT(const RVector & R, const Vec & rho, const RVector & thk){ Vec z0(R.size()); //double rabs; RVector rabs(abs(R)); for (size_t i = 0; i < R.size(); i++) { //rabs = std::fabs(R[ i ]); z0[ i ] = sum(myw_ * kern1dT<Vec>(myx_ / rabs[i], rho, thk) * 2.0) / rabs[i]; } return z0; } RVector createDefaultStartModel(); protected: /*! init myw and myx */ void init_(); void postprocess_(); size_t nlayers_; double meanrhoa_; RVector am_; RVector an_; RVector bm_; RVector bn_; RVector k_; RVector tmp_; RVector myx_; RVector myw_; }; /*! DC (direct current) 1D modelling for complex resistivity */ class DLLEXPORT DC1dModellingC : public DC1dModelling { public: /*! General constructor using AM, AN, BM, BN, distances * (as stored internally). */ DC1dModellingC(size_t nlayers, const RVector & am, const RVector & an, const RVector & bm, const RVector & bn, bool verbose=false); /*! Constructor for classical Schlumberger sounding */ DC1dModellingC(size_t nlayers, const RVector & ab2, const RVector & mn2, bool verbose=false); virtual ~DC1dModellingC() { } /*! Return [|rhoa|, +phi(rad)] for [thicks, res, phi(rad)]*/ RVector response(const RVector & model); }; /*! DC1dRhoModelling - Variant of DC 1D modelling with fixed parameterization * (occam inversion) */ /*! DC1dRhoModelling(mesh, dataContainer, thicknesses, verbose) */ class DLLEXPORT DC1dRhoModelling : public DC1dModelling { public: DC1dRhoModelling(const RVector & thk, const RVector & am, const RVector & an, const RVector & bm, const RVector & bn, bool verbose=false) : DC1dModelling(thk.size(), am, an, bm, bn, verbose), thk_(thk) { setMesh(createMesh1D(thk.size() + 1, 1)); } DC1dRhoModelling(const RVector & thk, const RVector & ab2, const RVector & mn2, bool verbose = false) : DC1dModelling(thk.size(), ab2, mn2, verbose), thk_(thk) { setMesh(createMesh1D(thk.size() + 1, 1)); } DC1dRhoModelling(const RVector & thk, DataContainer & data, bool verbose=false) : DC1dModelling(thk.size(), data, verbose), thk_(thk) { setMesh(createMesh1D(thk.size() + 1, 1)); } virtual ~DC1dRhoModelling() { } RVector response(const RVector & rho) { return rhoa(rho, thk_); } RVector createDefaultStartModel() { return RVector(thk_.size() + 1, meanrhoa_); } protected: RVector thk_; }; } // namespace GIMLI{ #endif // _GIMLI_DC1DMODELLING__H
37.205405
80
0.535668
[ "mesh", "model" ]
88dacc8587a3f082992a0060cd8993f339e825cc
5,182
h
C
Pods/Headers/Public/RZImport/RZImportable.h
adamhrz/party-playlist
daadf6f04ac6411d21f17d590267af1e388aab18
[ "MIT" ]
null
null
null
Pods/Headers/Public/RZImport/RZImportable.h
adamhrz/party-playlist
daadf6f04ac6411d21f17d590267af1e388aab18
[ "MIT" ]
null
null
null
Pods/Headers/Public/RZImport/RZImportable.h
adamhrz/party-playlist
daadf6f04ac6411d21f17d590267af1e388aab18
[ "MIT" ]
null
null
null
// // RZImportable.h // RZImport // // Created by Nick Donaldson on 5/21/14. // // Copyright 2014 Raizlabs and other contributors // http://raizlabs.com/ // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @import Foundation; #import "RZCompatibility.h" /** * Optional protocol for model objects to import in order to customize * the behavior of RZImport. */ @protocol RZImportable <NSObject> @optional /** * Implement this method to completely override the property names used for importing instances of this class. * By default, RZImport uses ObjC runtime to determine property names, however the usage of this override * may be handy in situations where that approach does not work (e.g. Swift + NSManagedObject). * * @return The property names to be used for importing. */ + (RZNonnull RZIStringArray *)rzi_propertyNames; /** * Implement to provide dictionary of custom mappings from dictionary keys/keypaths to properties. * * @note Keypaths are supported in custom mappings for access to values within nested dictionaries. * * @return A dictionary containing mappings from dictionary keys/keypaths to property names. */ + (RZNonnull RZIKeyMap *)rzi_customMappings; /** * Implement to ignore a specific set of keys or keypaths. * When performing an import, these keys will be ignored in the dictionary being imported. * * @note To ignore all keypaths in a nested dictionary, return its root key here. * * @return An array of NSString objects representing keys to ignore during import. */ + (RZNonnull RZIStringArray *)rzi_ignoredKeys; /** * Implement to provide a list of keys in dictionaries being imported whose values should be imported as nested objects. * These keys should represent nested dictionaries in the dictionary being imported and should have valid mappings to * properties on this class which are other importable model objects. * * @return An array of NSString objects representing keys whose values should be imported as other model objects. */ + (RZNonnull RZIStringArray *)rzi_nestedObjectKeys; /** * Implement to provide the order in which keys should be imported. * When performing an import, keys in this array will be imported first, and in the order specified. * Keys not including in this array will be imported in an arbitrary order. * * @return An array of NSString objects representing keys in the order in which they should be imported. */ + (RZNonnull RZIStringArray *)rzi_orderedKeys; /** * Implement to provide a custom date format string for a particular key or keys. * Will only be called if the inferred property is an NSDate type and the dict value is a string. * * @param key Unmodified key from the dictionary being imported. * * @return A date format to use for importing this key, otherwise nil to use the default (ISO-8601). */ + (RZNonnull NSString *)rzi_dateFormatForKey:(RZNonnull NSString *)key; /** * Implement to return an existing object for the provided dictionary representation. * Use this method to enforce object uniqueness. * * @param dict Dictionary representation of object being imported. * * @return An existing object instance represented by the dict, or nil if one does not exist. */ + (RZNonnull instancetype)rzi_existingObjectForDict:(RZNonnull NSDictionary *)dict; /** * Implement to optionally prevent import for particular key/value pairs. * Can be used to validate imported value or override automatic import to perform custom logic. * In order to support custom import logic for certain attributes, his is called by @p RZImport * prior to mapping the dictionary key to a property name, so the key here may not match a property * name in this class. * * @param value Unmodified value from dictionary being imported * @param key Unmodified key from dictionary being imported * * @return YES if RZImport should proceed with automatic import for the key/value pair * NO if the key/value pair should not be imported or will be handled within this method. */ - (BOOL)rzi_shouldImportValue:(RZNonnull id)value forKey:(RZNonnull NSString *)key; @end
42.47541
121
0.754535
[ "object", "model" ]
88dfde3d291334153e2c11c2f5b46e5418e5c5eb
2,046
h
C
Overlays/Posix/Libraries/WNMultiTasking/inc/internal/shared_mutex_base.h
WNProject/WNFramework
293d2b550ed8745654cc0a1da391588ed6abb96b
[ "BSD-2-Clause" ]
6
2015-05-04T17:39:37.000Z
2022-03-04T02:30:28.000Z
Overlays/Posix/Libraries/WNMultiTasking/inc/internal/shared_mutex_base.h
WNProject/WNFramework
293d2b550ed8745654cc0a1da391588ed6abb96b
[ "BSD-2-Clause" ]
276
2015-05-27T21:30:31.000Z
2022-03-24T01:52:36.000Z
Overlays/Posix/Libraries/WNMultiTasking/inc/internal/shared_mutex_base.h
WNProject/WNFramework
293d2b550ed8745654cc0a1da391588ed6abb96b
[ "BSD-2-Clause" ]
2
2017-11-30T19:06:08.000Z
2020-09-30T23:56:48.000Z
// Copyright (c) 2021, WNProject Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #pragma once #ifndef __WN_MULTI_TASKING_POSIX_INTERNAL_SHARED_MUTEX_BASE_H__ #define __WN_MULTI_TASKING_POSIX_INTERNAL_SHARED_MUTEX_BASE_H__ #include "core/inc/assert.h" #include "core/inc/utilities.h" #include <pthread.h> namespace wn { namespace multi_tasking { namespace internal { class shared_mutex_base : core::non_copyable { protected: shared_mutex_base() { const int result = ::pthread_rwlock_init(&m_read_write_lock, NULL); WN_RELEASE_ASSERT(result == 0, "failed to create read write lock object"); } ~shared_mutex_base() { const int result = ::pthread_rwlock_destroy(&m_read_write_lock); WN_DEBUG_ASSERT(result == 0, "failed to destroy read write lock object"); (void)result; } void lock() { const int result = ::pthread_rwlock_wrlock(&m_read_write_lock); WN_RELEASE_ASSERT( result == 0, "failed to lock read write lock object for writer"); } bool try_lock() { return (::pthread_rwlock_trywrlock(&m_read_write_lock) == 0); } void unlock() { const int result = ::pthread_rwlock_unlock(&m_read_write_lock); WN_RELEASE_ASSERT( result == 0, "failed to unlock read write lock object for writer"); } void lock_shared() { const int result = ::pthread_rwlock_rdlock(&m_read_write_lock); WN_RELEASE_ASSERT( result == 0, "failed to lock read write lock object for reader"); } bool try_lock_shared() { return (::pthread_rwlock_tryrdlock(&m_read_write_lock) == 0); } void unlock_shared() { const int result = ::pthread_rwlock_unlock(&m_read_write_lock); WN_RELEASE_ASSERT( result == 0, "failed to unlock read write lock object for reader"); } private: pthread_rwlock_t m_read_write_lock; }; } // namespace internal } // namespace multi_tasking } // namespace wn #endif // __WN_MULTI_TASKING_POSIX_INTERNAL_SHARED_MUTEX_BASE_H__
25.575
78
0.719453
[ "object" ]
88e8e0d9e71e096ac29fb1cc852a7bc570313f72
1,985
h
C
DQM/EcalMonitorTasks/interface/EcalDQMonitorTask.h
SWuchterl/cmssw
769b4a7ef81796579af7d626da6039dfa0347b8e
[ "Apache-2.0" ]
6
2017-09-08T14:12:56.000Z
2022-03-09T23:57:01.000Z
DQM/EcalMonitorTasks/interface/EcalDQMonitorTask.h
SWuchterl/cmssw
769b4a7ef81796579af7d626da6039dfa0347b8e
[ "Apache-2.0" ]
545
2017-09-19T17:10:19.000Z
2022-03-07T16:55:27.000Z
DQM/EcalMonitorTasks/interface/EcalDQMonitorTask.h
SWuchterl/cmssw
769b4a7ef81796579af7d626da6039dfa0347b8e
[ "Apache-2.0" ]
14
2017-10-04T09:47:21.000Z
2019-10-23T18:04:45.000Z
#ifndef EcalDQMonitorTask_H #define EcalDQMonitorTask_H #include "DQM/EcalCommon/interface/EcalDQMonitor.h" #include "DQMServices/Core/interface/DQMOneEDAnalyzer.h" #include "DQWorkerTask.h" #include "Collections.h" #include <set> #include <map> namespace edm { class InputTag; class ParameterSetDescription; } // namespace edm class EcalDQMonitorTask : public DQMOneLumiEDAnalyzer<>, public ecaldqm::EcalDQMonitor { public: EcalDQMonitorTask(edm::ParameterSet const&); ~EcalDQMonitorTask() override {} static void fillDescriptions(edm::ConfigurationDescriptions&); void bookHistograms(DQMStore::IBooker&, edm::Run const&, edm::EventSetup const&) override; void dqmBeginRun(edm::Run const&, edm::EventSetup const&) override; private: void dqmEndRun(edm::Run const&, edm::EventSetup const&) override; void dqmBeginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; void dqmEndLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; void analyze(edm::Event const&, edm::EventSetup const&) override; typedef void (EcalDQMonitorTask::*Processor)(edm::Event const&, ecaldqm::Collections, std::set<ecaldqm::DQWorker*> const&); template <typename CollectionClass> void runOnCollection(edm::Event const&, ecaldqm::Collections, std::set<ecaldqm::DQWorker*> const&); void formSchedule(std::vector<ecaldqm::Collections> const&, edm::ParameterSet const&); /* DATA MEMBERS */ edm::EDGetToken collectionTokens_[ecaldqm::nCollections]; // list of EDGetTokens std::vector<std::pair<Processor, ecaldqm::Collections> > schedule_; // schedule of collections to run bool allowMissingCollections_; // when true, skip missing collections silently int processedEvents_; /* TASK TIME PROFILING */ time_t lastResetTime_; float resetInterval_; }; #endif
35.446429
118
0.710327
[ "vector" ]
88f46793be9c727602e35525e2e2e997aae689b8
1,343
h
C
include/smtp.h
JamesBremner/mailc
c167afc95fba9289ab6ed9fe3d4ec3298cecc170
[ "MIT" ]
5
2018-06-10T12:10:41.000Z
2022-02-11T18:25:05.000Z
include/smtp.h
JamesBremner/mailc
c167afc95fba9289ab6ed9fe3d4ec3298cecc170
[ "MIT" ]
null
null
null
include/smtp.h
JamesBremner/mailc
c167afc95fba9289ab6ed9fe3d4ec3298cecc170
[ "MIT" ]
3
2020-07-23T09:09:58.000Z
2022-02-11T18:25:22.000Z
/** * @file */ #ifndef SMTP_H #define SMTP_H #include <iostream> #include "socket.h" /** * @brief SMTPConnection class * @details Stores socket which connect to SMTP server, has methos * which implemnet the SMTP commands * */ class SMTPConnection { public: /** * @brief Create an SMPTP Connection * @details Create socket, intilize ssl and create socket object * * @param hostname The hostname of the SMTP server * @param port The port of the SMTP server */ SMTPConnection(const std::string &hostname, int port); /** * @brief Login in the server * @details Login in the server with given config * * @param username The username of the user * @param password The password of the user * * @return Whether the login was successful */ bool auth(const std::string &username, const std::string &password); /** * @brief Send a mail * @details Send a mail using SMTP Protocol * * @param from From address * @param to To address * @param subject Subject of the mail * @param body Body of the mail * @return True if the mail is successfully sent */ bool send(const std::string &from, const std::string &to, const std::string &subject, const std::string &body); private: Socket socket; std::string username; std::string password; }; #endif
23.155172
70
0.669397
[ "object" ]
88f7d5e38884ef8f7911f284177b1aea5a76d780
2,646
h
C
src/include/TempLat/lattice/memory/memorylayouts/layoutstruct_test.h
cosmolattice/cosmolattice
bd9a31a026c0b47d53ff486db23448797dbe2fe0
[ "MIT" ]
12
2021-02-01T16:04:54.000Z
2022-03-18T08:27:46.000Z
src/include/TempLat/lattice/memory/memorylayouts/layoutstruct_test.h
cosmolattice/cosmolattice
bd9a31a026c0b47d53ff486db23448797dbe2fe0
[ "MIT" ]
1
2021-04-24T10:09:35.000Z
2021-04-24T10:09:35.000Z
src/include/TempLat/lattice/memory/memorylayouts/layoutstruct_test.h
cosmolattice/cosmolattice
bd9a31a026c0b47d53ff486db23448797dbe2fe0
[ "MIT" ]
2
2021-08-11T07:35:25.000Z
2022-03-07T21:33:30.000Z
#ifndef TEMPLAT_FFT_MEMORYLAYOUTS_LAYOUTSTRUCT_TEST_H #define TEMPLAT_FFT_MEMORYLAYOUTS_LAYOUTSTRUCT_TEST_H /* This file is part of CosmoLattice, available at www.cosmolattice.net . Copyright Daniel G. Figueroa, Adrien Florio, Francisco Torrenti and Wessel Valkenburg. Released under the MIT license, see LICENSE.md. */ // File info: Main contributor(s): Wessel Valkenburg, Year: 2019 inline void TempLat::LayoutStruct::Test(TempLat::TDDAssertion& tdd) { /* test the operator== */ LayoutStruct a({0,0,0}); LayoutStruct b({0,0,0}); LayoutStruct c({0,0}); LayoutStruct d({0,0,0}); d.getLocalSizes()[1] = 2; tdd.verify( ! (a == c) ); tdd.verify( (a == b) ); tdd.verify( ! (a == d) ); /* test the transposition */ a = LayoutStruct({16,16,16}); std::vector<ptrdiff_t> newLocalSizes {{ 4, 5, 6 }}; a.setLocalSizes(newLocalSizes); /* test that these propagate correctly */ tdd.verify( a.getLocalSizes()[0] == a.getSizesInMemory()[0]); tdd.verify( a.getLocalSizes()[1] == a.getSizesInMemory()[1]); tdd.verify( a.getLocalSizes()[2] == a.getSizesInMemory()[2]); std::vector<ptrdiff_t> newLocalStarts {{ 7, 8, 9 }}; a.setLocalStarts(newLocalStarts); a.setTranspositionMap_memoryToGlobalSpace({{2, 0, 1}}); std::vector<ptrdiff_t> memVec(3), posVec(3), memVec2(3); memVec[0] = 1; memVec[1] = 2; memVec[2] = 3; a.putSpatialLocationFromMemoryIndexInto(memVec[0], 0, posVec); a.putSpatialLocationFromMemoryIndexInto(memVec[1], 1, posVec); a.putSpatialLocationFromMemoryIndexInto(memVec[2], 2, posVec); say << "memVec " << memVec << " -> posVec " << posVec << "\n"; /* mem pos 2 at mem dim 1 -> global dim 0 -> global pos 2 + 7 = 9 -> 9 - 16 = -7 */ tdd.verify(posVec[0] == -7); /* mem pos 3 at mem dim 2 -> global dim 1 -> global pos 3 + 8 = 11 -> 11 - 16 = -5 */ tdd.verify(posVec[1] == -5); /* mem pos 1 at mem dim 0 -> global dim 2 -> global pos 1 + 9 = 10 -> 10 - 16 = -6 */ tdd.verify(posVec[2] == -6); a.putMemoryIndexFromSpatialLocationInto(posVec[0], 0, memVec2); a.putMemoryIndexFromSpatialLocationInto(posVec[1], 1, memVec2); a.putMemoryIndexFromSpatialLocationInto(posVec[2], 2, memVec2); say << "posVec " << posVec << " -> memVec2 " << memVec2 << "\n"; say << "memVec " << memVec << " -> memVec2 " << memVec2 << "\n"; say << " from layout:\n" << a << "\n"; tdd.verify(memVec[0] == memVec2[0]); tdd.verify(memVec[1] == memVec2[1]); tdd.verify(memVec[2] == memVec2[2]); say << "layout: " << a << "\n"; } #endif
33.493671
89
0.610355
[ "vector" ]
f0316d8d2639bbdaeff385317cf7cb4d353fe1da
2,980
h
C
src/prod/src/Common/SecurityDescriptor.h
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Common/SecurityDescriptor.h
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Common/SecurityDescriptor.h
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Common { class SecurityDescriptor; typedef std::shared_ptr<SecurityDescriptor> SecurityDescriptorSPtr; // SecurityDescriptor is used to set DACL on folder and processes class SecurityDescriptor { DENY_COPY(SecurityDescriptor) protected: SecurityDescriptor(const PSECURITY_DESCRIPTOR pSecurityDescriptor); public: virtual ~SecurityDescriptor(); __declspec(property(get=get_PSECURITY_DESCRIPTOR)) PSECURITY_DESCRIPTOR PSecurityDescriptor; PSECURITY_DESCRIPTOR get_PSECURITY_DESCRIPTOR() const { return pSecurityDescriptor_; } __declspec(property(get=get_Length)) ULONG Length; ULONG get_Length() const; bool IsEquals(const PSECURITY_DESCRIPTOR pDescriptor) const; static bool IsValid(PSECURITY_DESCRIPTOR pSecurityDescriptor); void WriteTo(Common::TextWriter&, Common::FormatOptions const &) const; private: PSECURITY_DESCRIPTOR const pSecurityDescriptor_; }; class BufferedSecurityDescriptor : public SecurityDescriptor { DENY_COPY(BufferedSecurityDescriptor) public: BufferedSecurityDescriptor(Common::ByteBuffer && buffer); virtual ~BufferedSecurityDescriptor(); static Common::ErrorCode CreateSPtr(__out SecurityDescriptorSPtr & sd); static Common::ErrorCode CreateSPtrFromKernelObject(HANDLE object, __out SecurityDescriptorSPtr & sd); static Common::ErrorCode CreateSPtr(std::wstring const & accountName, __out SecurityDescriptorSPtr & sd); static Common::ErrorCode CreateSPtr(PSECURITY_DESCRIPTOR const pSecurityDescriptor, __out SecurityDescriptorSPtr & sd); // Create self-relative security descriptor from owner token and allowed SIDs. // The DACL will contain allowed ACE for the owner SID and each SID in allowedSIDs. static Common::ErrorCode CreateAllowed( HANDLE ownerToken, bool allowOwner, std::vector<Common::SidSPtr> const & allowedSIDs, DWORD accessMask, _Out_ SecurityDescriptorSPtr & sd); static Common::ErrorCode CreateAllowed( std::vector<Common::SidSPtr> const & allowedSIDs, DWORD accessMask, _Out_ SecurityDescriptorSPtr & sd); static Common::ErrorCode ConvertSecurityDescriptorStringToSecurityDescriptor( std::wstring const & stringSecurityDescriptor, __out SecurityDescriptorSPtr & sd); static PSECURITY_DESCRIPTOR GetPSECURITY_DESCRIPTOR(Common::ByteBuffer const & buffer); private: Common::ByteBuffer const buffer_; }; }
39.210526
127
0.681544
[ "object", "vector" ]
f037a1224c1d1635d20e0b7dacd23644909dc23f
2,611
h
C
Source/ObjectiveDropboxOfficial/Shared/Generated/ApiObjects/TeamLog/Headers/DBTEAMLOGExternalDriveBackupPolicyChangedDetails.h
zhaoze1991/dropbox-sdk-obj-c
fde24d2f1efd76a8859d4b65d388c6eeccd37fe0
[ "MIT" ]
199
2016-08-24T01:48:43.000Z
2022-03-26T12:43:12.000Z
Source/ObjectiveDropboxOfficial/Shared/Generated/ApiObjects/TeamLog/Headers/DBTEAMLOGExternalDriveBackupPolicyChangedDetails.h
zhaoze1991/dropbox-sdk-obj-c
fde24d2f1efd76a8859d4b65d388c6eeccd37fe0
[ "MIT" ]
263
2016-08-28T16:56:00.000Z
2022-03-26T09:24:40.000Z
Source/ObjectiveDropboxOfficial/Shared/Generated/ApiObjects/TeamLog/Headers/DBTEAMLOGExternalDriveBackupPolicyChangedDetails.h
zhaoze1991/dropbox-sdk-obj-c
fde24d2f1efd76a8859d4b65d388c6eeccd37fe0
[ "MIT" ]
125
2016-08-31T17:49:54.000Z
2022-03-22T02:38:37.000Z
/// /// Copyright (c) 2016 Dropbox, Inc. All rights reserved. /// /// Auto-generated by Stone, do not modify. /// #import <Foundation/Foundation.h> #import "DBSerializableProtocol.h" @class DBTEAMLOGExternalDriveBackupPolicy; @class DBTEAMLOGExternalDriveBackupPolicyChangedDetails; NS_ASSUME_NONNULL_BEGIN #pragma mark - API Object /// /// The `ExternalDriveBackupPolicyChangedDetails` struct. /// /// Changed external drive backup policy for team. /// /// This class implements the `DBSerializable` protocol (serialize and /// deserialize instance methods), which is required for all Obj-C SDK API route /// objects. /// @interface DBTEAMLOGExternalDriveBackupPolicyChangedDetails : NSObject <DBSerializable, NSCopying> #pragma mark - Instance fields /// New external drive backup policy. @property (nonatomic, readonly) DBTEAMLOGExternalDriveBackupPolicy *dNewValue; /// Previous external drive backup policy. @property (nonatomic, readonly) DBTEAMLOGExternalDriveBackupPolicy *previousValue; #pragma mark - Constructors /// /// Full constructor for the struct (exposes all instance variables). /// /// @param dNewValue New external drive backup policy. /// @param previousValue Previous external drive backup policy. /// /// @return An initialized instance. /// - (instancetype)initWithDNewValue:(DBTEAMLOGExternalDriveBackupPolicy *)dNewValue previousValue:(DBTEAMLOGExternalDriveBackupPolicy *)previousValue; - (instancetype)init NS_UNAVAILABLE; @end #pragma mark - Serializer Object /// /// The serialization class for the `ExternalDriveBackupPolicyChangedDetails` /// struct. /// @interface DBTEAMLOGExternalDriveBackupPolicyChangedDetailsSerializer : NSObject /// /// Serializes `DBTEAMLOGExternalDriveBackupPolicyChangedDetails` instances. /// /// @param instance An instance of the /// `DBTEAMLOGExternalDriveBackupPolicyChangedDetails` API object. /// /// @return A json-compatible dictionary representation of the /// `DBTEAMLOGExternalDriveBackupPolicyChangedDetails` API object. /// + (nullable NSDictionary<NSString *, id> *)serialize:(DBTEAMLOGExternalDriveBackupPolicyChangedDetails *)instance; /// /// Deserializes `DBTEAMLOGExternalDriveBackupPolicyChangedDetails` instances. /// /// @param dict A json-compatible dictionary representation of the /// `DBTEAMLOGExternalDriveBackupPolicyChangedDetails` API object. /// /// @return An instantiation of the /// `DBTEAMLOGExternalDriveBackupPolicyChangedDetails` object. /// + (DBTEAMLOGExternalDriveBackupPolicyChangedDetails *)deserialize:(NSDictionary<NSString *, id> *)dict; @end NS_ASSUME_NONNULL_END
30.011494
114
0.782459
[ "object" ]
f04dcb7841c183e068a1f36bd2ab015fbdd24a8c
2,600
h
C
src/rx/display.h
DethRaid/rex
21ba92d38398240faa45a402583c11f8c72e6e41
[ "MIT" ]
2
2020-06-13T11:39:46.000Z
2021-03-10T01:03:03.000Z
src/rx/display.h
DethRaid/rex
21ba92d38398240faa45a402583c11f8c72e6e41
[ "MIT" ]
null
null
null
src/rx/display.h
DethRaid/rex
21ba92d38398240faa45a402583c11f8c72e6e41
[ "MIT" ]
1
2021-01-06T03:47:08.000Z
2021-01-06T03:47:08.000Z
#ifndef RX_DISPLAY_H #define RX_DISPLAY_H #include "rx/core/vector.h" #include "rx/core/string.h" #include "rx/math/vec2.h" #include "rx/math/rectangle.h" namespace Rx { struct Display { RX_MARK_NO_COPY(Display); Display(Memory::Allocator& _allocator); Display(Display&& display_); struct Mode { Math::Vec2z resolution; Float32 refresh_rate; }; using Extents = Math::Rectangle<Sint32>; static Vector<Display> displays(Memory::Allocator& _allocator); // The display modes are sorted by the given priority: // mode::resolution.w => largest to smallest // mode::resolution.h => largest to smallest // mode::refresh_rate => highest to lowest const Vector<Mode>& modes() const &; const String& name() const &; const Extents& bounds() const &; Float32 diagonal_dpi() const; Float32 horizontal_dpi() const; Float32 vertical_dpi() const; // Check if the given extents are inside the display. bool contains(const Extents& _extents) const; constexpr Memory::Allocator& allocator() const; private: Memory::Allocator* m_allocator; Vector<Mode> m_modes; String m_name; Extents m_bounds; Float32 m_diagonal_dpi; Float32 m_horizontal_dpi; Float32 m_vertical_dpi; }; inline Display::Display(Memory::Allocator& _allocator) : m_allocator{&_allocator} , m_modes{allocator()} , m_name{allocator()} , m_diagonal_dpi{0.0f} , m_horizontal_dpi{0.0f} , m_vertical_dpi{0.0f} { } inline Display::Display(Display&& display_) : m_allocator{display_.m_allocator} , m_modes{Utility::move(display_.m_modes)} , m_name{Utility::move(display_.m_name)} , m_bounds{display_.m_bounds} , m_diagonal_dpi{Utility::exchange(display_.m_diagonal_dpi, 0.0f)} , m_horizontal_dpi{Utility::exchange(display_.m_horizontal_dpi, 0.0f)} , m_vertical_dpi{Utility::exchange(display_.m_vertical_dpi, 0.0f)} { display_.m_bounds = {}; } inline const Vector<Display::Mode>& Display::modes() const & { return m_modes; } inline const String& Display::name() const & { return m_name; } inline const Display::Extents& Display::bounds() const & { return m_bounds; } inline Float32 Display::diagonal_dpi() const { return m_diagonal_dpi; } inline Float32 Display::horizontal_dpi() const { return m_horizontal_dpi; } inline Float32 Display::vertical_dpi() const { return m_vertical_dpi; } inline bool Display::contains(const Extents& _extents) const { return m_bounds.contains(_extents); } RX_HINT_FORCE_INLINE constexpr Memory::Allocator& Display::allocator() const { return *m_allocator; } } // namespace rx #endif // RX_DISPLAY_H
23.636364
78
0.728846
[ "vector" ]
f050d18ae3fbb08f981bb05f466323853dbd724c
874
h
C
c/Haxe/OpenFL/01.HelloWorld/Export/windows/cpp/obj/include/IMap.h
amenoyoya/old-project
640ec696af5d18267d86629098f41451857f8103
[ "MIT" ]
null
null
null
c/Haxe/OpenFL/01.HelloWorld/Export/windows/cpp/obj/include/IMap.h
amenoyoya/old-project
640ec696af5d18267d86629098f41451857f8103
[ "MIT" ]
1
2019-07-07T09:52:20.000Z
2019-07-07T09:52:20.000Z
c/Haxe/OpenFL/01.HelloWorld/Export/windows/cpp/obj/include/IMap.h
amenoyoya/old-project
640ec696af5d18267d86629098f41451857f8103
[ "MIT" ]
null
null
null
#ifndef INCLUDED_IMap #define INCLUDED_IMap #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS0(IMap) class HXCPP_CLASS_ATTRIBUTES IMap_obj : public hx::Interface{ public: typedef hx::Interface super; typedef IMap_obj OBJ_; HX_DO_INTERFACE_RTTI; static void __boot(); virtual Dynamic get( Dynamic k)=0; Dynamic get_dyn(); }; #define DELEGATE_IMap \ virtual Dynamic get( Dynamic k) { return mDelegate->get(k);} \ virtual Dynamic get_dyn() { return mDelegate->get_dyn();} \ template<typename IMPL> class IMap_delegate_ : public IMap_obj { protected: IMPL *mDelegate; public: IMap_delegate_(IMPL *inDelegate) : mDelegate(inDelegate) {} hx::Object *__GetRealObject() { return mDelegate; } void __Visit(HX_VISIT_PARAMS) { HX_VISIT_OBJECT(mDelegate); } DELEGATE_IMap }; #endif /* INCLUDED_IMap */
21.85
64
0.708238
[ "object" ]
f05b8493c4e0eb7223ab5aa7150d896d5041a3ee
886
h
C
TowerDefence/Game/Enemy.h
CameronD17/Tower-Defence
8dbfb66d01f2af9184e6cea0dc28c3969d060320
[ "Apache-2.0" ]
null
null
null
TowerDefence/Game/Enemy.h
CameronD17/Tower-Defence
8dbfb66d01f2af9184e6cea0dc28c3969d060320
[ "Apache-2.0" ]
null
null
null
TowerDefence/Game/Enemy.h
CameronD17/Tower-Defence
8dbfb66d01f2af9184e6cea0dc28c3969d060320
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../Engine/Constants.h" #include "../Engine/Engine.h" #include "../Engine/Object.h" #include "../Engine/Pathfinder.h" #include "Bank.h" #include "Map.h" struct eStats { int id, targetX, targetY, value, bounty, speed, type; float currentHealth, maxHealth; bool isBoss, canSwim; std::string category; }; class Enemy : public Object { private: Engine engine; Pathfinder astar; eStats stats; int stepsTaken, stepsPerSquare; void initialise(int level, int x, int y, int tX, int tY, int type, Map &m); void releaseTiles(Map &m); void lockTiles(Map &m); public: Enemy(); Enemy(Engine &e, int x, int y, int type, int targetX, int targetY, int level, Map &m, int i); ~Enemy(); void draw(); void updateTarget(int tX, int t, Map &m); void updatePath(Map &m, int x = -1, int y = -1); bool reduceHealth(int h, Map &m, Bank &b); void move(Map &m); };
21.609756
94
0.676072
[ "object" ]
f05d28d441d69271d4597a31a04b5e929722b5cb
6,688
h
C
contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/IOKit.framework/Versions/A/Headers/network/IONetworkInterface.h
Amity-Network/amity
3e57379f01af4ca851079c8e469fbda7c8165b47
[ "MIT" ]
28
2019-06-20T13:05:19.000Z
2022-03-28T03:56:22.000Z
contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/IOKit.framework/Versions/A/Headers/network/IONetworkInterface.h
Amity-Network/amity
3e57379f01af4ca851079c8e469fbda7c8165b47
[ "MIT" ]
1
2019-11-17T18:51:10.000Z
2019-11-28T12:53:24.000Z
contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/IOKit.framework/Versions/A/Headers/network/IONetworkInterface.h
Amity-Network/amity
3e57379f01af4ca851079c8e469fbda7c8165b47
[ "MIT" ]
7
2019-06-06T13:05:22.000Z
2020-12-07T12:33:08.000Z
/* * Copyright (c) 1998-2008 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IONETWORKINTERFACE_H #define _IONETWORKINTERFACE_H /*! @defined kIONetworkInterfaceClass @abstract The name of the IONetworkInterface class. */ #define kIONetworkInterfaceClass "IONetworkInterface" /*! @defined kIONetworkData @abstract A property of IONetworkInterface objects. @discussion The kIONetworkData property has an OSDictionary value and is a container for the set of IONetworkData objects managed by the interface. Each entry in the dictionary is a key/value pair consisting of the network data name, and an OSDictionary describing the contents of the network data. */ #define kIONetworkData "IONetworkData" /*! @defined kIOInterfaceType @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceType property has an OSNumber value that specifies the type of network interface that this interface represents. The type constants are defined in bsd/net/if_types.h. */ #define kIOInterfaceType "IOInterfaceType" /*! @defined kIOMaxTransferUnit @abstract A property of IONetworkInterface objects. @discussion The kIOMaxTransferUnit property has an OSNumber value that specifies the maximum transfer unit for the interface in bytes. */ #define kIOMaxTransferUnit "IOMaxTransferUnit" /*! @defined kIOMediaAddressLength @abstract A property of IONetworkInterface objects. @discussion The kIOMediaAddressLength property has an OSNumber value that specifies the size of the media address in bytes. */ #define kIOMediaAddressLength "IOMediaAddressLength" /*! @defined kIOMediaHeaderLength @abstract A property of IONetworkInterface objects. @discussion The kIOMediaHeaderLength property has an OSNumber value that specifies the size of the media header in bytes. */ #define kIOMediaHeaderLength "IOMediaHeaderLength" /*! @defined kIOInterfaceFlags @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceFlags property has an OSNumber value that specifies the current value of the interface flags. The flag constants are defined in bsd/net/if.h. */ #define kIOInterfaceFlags "IOInterfaceFlags" /*! @defined kIOInterfaceExtraFlags @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceExtraFlags property has an OSNumber value that specifies the current value of the interface eflags. The eflag constants are defined in bsd/net/if.h. */ #define kIOInterfaceExtraFlags "IOInterfaceExtraFlags" /*! @defined kIOInterfaceUnit @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceUnit property has an OSNumber value that describes the unit number assigned to the interface object. */ #define kIOInterfaceUnit "IOInterfaceUnit" /*! @defined kIOInterfaceState @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceState property has an OSNumber value that describes the current state of the interface object. This property is not exported to BSD via the ifnet structure. */ #define kIOInterfaceState "IOInterfaceState" /*! @defined kIOInterfaceNamePrefix @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceNamePrefix property has an OSString value that describes the string prefix for the BSD name assigned to the interface. */ #define kIOInterfaceNamePrefix "IOInterfaceNamePrefix" /*! @defined kIOPrimaryInterface @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceNamePrefix property has an OSBoolean value that describes whether the interface is the primary or the built-in network interface. */ #define kIOPrimaryInterface "IOPrimaryInterface" /*! @defined kIOBuiltin @abstract kIOBuiltin is a property of IONetworkInterface objects. It has an OSBoolean value. @discussion The kIOBuiltin property describes whether the interface is built-in. */ #define kIOBuiltin "IOBuiltin" /*! @defined kIOLocation @abstract kIOLocation is a property of IONetworkInterface objects. It has an OSString value. @discussion The kIOLocation property describes the physical location of built-in interfaces. */ #define kIOLocation "IOLocation" /*! @defined kIONetworkNoBSDAttachKey @abstract kIONetworkNoBSDAttachKey is a property of IONetworkInterface objects. It has an OSBoolean value. @discussion Adding a property with this key and the value kOSBooleanTrue before the interface is published will hold off the BSD attach. When the interface is ready to attach to BSD, remove the property and then re-publish the interface by calling registerService(). */ #define kIONetworkNoBSDAttachKey "IONetworkNoBSDAttach" /*! @enum InterfaceObjectStates @discussion Constants used to encode the state of the interface object. @constant kIONetworkInterfaceRegisteredState The interface object has registered with the data link layer. @constant kIONetworkInterfaceOpenedState One or more clients have an open on the interface object. @constant kIONetworkInterfaceDisabledState The interface is temporarily unable to service its clients. This will occur when the network controller that is servicing the interface has entered a low power state that renders it unusable. */ enum { kIONetworkInterfaceRegisteredState = 0x1, kIONetworkInterfaceOpenedState = 0x2, kIONetworkInterfaceDisabledState = 0x4 }; #endif /* !_IONETWORKINTERFACE_H */
38
80
0.749103
[ "object" ]
f05f27e29f1efee6aeb11a5940ebf0a85f4b88f4
20,088
c
C
pTk/mTk/win/tkWinEmbed.c
bekuno/perl-tk
ab69338e7a7d052d31b25fa54f920b1826b3b5af
[ "TCL" ]
28
2015-01-02T00:31:12.000Z
2021-12-21T09:03:05.000Z
pTk/mTk/win/tkWinEmbed.c
bekuno/perl-tk
ab69338e7a7d052d31b25fa54f920b1826b3b5af
[ "TCL" ]
44
2015-01-07T22:25:25.000Z
2022-03-28T13:34:44.000Z
pTk/mTk/win/tkWinEmbed.c
bekuno/perl-tk
ab69338e7a7d052d31b25fa54f920b1826b3b5af
[ "TCL" ]
18
2015-01-02T00:32:47.000Z
2022-03-24T12:57:40.000Z
/* * tkWinEmbed.c -- * * This file contains platform specific procedures for Windows platforms * to provide basic operations needed for application embedding (where * one application can use as its main window an internal window from * another application). * * Copyright (c) 1996-1997 Sun Microsystems, Inc. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * * RCS: @(#) $Id: tkWinEmbed.c,v 1.7 2002/08/05 04:30:41 dgp Exp $ */ #include "tkWinInt.h" /* * One of the following structures exists for each container in this * application. It keeps track of the container window and its * associated embedded window. */ typedef struct Container { HWND parentHWnd; /* Windows HWND to the parent window */ TkWindow *parentPtr; /* Tk's information about the container * or NULL if the container isn't * in this process. */ HWND embeddedHWnd; /* Windows HWND to the embedded window */ TkWindow *embeddedPtr; /* Tk's information about the embedded * window, or NULL if the * embedded application isn't in * this process. */ struct Container *nextPtr; /* Next in list of all containers in * this process. */ } Container; typedef struct ThreadSpecificData { Container *firstContainerPtr; /* First in list of all containers * managed by this process. */ } ThreadSpecificData; static Tcl_ThreadDataKey dataKey; static void CleanupContainerList _ANSI_ARGS_(( ClientData clientData)); static void ContainerEventProc _ANSI_ARGS_((ClientData clientData, XEvent *eventPtr)); static void EmbeddedEventProc _ANSI_ARGS_(( ClientData clientData, XEvent *eventPtr)); static void EmbedGeometryRequest _ANSI_ARGS_(( Container*containerPtr, int width, int height)); static void EmbedWindowDeleted _ANSI_ARGS_((TkWindow *winPtr)); /* *---------------------------------------------------------------------- * * CleanupContainerList -- * * Finalizes the list of containers. * * Results: * None. * * Side effects: * Releases memory occupied by containers of embedded windows. * *---------------------------------------------------------------------- */ /* ARGSUSED */ static void CleanupContainerList(clientData) ClientData clientData; { Container *nextPtr; ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); for (; tsdPtr->firstContainerPtr != (Container *) NULL; tsdPtr->firstContainerPtr = nextPtr) { nextPtr = tsdPtr->firstContainerPtr->nextPtr; ckfree((char *) tsdPtr->firstContainerPtr); } tsdPtr->firstContainerPtr = (Container *) NULL; } /* *---------------------------------------------------------------------- * * TkpTestembedCmd -- * * Test command for the embedding facility. * * Results: * Always returns TCL_OK. * * Side effects: * Currently it does not do anything. * *---------------------------------------------------------------------- */ /* ARGSUSED */ int TkpTestembedCmd(clientData, interp, argc, argv) ClientData clientData; Tcl_Interp *interp; int argc; CONST char **argv; { return TCL_OK; } /* *---------------------------------------------------------------------- * * TkpUseWindow -- * * This procedure causes a Tk window to use a given Windows handle * for a window as its underlying window, rather than a new Windows * window being created automatically. It is invoked by an embedded * application to specify the window in which the application is * embedded. * * Results: * The return value is normally TCL_OK. If an error occurred (such as * if the argument does not identify a legal Windows window handle), * the return value is TCL_ERROR and an error message is left in the * the interp's result if interp is not NULL. * * Side effects: * None. * *---------------------------------------------------------------------- */ int TkpUseWindow(interp, tkwin, string) Tcl_Interp *interp; /* If not NULL, used for error reporting * if string is bogus. */ Tk_Window tkwin; /* Tk window that does not yet have an * associated X window. */ Tcl_Obj *string; /* String identifying an X window to use * for tkwin; must be an integer value. */ { TkWindow *winPtr = (TkWindow *) tkwin; TkWindow *usePtr; int id; HWND hwnd; Container *containerPtr; ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); if (winPtr->window != None) { panic("TkpUseWindow: Already assigned a window"); } if (Tcl_GetIntFromObj(interp, string, &id) != TCL_OK) { char *s = Tcl_GetString(string); char *e = NULL; id = strtoul(s,&e,0); if (!e || *e) return TCL_ERROR; } hwnd = (HWND) id; /* * Check if the window is a valid handle. If it is invalid, return * TCL_ERROR and potentially leave an error message in the interp's * result. */ if (!IsWindow(hwnd)) { if (interp != (Tcl_Interp *) NULL) { Tcl_AppendResult(interp, "window \"", Tcl_GetString(string), "\" doesn't exist", (char *) NULL); } return TCL_ERROR; } usePtr = (TkWindow *) Tk_HWNDToWindow(hwnd); if (usePtr != NULL) { if (!(usePtr->flags & TK_CONTAINER)) { Tcl_AppendResult(interp, "window \"", usePtr->pathName, "\" doesn't have -container option set", (char *) NULL); return TCL_ERROR; } } /* * Store the parent window in the platform private data slot so * TkWmMapWindow can use it when creating the wrapper window. */ winPtr->privatePtr = (struct TkWindowPrivate*) hwnd; /* * Create an event handler to clean up the Container structure when * tkwin is eventually deleted. */ Tk_CreateEventHandler(tkwin, StructureNotifyMask, EmbeddedEventProc, (ClientData) winPtr); /* * If this is the first container, register an exit handler so that * things will get cleaned up at finalization. */ if (tsdPtr->firstContainerPtr == (Container *) NULL) { Tcl_CreateExitHandler(CleanupContainerList, (ClientData) NULL); } /* * Save information about the container and the embedded window * in a Container structure. If there is already an existing * Container structure, it means that both container and embedded * app. are in the same process. */ for (containerPtr = tsdPtr->firstContainerPtr; containerPtr != NULL; containerPtr = containerPtr->nextPtr) { if (containerPtr->parentHWnd == hwnd) { winPtr->flags |= TK_BOTH_HALVES; containerPtr->parentPtr->flags |= TK_BOTH_HALVES; break; } } if (containerPtr == NULL) { containerPtr = (Container *) ckalloc(sizeof(Container)); containerPtr->parentPtr = NULL; containerPtr->parentHWnd = hwnd; containerPtr->nextPtr = tsdPtr->firstContainerPtr; tsdPtr->firstContainerPtr = containerPtr; } /* * embeddedHWnd is not created yet. It will be created by TkWmMapWindow(), * which will send a TK_ATTACHWINDOW to the container window. * TkWinEmbeddedEventProc will process this message and set the embeddedHWnd * variable */ containerPtr->embeddedPtr = winPtr; containerPtr->embeddedHWnd = NULL; winPtr->flags |= TK_EMBEDDED; winPtr->flags &= (~(TK_MAPPED)); return TCL_OK; } /* *---------------------------------------------------------------------- * * TkpMakeContainer -- * * This procedure is called to indicate that a particular window will * be a container for an embedded application. This changes certain * aspects of the window's behavior, such as whether it will receive * events anymore. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ void TkpMakeContainer(tkwin) Tk_Window tkwin; { TkWindow *winPtr = (TkWindow *) tkwin; Container *containerPtr; ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); /* * If this is the first container, register an exit handler so that * things will get cleaned up at finalization. */ if (tsdPtr->firstContainerPtr == (Container *) NULL) { Tcl_CreateExitHandler(CleanupContainerList, (ClientData) NULL); } /* * Register the window as a container so that, for example, we can * find out later if the embedded app. is in the same process. */ Tk_MakeWindowExist(tkwin); containerPtr = (Container *) ckalloc(sizeof(Container)); containerPtr->parentPtr = winPtr; containerPtr->parentHWnd = Tk_GetHWND(Tk_WindowId(tkwin)); containerPtr->embeddedHWnd = NULL; containerPtr->embeddedPtr = NULL; containerPtr->nextPtr = tsdPtr->firstContainerPtr; tsdPtr->firstContainerPtr = containerPtr; winPtr->flags |= TK_CONTAINER; /* * Unlike in tkUnixEmbed.c, we don't make any requests for events * in the embedded window here. Now we just allow the embedding * of another TK application into TK windows. When the embedded * window makes a request, that will be done by sending to the * container window a WM_USER message, which will be intercepted * by TkWinContainerProc. * * We need to get structure events of the container itself, though. */ Tk_CreateEventHandler(tkwin, StructureNotifyMask, ContainerEventProc, (ClientData) containerPtr); } /* *---------------------------------------------------------------------- * * EmbeddedEventProc -- * * This procedure is invoked by the Tk event dispatcher when various * useful events are received for a window that is embedded in * another application. * * Results: * None. * * Side effects: * Our internal state gets cleaned up when an embedded window is * destroyed. * *---------------------------------------------------------------------- */ static void EmbeddedEventProc(clientData, eventPtr) ClientData clientData; /* Token for container window. */ XEvent *eventPtr; /* ResizeRequest event. */ { TkWindow *winPtr = (TkWindow *) clientData; if (eventPtr->type == DestroyNotify) { EmbedWindowDeleted(winPtr); } } /* *---------------------------------------------------------------------- * * TkWinEmbeddedEventProc -- * * This procedure is invoked by the Tk event dispatcher when * various useful events are received for the *children* of a * container window. It forwards relevant information, such as * geometry requests, from the events into the container's * application. * * Results: * None. * * Side effects: * Depends on the event. For example, when ConfigureRequest events * occur, geometry information gets set for the container window. * *---------------------------------------------------------------------- */ LRESULT TkWinEmbeddedEventProc(hwnd, message, wParam, lParam) HWND hwnd; UINT message; WPARAM wParam; LPARAM lParam; { Container *containerPtr; ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); /* * Find the Container structure associated with the parent window. */ for (containerPtr = tsdPtr->firstContainerPtr; containerPtr->parentHWnd != hwnd; containerPtr = containerPtr->nextPtr) { if (containerPtr == NULL) { panic("TkWinContainerProc couldn't find Container record"); } } switch (message) { case TK_ATTACHWINDOW: /* An embedded window (either from this application or from * another application) is trying to attach to this container. * We attach it only if this container is not yet containing any * window. */ if (containerPtr->embeddedHWnd == NULL) { containerPtr->embeddedHWnd = (HWND)wParam; } else { return 0; } break; case TK_GEOMETRYREQ: EmbedGeometryRequest(containerPtr, (int) wParam, lParam); break; } return 1; } /* *---------------------------------------------------------------------- * * EmbedGeometryRequest -- * * This procedure is invoked when an embedded application requests * a particular size. It processes the request (which may or may * not actually resize the window) and reflects the results back * to the embedded application. * * Results: * None. * * Side effects: * If we deny the child's size change request, a Configure event * is synthesized to let the child know that the size is the same * as it used to be. Events get processed while we're waiting for * the geometry managers to do their thing. * *---------------------------------------------------------------------- */ void EmbedGeometryRequest(containerPtr, width, height) Container *containerPtr; /* Information about the container window. */ int width, height; /* Size that the child has requested. */ { TkWindow * winPtr = containerPtr->parentPtr; /* * Forward the requested size into our geometry management hierarchy * via the container window. We need to send a Configure event back * to the embedded application even if we decide not to resize * the window; to make this happen, process all idle event handlers * synchronously here (so that the geometry managers have had a * chance to do whatever they want to do), and if the window's size * didn't change then generate a configure event. */ Tk_GeometryRequest((Tk_Window)winPtr, width, height); if (containerPtr->embeddedHWnd != NULL) { while (Tcl_DoOneEvent(TCL_IDLE_EVENTS)) { /* Empty loop body. */ } SetWindowPos(containerPtr->embeddedHWnd, NULL, 0, 0, winPtr->changes.width, winPtr->changes.height, SWP_NOZORDER); } } /* *---------------------------------------------------------------------- * * ContainerEventProc -- * * This procedure is invoked by the Tk event dispatcher when * various useful events are received for the container window. * * Results: * None. * * Side effects: * Depends on the event. For example, when ConfigureRequest events * occur, geometry information gets set for the container window. * *---------------------------------------------------------------------- */ static void ContainerEventProc(clientData, eventPtr) ClientData clientData; /* Token for container window. */ XEvent *eventPtr; /* ResizeRequest event. */ { Container *containerPtr = (Container *)clientData; Tk_Window tkwin = (Tk_Window)containerPtr->parentPtr; if (eventPtr->type == ConfigureNotify) { if (containerPtr->embeddedPtr == NULL) { return; } /* Resize the embedded window, if there is any */ if (containerPtr->embeddedHWnd) { SetWindowPos(containerPtr->embeddedHWnd, NULL, 0, 0, Tk_Width(tkwin), Tk_Height(tkwin), SWP_NOZORDER); } } else if (eventPtr->type == DestroyNotify) { /* The container is gone, remove it from the list */ EmbedWindowDeleted(containerPtr->parentPtr); } } /* *---------------------------------------------------------------------- * * TkpGetOtherWindow -- * * If both the container and embedded window are in the same * process, this procedure will return either one, given the other. * * Results: * If winPtr is a container, the return value is the token for the * embedded window, and vice versa. If the "other" window isn't in * this process, NULL is returned. * * Side effects: * None. * *---------------------------------------------------------------------- */ TkWindow * TkpGetOtherWindow(winPtr) TkWindow *winPtr; /* Tk's structure for a container or * embedded window. */ { Container *containerPtr; ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); for (containerPtr = tsdPtr->firstContainerPtr; containerPtr != NULL; containerPtr = containerPtr->nextPtr) { if (containerPtr->embeddedPtr == winPtr) { return containerPtr->parentPtr; } else if (containerPtr->parentPtr == winPtr) { return containerPtr->embeddedPtr; } } panic("TkpGetOtherWindow couldn't find window"); return NULL; } /* *---------------------------------------------------------------------- * * TkpClaimFocus -- * * This procedure is invoked when someone asks or the input focus * to be put on a window in an embedded application, but the * application doesn't currently have the focus. It requests the * input focus from the container application. * * Results: * None. * * Side effects: * The input focus may change. * *---------------------------------------------------------------------- */ void TkpClaimFocus(topLevelPtr, force) TkWindow *topLevelPtr; /* Top-level window containing desired * focus window; should be embedded. */ int force; /* One means that the container should * claim the focus if it doesn't * currently have it. */ { HWND hwnd = GetParent(Tk_GetHWND(topLevelPtr->window)); SendMessage(hwnd, TK_CLAIMFOCUS, (WPARAM) force, 0); } /* *---------------------------------------------------------------------- * * TkpRedirectKeyEvent -- * * This procedure is invoked when a key press or release event * arrives for an application that does not believe it owns the * input focus. This can happen because of embedding; for example, * X can send an event to an embedded application when the real * focus window is in the container application and is an ancestor * of the container. This procedure's job is to forward the event * back to the application where it really belongs. * * Results: * None. * * Side effects: * The event may get sent to a different application. * *---------------------------------------------------------------------- */ void TkpRedirectKeyEvent(winPtr, eventPtr) TkWindow *winPtr; /* Window to which the event was originally * reported. */ XEvent *eventPtr; /* X event to redirect (should be KeyPress * or KeyRelease). */ { /* not implemented */ } /* *---------------------------------------------------------------------- * * EmbedWindowDeleted -- * * This procedure is invoked when a window involved in embedding * (as either the container or the embedded application) is * destroyed. It cleans up the Container structure for the window. * * Results: * None. * * Side effects: * A Container structure may be freed. * *---------------------------------------------------------------------- */ static void EmbedWindowDeleted(winPtr) TkWindow *winPtr; /* Tk's information about window that * was deleted. */ { Container *containerPtr, *prevPtr; ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); /* * Find the Container structure for this window work. Delete the * information about the embedded application and free the container's * record. * The main container may be null. [Bug #476176] */ prevPtr = NULL; containerPtr = tsdPtr->firstContainerPtr; if (containerPtr == NULL) return; while (1) { if (containerPtr->embeddedPtr == winPtr) { containerPtr->embeddedHWnd = NULL; containerPtr->embeddedPtr = NULL; break; } if (containerPtr->parentPtr == winPtr) { containerPtr->parentPtr = NULL; break; } prevPtr = containerPtr; containerPtr = containerPtr->nextPtr; if (containerPtr == NULL) { panic("EmbedWindowDeleted couldn't find window"); } } if ((containerPtr->embeddedPtr == NULL) && (containerPtr->parentPtr == NULL)) { if (prevPtr == NULL) { tsdPtr->firstContainerPtr = containerPtr->nextPtr; } else { prevPtr->nextPtr = containerPtr->nextPtr; } ckfree((char *) containerPtr); } }
29.628319
80
0.621615
[ "geometry" ]
f05fe2ccce7af38daf932b6459f7eb07a317e521
1,776
h
C
include/kontiki/sensors/vlp16_lidar.h
AlexDayCRL/Kontiki
afeaa22020b4ee14c4078dfd8700836fa6c423a2
[ "MIT" ]
13
2020-11-18T11:31:22.000Z
2022-01-27T06:01:15.000Z
include/kontiki/sensors/vlp16_lidar.h
AlexDayCRL/Kontiki
afeaa22020b4ee14c4078dfd8700836fa6c423a2
[ "MIT" ]
null
null
null
include/kontiki/sensors/vlp16_lidar.h
AlexDayCRL/Kontiki
afeaa22020b4ee14c4078dfd8700836fa6c423a2
[ "MIT" ]
8
2020-09-22T07:52:00.000Z
2022-03-22T06:43:07.000Z
#ifndef VLP16_LIDAR_H #define VLP16_LIDAR_H #include <iostream> #include <Eigen/Dense> #include "lidar.h" #include <entity/paramstore/dynamic_pstore.h> namespace kontiki { namespace sensors { namespace internal { struct VLP16Meta : public LiDARMeta { size_t NumParameters() const override { return LiDARMeta::NumParameters(); } }; template<typename T, typename MetaType> class VLP16View : public LiDARView<T, MetaType> { using Vector3 = Eigen::Matrix<T, 3, 1>; using Result = std::unique_ptr<LiDAREvaluation<T>>; public: // Inherit constructors using LiDARView<T, MetaType>::LiDARView; }; template<template<typename...> typename ViewTemplate, typename MetaType, typename StoreType> class VLP16Entity : public LiDAREntity<ViewTemplate, MetaType, StoreType> { using Base = LiDAREntity<ViewTemplate, MetaType, StoreType>; public: VLP16Entity() : Base() {} void AddToProblem(ceres::Problem &problem, time_init_t times, MetaType &meta, std::vector<entity::ParameterInfo<double>> &parameters) const override { meta = this->meta_; Base::AddToProblem(problem, times, meta, parameters); } }; } // namespace internal class VLP16LiDAR : public internal::VLP16Entity<internal::VLP16View, internal::VLP16Meta, entity::DynamicParameterStore<double> > { public: using internal::VLP16Entity< internal::VLP16View, internal::VLP16Meta, entity::DynamicParameterStore<double>>::VLP16Entity; static constexpr const char *CLASS_ID = "VLP16LiDAR"; }; } // namespace sensors } // namespace kontiki #endif // VLP16_LIDAR_H
25.371429
92
0.654279
[ "vector" ]
f062b8b12f194c43c0e3b0ad1e64b9230169eed7
8,177
h
C
Code/Components/Analysis/analysisutilities/current/mathsutils/MathsUtils.h
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
1
2020-06-18T08:37:43.000Z
2020-06-18T08:37:43.000Z
Code/Components/Analysis/analysisutilities/current/mathsutils/MathsUtils.h
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Analysis/analysisutilities/current/mathsutils/MathsUtils.h
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
/// @file /// /// Provides utility functions for simulations package /// /// @copyright (c) 2007 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// atnf-enquiries@csiro.au /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// @author Matthew Whiting <matthew.whiting@csiro.au> /// #ifndef ASKAP_ANALYSISUTILS_MATHS_H_ #define ASKAP_ANALYSISUTILS_MATHS_H_ #include <askap/AskapLogging.h> #include <askap/AskapError.h> #include <casacore/casa/namespace.h> #include <casacore/scimath/Functionals/Gaussian2D.h> #include <duchamp/FitsIO/Beam.hh> #include <vector> #include <utility> #include <string> #include <math.h> namespace askap { namespace analysisutilities { /// @brief Convert between a Gaussian's sigma and its FWHM inline const double FWHMtoSIGMA(const double f) {return f / (2. * M_SQRT2 * sqrt(M_LN2));}; inline const double SIGMAtoFWHM(const double s) {return s * (2. * M_SQRT2 * sqrt(M_LN2));}; /// @brief Return a normal random variable /// @details Simulate a normal random variable from a /// distribution with mean given by mean and standard deviation /// given by sigma. The variable is simulated via the polar /// method. /// @param mean The mean of the normal distribution /// @param sigma The standard deviation of the normal distribution /// @return A random variable. const float normalRandomVariable(const float mean, const float rms); /// @brief Return the standard normal z-score corresponding to a probability (integrated from -infinity) const double probToZvalue(const double prob); const double atanCircular(const double sinTerm, const double cosTerm); /// Use the parametric equation for an ellipse (u = a cos(t), v = b /// sin(t)) to find the limits of x and y once converted from u & v. void findEllipseLimits(const double major, const double minor, const double pa, float &xmin, float &xmax, float &ymin, float &ymax); /// Find the mean or robust estimate thereof for an array. Finds the /// "middle" (ie. the mean) of an array of values. The option exists /// to use the mean, or, by setting robust=true, the median. const double findMiddle(const bool robust, const std::vector<float> &array); /// Find an rms or robust estimate thereof for an array given a mean value. /// Finds the "spread" (ie. the rms or standard deviation) of an /// array of values using a given mean value. The option exists /// to use the standard deviation, or, by setting robust=true, /// the median absolute deviation from the median. In the latter /// case, the middle value given is assumed to be the median, /// and the returned value is the median absolute difference of /// the data values from the median. /// @ingroup analysisutilities const double findSpread(const bool robust, const double middle, const std::vector<float> &array); /// Find an rms robust estimate thereof for an array. Calls /// findMiddle first, then uses that value to call /// findSpread(bool,double,std::vector<float>&). const double findSpread(const bool robust, const std::vector<float> &array); /// Find the mean or robust estimate thereof for an array, with /// masking of pixels. Finds the "middle" (ie. the mean) of an array /// of values. The option exists to use the mean, or, by setting /// robust=true, the median. Only pixels where the mask is true are /// used. const double findMiddle(const bool robust, const std::vector<float> &array, const std::vector<bool> &mask); /// Find an rms for an array given a mean value, with masking of /// pixels. Finds the "spread" (ie. the rms or standard deviation) of /// an array of values using a given mean value. The option exists to /// use the standard deviation, or, by setting robust=true, the median /// absolute deviation from the median. In the latter case, the middle /// value given is assumed to be the median, and the returned value is /// the median absolute difference of the data values from the /// median. Only pixels where the mask is true are used. const double findSpread(const bool robust, const double middle, const std::vector<float> &array, const std::vector<bool> &mask); /// Find an rms robust estimate thereof for an array, with masking of /// pixels. Calls findMiddle first, then uses that value to call /// findSpread(bool,double,std::vector<float>&,std::vector<bool>&). const double findSpread(const bool robust, const std::vector<float> &array, const std::vector<bool> &mask); /// @brief Return the probability of obtaining a chisq value by /// chance, for a certain number of degrees of freedom. /// @ingroup analysisutilities /// @details Returns the probability of exceeding the given /// value of chisq by chance. If it comes from a fit, this /// probability is assuming the fit is valid. /// /// Typical use: say you have a fit with ndof=5 degrees of /// freedom that gives a chisq value of 12. You call this /// function via chisqProb(5,12.), which will return /// 0.0347878. If your confidence limit is 95% (ie. you can /// tolerate a 1-in-20 chance that a valid fit will produce a /// chisq value that high), you would reject that fit (since /// 0.0347878 < 0.05), but if it is 99%, you would accept it /// (since 0.0347878 > 0.01). const float chisqProb(const float ndof, const float chisq); /// @brief Return the Gaussian after deconvolution with the given beam /// @details Deconvolution of a Gaussian shape, assuming it /// was convolved with the given beam. This procedure /// replicates the approach described in Wild (1970), AuJPh /// 23, 113. /// @param measured Gaussian shape to be deconvolved /// @param beam Beam shape of image /// @return A vector containing (in order), the major & minor /// axes, and the position angle (in radians). const std::vector<Double> deconvolveGaussian(const casa::Gaussian2D<Double> &measured, duchamp::Beam beam); /// @brief Return the Gaussian after deconvolution with the given beam /// @details Deconvolution of a Gaussian shape, assuming it was /// convolved with the given beam. This procedure replicates the /// approach described in Wild (1970), AuJPh 23, 113. Also returned /// are the errors on the deconvolved sizes, calculated using the /// errors on the measured sizes. /// @param measured Gaussian shape to be deconvolved /// @param beam Beam shape of image /// @return A vector containing (in order), the major & minor axes, /// and the position angle (in radians), followed by the error on /// those three parameters const std::vector<Double> deconvolveGaussian(const casa::Gaussian2D<Double> &measured, casa::Vector<Double> &errors, duchamp::Beam beam); /// @brief Fit a quadratic analytically to three points. /// @details Directly calculates the parabola of the form y = Ax^2 + /// Bx + C that goest through the three points given. The vectors may /// have sizes larger than three, but only the first three points in /// each are used. The returned vector is of size three, in order of /// [A,B,C]. template <class T> std::vector<T> fit3ptParabola(const T x0, const T y0, const T x1, const T y1, const T x2, const T y2); } } #endif
44.2
111
0.71163
[ "shape", "vector" ]
f06f7976822d8b8c9b6f4a90c3c8a043306c581c
4,765
c
C
src/kbapi.c
Suptree/kilombo
21efce54fc83ca9f13f874d63602c4b74201deb0
[ "MIT" ]
39
2015-11-19T07:58:08.000Z
2021-02-14T08:44:48.000Z
src/kbapi.c
Suptree/kilombo
21efce54fc83ca9f13f874d63602c4b74201deb0
[ "MIT" ]
24
2015-11-11T14:15:15.000Z
2021-09-27T07:50:26.000Z
src/kbapi.c
Suptree/kilombo
21efce54fc83ca9f13f874d63602c4b74201deb0
[ "MIT" ]
24
2016-08-30T20:28:59.000Z
2022-02-16T20:32:08.000Z
#include <math.h> #include "skilobot.h" #include "kilolib.h" /* pointers to messaging functions * the kilobot program typically sets these in main() * * for simplicity we have only ONE set of these instead of * one for each bot. If all bots register the same functions, * this will work. */ message_tx_t kilo_message_tx = NULL; message_tx_success_t kilo_message_tx_success = NULL; message_rx_t kilo_message_rx = NULL; /* the clock variable. Counts ticks since beginning of the program. * Each bot really has it's own, but for now we have just one. * Declared volatile to match declaration in kilolib.h */ volatile uint32_t kilo_ticks = 0; // the simulator will copy a new UID here, before calling each bot uint16_t kilo_uid = 0; /* motor calibration values * In the kilobots, these are different for each robot, and are stored in the EEPROM. * We model this in a very simple way in the simulator. The model is tuned so that * even if noise is set, on average the configured turn speed will be reached at an * activation value of 75. * Note that at this point straight movement is still independent of motor activation value. */ uint8_t kilo_turn_left = 75; uint8_t kilo_turn_right = 75; uint8_t kilo_straight_left = 75; uint8_t kilo_straight_right = 75; /* Each bot is required to call kilo_init. * In the simulator, we initialize the software RNG. */ void kilo_init(void) { kilobot* self = Me(); self->seed=0xaa; //same state as in the bot self->accumulator = 0; } /* In the kilobot, this function calls setup once. * Then it loops forever calling the function loop() and checks for control messages. * We just store the function pointers and call setup() * the loop() will be run for all bots later */ void kilo_start(void (*setup)(void), void (*loop)(void)) { current_bot->user_setup = setup; current_bot->user_loop = loop; } void set_motors(uint8_t left, uint8_t right) { kilobot* self = Me(); set_speeds(self, left, right); return; } /* run the motors at full power for 15 ms to start them * Ignored in the simulator. */ void spinup_motors() { } /* Set the LED colour. Bits: 00bbggrr */ void set_color(uint8_t color) { int r = color & 3; int g = (color >> 2) & 3; int b = (color >> 4) & 3; kilobot* self = Me(); self->r_led = r; self->g_led = g; self->b_led = b; } /* Estimate distance from signal strength measurements. * We store the distance in mm in the high_gain field when passing messages, * so we can simply return it here. */ uint8_t estimate_distance(const distance_measurement_t *d) { return d->high_gain; } // checksum for messages uint16_t message_crc(const message_t *msg) { return 0; /* if we never check it we don't need to implement it. * otherwise copy from kilolib, message_crc.c and * the crc functions from util/crc16.h */ } /* delay is tricky to implement in the simulator * do as much as possible using the kilo_ticks variable instead */ void _delay_ms(int ms) { /* TODO - implementation! */ return; } // the kilobot API version of delay void delay (uint16_t ms) { return; } /* Hardware random number generator - "truly random" in the bot. * In the simulator, we use rand(), with the SAME generator shared by all bots * and shared by the simulator itself, if it uses rand somewhere internally. */ uint8_t rand_hard() { return rand() & 0xFF; } /* Software random number generator. * this is the same as the one in kilolib. * Each bot has it's own seed and accumulator, so the sequence should be the same as in the bot */ uint8_t rand_soft() { kilobot* self = Me(); self->seed ^= self->seed<<3; self->seed ^= self->seed>>5; self->seed ^= self->accumulator++>>2; return self->seed; } void rand_seed(uint8_t seed) { kilobot* self = Me(); self->seed = seed; } float get_potential(int type) { kilobot* self = Me(); switch(type) { case POT_LINEAR: return self->x; case POT_PARABOLIC: return pow(self->x, 2) + pow(self->y, 2); case POT_GRAVITY: return 1.0 / hypot(self->x, self->y); default: return 0; } } // 10 bit measurement of ambient light // return the x coordinate as the light intensity // - simulates a light gradient in x int16_t get_ambientlight() { kilobot* self = Me(); int l; if (user_light != NULL) l = user_light(self->x, self->y); else // parabolic well l = ( pow(self->x, 2) + pow(self->y, 2) )/1000; // constrain to interval [0,1023] if (l > 1023) l = 1023; if (l < 0) l = 0; return l; } // 10 bit measurement of battery voltage. // TODO: find the scale, implement a decrease with time? int16_t get_voltage() { return 876; } int16_t get_temperature() { return 314; }
22.908654
95
0.683526
[ "model" ]
f07b87573466d17b2a83bd04e3067f89bdc979e0
2,836
h
C
yave/scene/OctreeNode.h
gan74/Yave
a35a68d388729d02f9793cc0fe9a530c010cf432
[ "MIT" ]
259
2016-12-02T03:06:19.000Z
2022-03-13T19:21:00.000Z
yave/scene/OctreeNode.h
gan74/Yave
a35a68d388729d02f9793cc0fe9a530c010cf432
[ "MIT" ]
3
2019-05-02T04:09:13.000Z
2021-12-27T02:27:33.000Z
yave/scene/OctreeNode.h
gan74/Yave
a35a68d388729d02f9793cc0fe9a530c010cf432
[ "MIT" ]
17
2019-01-04T10:07:23.000Z
2021-09-15T08:41:04.000Z
/******************************* Copyright (c) 2016-2021 Grégoire Angerand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **********************************/ #ifndef YAVE_SCENE_OCTREENODE_H #define YAVE_SCENE_OCTREENODE_H #include "OctreeData.h" #include <yave/meshes/AABB.h> #include <array> #include <memory> namespace yave { class OctreeNode { using Children = std::array<OctreeNode, 8>; static constexpr bool split_small_object = false; static constexpr float min_object_size_ratio = 16.0f; static constexpr usize max_entities_per_node = 32; static constexpr float min_node_extent = 1.0f; static constexpr float overlap_extent_multiplier = 1.25f; static constexpr float full_extent_multiplier = overlap_extent_multiplier * 2.0f; public: OctreeNode() = default; OctreeNode(const math::Vec3& center, float half_extent, OctreeData* data); OctreeNode* insert(ecs::EntityId id, const AABB& bbox); AABB aabb() const; AABB strict_aabb() const; bool contains(const AABB& bbox) const; bool contains(const math::Vec3& pos, float radius) const; bool has_children() const; bool is_empty() const; core::Span<OctreeNode> children() const; Y_TODO(Make thread safe) void set_dirty(ecs::EntityId id); private: friend class Octree; // REMOVE friend class OctreeSystem; void into_parent(const math::Vec3& toward); private: void swap(OctreeNode& other); void build_children(); usize children_index(const math::Vec3& pos); math::Vec3 _center; float _half_extent = -1.0f; std::unique_ptr<Children> _children; core::Vector<ecs::EntityId> _entities; OctreeData* _data = nullptr; }; } #endif // YAVE_SCENE_OCTREENODE_H
29.541667
85
0.702045
[ "vector" ]
f07be9e61630e72990571dbfdd813f50ef30f654
76,840
h
C
src/libtsduck/tsMPEG.h
yrpark99/tsduck
2929092e42c5c7eec95a119af91cc09ffdde2028
[ "BSD-2-Clause" ]
null
null
null
src/libtsduck/tsMPEG.h
yrpark99/tsduck
2929092e42c5c7eec95a119af91cc09ffdde2028
[ "BSD-2-Clause" ]
null
null
null
src/libtsduck/tsMPEG.h
yrpark99/tsduck
2929092e42c5c7eec95a119af91cc09ffdde2028
[ "BSD-2-Clause" ]
null
null
null
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2018, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- //! //! @file //! @ingroup mpeg //! Common definition for MPEG level. //! //---------------------------------------------------------------------------- #pragma once #include "tsPlatform.h" #include "tsEnumeration.h" namespace ts { // Base types typedef uint16_t PID; //!< PID value. typedef uint8_t TID; //!< Table identifier. typedef uint8_t DID; //!< Descriptor identifier. typedef uint32_t PDS; //!< Private data specifier. typedef uint32_t BitRate; //!< Bitrate in bits/second. //! //! MPEG TS packet size in bytes. //! const size_t PKT_SIZE = 188; //! //! MPEG TS packet size in bits. //! const size_t PKT_SIZE_BITS = 8 * PKT_SIZE; //! //! Size in bytes of a Reed-Solomon outer FEC. //! const size_t RS_SIZE = 16; //! //! Size in bytes of a TS packet with trailing Reed-Solomon outer FEC. //! const size_t PKT_RS_SIZE = PKT_SIZE + RS_SIZE; //! //! Size in bytes of a timestamp preceeding a TS packet in M2TS files (Blu-ray disc). //! const size_t M2TS_HEADER_SIZE = 4; //! //! Size in bytes of an TS packet in M2TS files (Blu-ray disc). //! There is a leading 4-byte timestamp before the TS packet. //! const size_t PKT_M2TS_SIZE = M2TS_HEADER_SIZE + PKT_SIZE; //! //! Number of Transport Stream packets. //! //! TS packets are counted using 64-bit integers. //! Thus, PacketCounter will never overflow: at 100 Mb/s, 2^64 188-byte //! packets will take 8.7 million years to transmit. No process will //! ever run that long. On the contrary, using 32-bit integer would //! be insufficient: at 100 Mb/s, 2^32 188-byte packets will take //! only 17 hours to transmit. //! typedef uint64_t PacketCounter; //! //! A impossible value for PacketCounter, meaning "undefined". //! const PacketCounter INVALID_PACKET_COUNTER = std::numeric_limits<PacketCounter>::max(); //! //! Number of sections. //! typedef uint64_t SectionCounter; //! //! Convert 188-byte packet bitrate into 204-byte packet bitrate. //! @param [in] bitrate188 Bitrate using 188-byte packet as reference. //! @return Corresponding bitrate using 204-byte packet as reference. //! TSDUCKDLL inline BitRate ToBitrate204(BitRate bitrate188) { return BitRate((uint64_t (bitrate188) * 204L) / 188L); } //! //! Convert 204-byte packet bitrate into 188-byte packet bitrate. //! @param [in] bitrate204 Bitrate using 204-byte packet as reference. //! @return Corresponding bitrate using 188-byte packet as reference. //! TSDUCKDLL inline BitRate ToBitrate188(BitRate bitrate204) { return BitRate((uint64_t (bitrate204) * 188L) / 204L); } //! //! Compute the interval, in milliseconds, between two packets. //! @param [in] bitrate TS bitrate in bits/second, based on 188-byte packets. //! @param [in] distance Distance between the two packets: 0 for the same //! packet, 1 for the next packet (the default), etc. //! @return Interval in milliseconds between the first byte of the first packet //! and the first byte of the second packet. //! TSDUCKDLL inline MilliSecond PacketInterval(BitRate bitrate, PacketCounter distance = 1) { return bitrate == 0 ? 0 : (distance * 8 * PKT_SIZE * MilliSecPerSec) / MilliSecond(bitrate); } //! //! Compute the number of packets transmitted during a given duration in milliseconds. //! @param [in] bitrate TS bitrate in bits/second, based on 188-byte packets. //! @param [in] duration Number of milliseconds. //! @return Number of packets during @a duration milliseconds. //! TSDUCKDLL inline PacketCounter PacketDistance(BitRate bitrate, MilliSecond duration) { return (PacketCounter (bitrate) * (duration >= 0 ? duration : -duration)) / (MilliSecPerSec * 8 * PKT_SIZE); } //! //! Compute the bitrate from a number of packets transmitted during a given duration in milliseconds. //! @param [in] packets Number of packets during @a duration milliseconds. //! @param [in] duration Number of milliseconds. //! @return TS bitrate in bits/second, based on 188-byte packets. //! TSDUCKDLL inline BitRate PacketBitRate(PacketCounter packets, MilliSecond duration) { return duration == 0 ? 0 : BitRate((packets * 8 * PKT_SIZE * MilliSecPerSec) / duration); } //! //! Compute the minimum number of TS packets required to transport a section. //! @param [in] section_size Total section size in bytes. //! @return Number of packets required for the section. //! TSDUCKDLL inline PacketCounter SectionPacketCount(size_t section_size) { // The required size for a section is section_size + 1 (1 for pointer_field // in first packet). In each packet, the useable size is 184 bytes. return PacketCounter((section_size + 184) / 184); } //! //! Value of a sync byte (first byte in a TS packet). //! const uint8_t SYNC_BYTE = 0x47; //! //! PES packet start code prefix (24 bits). //! const uint32_t PES_START = 0x000001; //! //! Size (in bits) of a PID field. //! const size_t PID_BITS = 13; //! //! Maximum number of PID's (8192). //! const PID PID_MAX = 1 << PID_BITS; //! //! A bit mask for PID values. //! Useful to implement PID filtering. //! typedef std::bitset <PID_MAX> PIDSet; //! //! PIDSet constant with no PID set. //! TSDUCKDLL extern const PIDSet NoPID; //! //! PIDSet constant with all PID's set. //! TSDUCKDLL extern const PIDSet AllPIDs; //! //! Size (in bits) of a Continuity Counter (CC) field. //! const size_t CC_BITS = 4; //! //! Mask to wrap a Continuity Counter (CC) value. //! CC values wrap at 16. //! const uint8_t CC_MASK = 0x0F; //! //! Maximum value of a Continuity Counter (CC). //! const uint8_t CC_MAX = 1 << CC_BITS; //! //! Size (in bits) of a section version field. //! const size_t SVERSION_BITS = 5; //! //! Mask to wrap a section version value. //! Section version values wrap at 32. //! const uint8_t SVERSION_MASK = 0x1F; //! //! Maximum value of a section version. //! const uint8_t SVERSION_MAX = 1 << SVERSION_BITS; //! //! Scrambling_control values (used in TS and PES packets headers) //! enum : uint8_t { SC_CLEAR = 0, //!< Not scrambled (MPEG-defined). SC_DVB_RESERVED = 1, //!< Reserved for future use by DVB. SC_EVEN_KEY = 2, //!< Scrambled with even key (DVB-defined). SC_ODD_KEY = 3 //!< Scrambled with odd key (DVB-defined). }; //! //! Origin of Modified Julian Dates (MJD). //! The origin of MJD is 17 Nov 1858 00:00:00. //! The UNIX epoch (1 Jan 1970) is 40587 days from julian time origin. //! const uint32_t MJD_EPOCH = 40587; //! //! Video macroblock width in pixels. //! Valid for: //! - ISO 11172-2 (MPEG-1 video) //! - ISO 13818-2 (MPEG-2 video) //! - ISO 14496-10 (MPEG-4 Advanced Video Coding, AVC, ITU H.264) //! const size_t MACROBLOCK_WIDTH = 16; //! //! Video macroblock height in pixels. //! @see MACROBLOCK_WIDTH //! const size_t MACROBLOCK_HEIGHT = 16; //--------------------------------------------------------------------- //! Predefined PID values //--------------------------------------------------------------------- enum : PID { // Valid in all MPEG contexts: PID_PAT = 0x0000, //!< PID for Program Association Table PAT PID_CAT = 0x0001, //!< PID for Conditional Access Table PID_TSDT = 0x0002, //!< PID for Transport Stream Description Table PID_MPEG_LAST = 0x000F, //!< Last reserved PID for MPEG. PID_NULL = 0x1FFF, //!< PID for Null packets (stuffing) // Valid in DVB context: PID_NIT = 0x0010, //!< PID for Network Information Table PID_SDT = 0x0011, //!< PID for Service Description Table PID_BAT = 0x0011, //!< PID for Bouquet Association Table PID_EIT = 0x0012, //!< PID for Event Information Table PID_RST = 0x0013, //!< PID for Running Status Table PID_TDT = 0x0014, //!< PID for Time & Date Table PID_TOT = 0x0014, //!< PID for Time Offset Table PID_NETSYNC = 0x0015, //!< PID for Network synchronization PID_RNT = 0x0016, //!< PID for TV-Anytime PID_INBSIGN = 0x001C, //!< PID for Inband Signalling PID_MEASURE = 0x001D, //!< PID for Measurement PID_DIT = 0x001E, //!< PID for Discontinuity Information Table PID_SIT = 0x001F, //!< PID for Selection Information Table PID_DVB_LAST = 0x001F, //!< Last reserved PID for DVB. }; //--------------------------------------------------------------------- // MPEG clock representation: // - PCR (Program Clock Reference) // - PTS (Presentation Time Stamp) // - DTS (Decoding Time Stamp) //--------------------------------------------------------------------- //! //! MPEG-2 System Clock frequency in Hz, used by PCR (27 Mb/s). //! const uint32_t SYSTEM_CLOCK_FREQ = 27000000; //! //! Subfactor of MPEG-2 System Clock subfrequency, used by PTS and DTS. //! const uint32_t SYSTEM_CLOCK_SUBFACTOR = 300; //! //! MPEG-2 System Clock subfrequency in Hz, used by PTS and DTS (90 Kb/s). //! const uint32_t SYSTEM_CLOCK_SUBFREQ = SYSTEM_CLOCK_FREQ / SYSTEM_CLOCK_SUBFACTOR; //! //! Size in bits of a PCR (Program Clock Reference). //! const size_t PCR_BIT_SIZE = 42; //! //! Size in bits of a PTS (Presentation Time Stamp) or DTS (Decoding Time Stamp). //! const size_t PTS_DTS_BIT_SIZE = 33; //! //! Mask for PCR values (wrap up at 2**42). //! const uint64_t PCR_MASK = TS_UCONST64(0x000003FFFFFFFFFF); //! //! Scale factor for PCR values (wrap up at 2**42). //! const uint64_t PCR_SCALE = TS_UCONST64(0x0000040000000000); //! //! Mask for PTS and DTS values (wrap up at 2**33). //! const uint64_t PTS_DTS_MASK = TS_UCONST64(0x00000001FFFFFFFF); //! //! Scale factor for PTS and DTS values (wrap up at 2**33). //! const uint64_t PTS_DTS_SCALE = TS_UCONST64(0x0000000200000000); //! //! An invalid PCR (Program Clock Reference) value, can be used as a marker. //! const uint64_t INVALID_PCR = TS_UCONST64(0xFFFFFFFFFFFFFFFF); //! //! An invalid PTS value, can be used as a marker. //! const uint64_t INVALID_PTS = TS_UCONST64(0xFFFFFFFFFFFFFFFF); //! //! An invalid DTS value, can be used as a marker. //! const uint64_t INVALID_DTS = TS_UCONST64(0xFFFFFFFFFFFFFFFF); //! //! Check if PCR2 follows PCR1 after wrap up. //! @param [in] pcr1 First PCR. //! @param [in] pcr2 Second PCR. //! @return True is @a pcr2 is probably following @a pcr1 after wrapping up at 2**42. //! TSDUCKDLL inline bool WrapUpPCR(uint64_t pcr1, uint64_t pcr2) { return pcr2 < pcr1 && (pcr1 - pcr2) > TS_UCONST64(0x000003F000000000); } //! //! Check if PTS2 follows PTS1 after wrap up. //! @param [in] pts1 First PTS. //! @param [in] pts2 Second PTS. //! @return True is @a pts2 is probably following @a pts1 after wrapping up at 2**33. //! TSDUCKDLL inline bool WrapUpPTS(uint64_t pts1, uint64_t pts2) { return pts2 < pts1 && (pts1 - pts2) > TS_UCONST64(0x00000001F0000000); } //! //! Check if two Presentation Time Stamp are in sequence. //! //! In MPEG video, B-frames are transported out-of-sequence. //! Their PTS is typically lower than the previous D-frame or I-frame //! in the transport. A "sequenced" PTS is one that is higher than //! the previous sequenced PTS (with possible wrap up). //! @param [in] pts1 First PTS. //! @param [in] pts2 Second PTS. //! @return True is @a pts2 is after @a pts1, possibly after wrapping up at 2**33. //! TSDUCKDLL inline bool SequencedPTS(uint64_t pts1, uint64_t pts2) { return pts1 <= pts2 || WrapUpPTS(pts1, pts2); } //--------------------------------------------------------------------- //! Stream id values, as used in PES header. //--------------------------------------------------------------------- enum : uint8_t { SID_PSMAP = 0xBC, //!< Stream id for Program stream map SID_PRIV1 = 0xBD, //!< Stream id for Private stream 1 SID_PAD = 0xBE, //!< Stream id for Padding stream SID_PRIV2 = 0xBF, //!< Stream id for Private stream 2 SID_AUDIO = 0xC0, //!< Stream id for Audio stream, with number SID_AUDIO_MASK = 0x1F, //!< Stream id for Mask to get audio stream number SID_VIDEO = 0xE0, //!< Stream id for Video stream, with number SID_VIDEO_MASK = 0x0F, //!< Stream id for Mask to get video stream number SID_ECM = 0xF0, //!< Stream id for ECM stream SID_EMM = 0xF1, //!< Stream id for EMM stream SID_DSMCC = 0xF2, //!< Stream id for DSM-CC data SID_ISO13522 = 0xF3, //!< Stream id for ISO 13522 (hypermedia) SID_H222_1_A = 0xF4, //!< Stream id for H.222.1 type A SID_H222_1_B = 0xF5, //!< Stream id for H.222.1 type B SID_H222_1_C = 0xF6, //!< Stream id for H.222.1 type C SID_H222_1_D = 0xF7, //!< Stream id for H.222.1 type D SID_H222_1_E = 0xF8, //!< Stream id for H.222.1 type E SID_ANCILLARY = 0xF9, //!< Stream id for Ancillary stream SID_MP4_SLPACK = 0xFA, //!< Stream id for MPEG-4 SL-packetized stream SID_MP4_FLEXM = 0xFB, //!< Stream id for MPEG-4 FlexMux stream SID_METADATA = 0xFC, //!< Stream id for MPEG-7 metadata stream SID_EXTENDED = 0xFD, //!< Stream id for Extended stream id SID_RESERVED = 0xFE, //!< Stream id for Reserved value SID_PSDIR = 0xFF, //!< Stream id for Program stream directory }; //! //! Check if a stream id value indicates a video stream. //! @param [in] sid Stream id as found in a PES header. //! @return True if @a sid indicates a video stream. //! TSDUCKDLL inline bool IsVideoSID(uint8_t sid) { return (sid & ~SID_VIDEO_MASK) == SID_VIDEO; } //! //! Check if a stream id value indicates an audio stream. //! @param [in] sid Stream id as found in a PES header. //! @return True if @a sid indicates an audio stream. //! TSDUCKDLL inline bool IsAudioSID (uint8_t sid) { return (sid & ~SID_AUDIO_MASK) == SID_AUDIO; } //! //! Check if a stream id value indicates a PES packet with long header. //! @param [in] sid Stream id as found in a PES header. //! @return True if @a sid indicates a PES packet with long header. //! TSDUCKDLL bool IsLongHeaderSID(uint8_t sid); //--------------------------------------------------------------------- //! PES start code values. //--------------------------------------------------------------------- enum : uint8_t { PST_PICTURE = 0x00, //!< Picture PES start code. PST_SLICE_MIN = 0x01, //!< First slice PES start code. PST_SLICE_MAX = 0xAF, //!< Last slice PES start code. PST_RESERVED_B0 = 0xB0, //!< Reserved PES start code. PST_RESERVED_B1 = 0xB1, //!< Reserved PES start code. PST_USER_DATA = 0xB2, //!< User data PES start code. PST_SEQUENCE_HEADER = 0xB3, //!< Sequence header PES start code. PST_SEQUENCE_ERROR = 0xB4, //!< Sequence error PES start code. PST_EXTENSION = 0xB5, //!< Extension PES start code. PST_RESERVED_B6 = 0xB6, //!< Reserved PES start code. PST_SEQUENCE_END = 0xB7, //!< End of sequence PES start code. PST_GROUP = 0xB8, //!< Group PES start code. PST_SYSTEM_MIN = 0xB9, //!< First stream id value (SID_*). PST_SYSTEM_MAX = 0xFF, //!< Last stream id value (SID_*). }; //--------------------------------------------------------------------- //! Frame rate values (in MPEG-1/2 video sequence). //--------------------------------------------------------------------- enum { FPS_23_976 = 0x01, //!< 23.976 fps (24000/1001) FPS_24 = 0x02, //!< 24 fps FPS_25 = 0x03, //!< 25 fps FPS_29_97 = 0x04, //!< 29.97 fps (30000/1001) FPS_30 = 0x05, //!< 30 fps FPS_50 = 0x06, //!< 50 fps FPS_59_94 = 0x07, //!< 59.94 fps (60000/1001) FPS_60 = 0x08, //!< 60 fps }; //--------------------------------------------------------------------- //! Aspect ratio values (in MPEG-1/2 video sequence header). //--------------------------------------------------------------------- enum { AR_SQUARE = 1, //!< 1/1 MPEG video aspect ratio. AR_4_3 = 2, //!< 4/3 MPEG video aspect ratio. AR_16_9 = 3, //!< 16/9 MPEG video aspect ratio. AR_221 = 4, //!< 2.21/1 MPEG video aspect ratio. }; //--------------------------------------------------------------------- //! Chroma format values (in MPEG-1/2 video sequence header). //--------------------------------------------------------------------- enum { CHROMA_MONO = 0, //!< Monochrome MPEG video. CHROMA_420 = 1, //!< Chroma 4:2:0 MPEG video. CHROMA_422 = 2, //!< Chroma 4:2:2 MPEG video. CHROMA_444 = 3, //!< Chroma 4:4:4 MPEG video. }; //--------------------------------------------------------------------- //! AVC access unit types //--------------------------------------------------------------------- enum { AVC_AUT_NON_IDR = 1, //!< Coded slice of a non-IDR picture (NALunit type). AVC_AUT_SLICE_A = 2, //!< Coded slice data partition A (NALunit type). AVC_AUT_SLICE_B = 3, //!< Coded slice data partition B (NALunit type). AVC_AUT_SLICE_C = 4, //!< Coded slice data partition C (NALunit type). AVC_AUT_IDR = 5, //!< Coded slice of an IDR picture (NALunit type). AVC_AUT_SEI = 6, //!< Supplemental enhancement information (SEI) (NALunit type). AVC_AUT_SEQPARAMS = 7, //!< Sequence parameter set (NALunit type). AVC_AUT_PICPARAMS = 8, //!< Picture parameter set (NALunit type). AVC_AUT_DELIMITER = 9, //!< Access unit delimiter (NALunit type). AVC_AUT_END_SEQUENCE = 10, //!< End of sequence (NALunit type). AVC_AUT_END_STREAM = 11, //!< End of stream (NALunit type). AVC_AUT_FILLER = 12, //!< Filler data (NALunit type). AVC_AUT_SEQPARAMSEXT = 13, //!< Sequence parameter set extension (NALunit type). AVC_AUT_PREFIX = 14, //!< Prefix NAL unit in scalable extension (NALunit type). AVC_AUT_SUBSETPARAMS = 15, //!< Subset sequence parameter set (NALunit type). AVC_AUT_SLICE_NOPART = 19, //!< Coded slice without partitioning (NALunit type). AVC_AUT_SLICE_SCALE = 20, //!< Coded slice in scalable extension (NALunit type). }; //--------------------------------------------------------------------- //! AVC SEI types //--------------------------------------------------------------------- enum { AVC_SEI_BUF_PERIOD = 0, //!< SEI type: buffering_period AVC_SEI_PIC_TIMING = 1, //!< SEI type: pic_timing AVC_SEI_PAN_SCAN_RECT = 2, //!< SEI type: pan_scan_rect AVC_SEI_FILLER_PAYLOAD = 3, //!< SEI type: filler_payload AVC_SEI_USER_DATA_REG = 4, //!< SEI type: user_data_registered_itu_t_t35 AVC_SEI_USER_DATA_UNREG = 5, //!< SEI type: user_data_unregistered AVC_SEI_RECOVERY_POINT = 6, //!< SEI type: recovery_point AVC_SEI_DEC_REF_PIC_MAR_REP = 7, //!< SEI type: dec_ref_pic_marking_repetition AVC_SEI_SPARE_PIC = 8, //!< SEI type: spare_pic AVC_SEI_SCENE_INFO = 9, //!< SEI type: scene_info AVC_SEI_SUB_SEQ_INFO = 10, //!< SEI type: sub_seq_info AVC_SEI_SUB_SEQ_LAYER_CHARS = 11, //!< SEI type: sub_seq_layer_characteristics AVC_SEI_SUB_SEQ_CHARS = 12, //!< SEI type: sub_seq_characteristics AVC_SEI_FFRAME_FREEZE = 13, //!< SEI type: full_frame_freeze AVC_SEI_FFRAME_FREEZE_RELEASE = 14, //!< SEI type: full_frame_freeze_release AVC_SEI_FFRAME_SNAPSHOT = 15, //!< SEI type: full_frame_snapshot AVC_SEI_PROG_REF_SEG_START = 16, //!< SEI type: progressive_refinement_segment_start AVC_SEI_PROG_REF_SEG_END = 17, //!< SEI type: progressive_refinement_segment_end AVC_SEI_MOTION_CSLICE_GROUP_SET = 18, //!< SEI type: motion_constrained_slice_group_set AVC_SEI_FILM_GRAIN_CHARS = 19, //!< SEI type: film_grain_characteristics AVC_SEI_DEBLOCK_FILTER_DISP_PREF = 20, //!< SEI type: deblocking_filter_display_preference AVC_SEI_STEREO_VIDEO_INFO = 21, //!< SEI type: stereo_video_info AVC_SEI_POST_FILTER_HINT = 22, //!< SEI type: post_filter_hint AVC_SEI_TONE_MAPPING_INFO = 23, //!< SEI type: tone_mapping_info AVC_SEI_SCALABILITY_INFO = 24, //!< SEI type: scalability_info AVC_SEI_SUB_PIC_SCALABLE_LAYER = 25, //!< SEI type: sub_pic_scalable_layer AVC_SEI_NON_REQUIRED_LAYER_REP = 26, //!< SEI type: non_required_layer_rep AVC_SEI_PRIORITY_LAYER_INFO = 27, //!< SEI type: priority_layer_info AVC_SEI_LAYERS_NOT_PRESENT = 28, //!< SEI type: layers_not_present AVC_SEI_LAYER_DEP_CHANGE = 29, //!< SEI type: layer_dependency_change AVC_SEI_SCALABLE_NESTING = 30, //!< SEI type: scalable_nesting AVC_SEI_BASE_LAYER_TEMPORAL_HRD = 31, //!< SEI type: base_layer_temporal_hrd AVC_SEI_QUALITY_LAYER_INTEG_CHECK = 32, //!< SEI type: quality_layer_integrity_check AVC_SEI_REDUNDANT_PIC_PROPERTY = 33, //!< SEI type: redundant_pic_property AVC_SEI_TL0_PICTURE_INDEX = 34, //!< SEI type: tl0_picture_index AVC_SEI_TL_SWITCHING_POINT = 35, //!< SEI type: tl_switching_point }; //! Size in bytes of a UUID in AVC SEI's. const size_t AVC_SEI_UUID_SIZE = 16; //--------------------------------------------------------------------- //! Stream type values, as used in the PMT. //--------------------------------------------------------------------- enum : uint8_t { ST_NULL = 0x00, //!< Invalid stream type value, used to indicate an absence of value ST_MPEG1_VIDEO = 0x01, //!< MPEG-1 Video ST_MPEG2_VIDEO = 0x02, //!< MPEG-2 Video ST_MPEG1_AUDIO = 0x03, //!< MPEG-1 Audio ST_MPEG2_AUDIO = 0x04, //!< MPEG-2 Audio ST_PRIV_SECT = 0x05, //!< MPEG-2 Private sections ST_PES_PRIV = 0x06, //!< MPEG-2 PES private data ST_MHEG = 0x07, //!< MHEG ST_DSMCC = 0x08, //!< DSM-CC ST_MPEG2_ATM = 0x09, //!< MPEG-2 over ATM ST_DSMCC_MPE = 0x0A, //!< DSM-CC Multi-Protocol Encapsulation ST_DSMCC_UN = 0x0B, //!< DSM-CC User-to-Network messages ST_DSMCC_SD = 0x0C, //!< DSM-CC Stream Descriptors ST_DSMCC_SECT = 0x0D, //!< DSM-CC Sections ST_MPEG2_AUX = 0x0E, //!< MPEG-2 Auxiliary ST_AAC_AUDIO = 0x0F, //!< Advanced Audio Coding (ISO 13818-7) ST_MPEG4_VIDEO = 0x10, //!< MPEG-4 Video ST_MPEG4_AUDIO = 0x11, //!< MPEG-4 Audio ST_MPEG4_PES = 0x12, //!< MPEG-4 SL or FlexMux in PES packets ST_MPEG4_SECT = 0x13, //!< MPEG-4 SL or FlexMux in sections ST_DSMCC_DLOAD = 0x14, //!< DSM-CC Synchronized Download Protocol ST_MDATA_PES = 0x15, //!< MPEG-7 MetaData in PES packets ST_MDATA_SECT = 0x16, //!< MPEG-7 MetaData in sections ST_MDATA_DC = 0x17, //!< MPEG-7 MetaData in DSM-CC Data Carousel ST_MDATA_OC = 0x18, //!< MPEG-7 MetaData in DSM-CC Object Carousel ST_MDATA_DLOAD = 0x19, //!< MPEG-7 MetaData in DSM-CC Sync Downl Proto ST_MPEG2_IPMP = 0x1A, //!< MPEG-2 IPMP stream ST_AVC_VIDEO = 0x1B, //!< AVC video ST_HEVC_VIDEO = 0x24, //!< HEVC video ST_HEVC_SUBVIDEO = 0x25, //!< HEVC temporal video subset of an HEVC video stream ST_IPMP = 0x7F, //!< IPMP stream ST_AC3_AUDIO = 0x81, //!< AC-3 Audio (ATSC only) ST_SCTE35_SPLICE = 0x86, //!< SCTE 35 splice information tables ST_EAC3_AUDIO = 0x87, //!< Enhanced-AC-3 Audio (ATSC only) }; //! //! Check if an stream type value indicates a PES stream. //! @param [in] st Stream type as used in the PMT. //! @return True if @a st indicates a PES stream. //! TSDUCKDLL bool IsPES(uint8_t st); //! //! Check if an stream type value indicates a video stream. //! @param [in] st Stream type as used in the PMT. //! @return True if @a st indicates a video stream. //! TSDUCKDLL bool IsVideoST(uint8_t st); //! //! Check if an stream type value indicates an audio stream. //! @param [in] st Stream type as used in the PMT. //! @return True if @a st indicates an audio stream. //! TSDUCKDLL bool IsAudioST(uint8_t st); //! //! Check if an stream type value indicates a stream carrying sections. //! @param [in] st Stream type as used in the PMT. //! @return True if @a st indicates a stream carrying sections. //! TSDUCKDLL bool IsSectionST(uint8_t st); //--------------------------------------------------------------------- // PSI, SI and data sections and tables //--------------------------------------------------------------------- //! Maximum size of a descriptor (255 + 2-byte header). const size_t MAX_DESCRIPTOR_SIZE = 257; //! Header size of a short section. const size_t SHORT_SECTION_HEADER_SIZE = 3; //! Header size of a long section. const size_t LONG_SECTION_HEADER_SIZE = 8; //! Size of the CRC32 field in a long section. const size_t SECTION_CRC32_SIZE = 4; //! Maximum size of a PSI section (MPEG-defined). const size_t MAX_PSI_SECTION_SIZE = 1024; //! Maximum size of a private section (including DVB-defined sections). const size_t MAX_PRIVATE_SECTION_SIZE = 4096; //! Minimum size of a short section. const size_t MIN_SHORT_SECTION_SIZE = SHORT_SECTION_HEADER_SIZE; //! Minimum size of a long section. const size_t MIN_LONG_SECTION_SIZE = LONG_SECTION_HEADER_SIZE + SECTION_CRC32_SIZE; //! Maximum size of the payload of a short section. const size_t MAX_PSI_SHORT_SECTION_PAYLOAD_SIZE = MAX_PSI_SECTION_SIZE - SHORT_SECTION_HEADER_SIZE; //! Maximum size of the payload of a PSI long section. const size_t MAX_PSI_LONG_SECTION_PAYLOAD_SIZE = MAX_PSI_SECTION_SIZE - LONG_SECTION_HEADER_SIZE - SECTION_CRC32_SIZE; //! Maximum size of the payload of a private short section. const size_t MAX_PRIVATE_SHORT_SECTION_PAYLOAD_SIZE = MAX_PRIVATE_SECTION_SIZE - SHORT_SECTION_HEADER_SIZE; //! Maximum size of the payload of a private long section. const size_t MAX_PRIVATE_LONG_SECTION_PAYLOAD_SIZE = MAX_PRIVATE_SECTION_SIZE - LONG_SECTION_HEADER_SIZE - SECTION_CRC32_SIZE; //--------------------------------------------------------------------- //! Table identification (TID) values //--------------------------------------------------------------------- enum : TID { // Valid in all MPEG contexts: TID_PAT = 0x00, //!< Table id for Program Association Table PAT TID_CAT = 0x01, //!< Table id for Conditional Access Table TID_PMT = 0x02, //!< Table id for Program Map Table TID_TSDT = 0x03, //!< Table id for Transport Stream Description Table TID_MP4SDT = 0x04, //!< Table id for MPEG-4 Scene Description Table TID_MP4ODT = 0x05, //!< Table id for MPEG-4 Object Descriptor Table TID_MDT = 0x06, //!< Table id for MetaData Table TID_DSMCC_MPE = 0x3A, //!< Table id for DSM-CC Multi-Protocol Encapsulated data TID_DSMCC_UNM = 0x3B, //!< Table id for DSM-CC User-to-Network Messages TID_DSMCC_DDM = 0x3C, //!< Table id for DSM-CC Download Data Messages TID_DSMCC_SD = 0x3D, //!< Table id for DSM-CC Stream Descriptors TID_DSMCC_PD = 0x3E, //!< Table id for DSM-CC Private Data TID_NULL = 0xFF, //!< Reserved table id value, end of TS packet PSI payload // Valid in DVB context: TID_NIT_ACT = 0x40, //!< Table id for Network Information Table - Actual network TID_NIT_OTH = 0x41, //!< Table id for Network Information Table - Other network TID_SDT_ACT = 0x42, //!< Table id for Service Description Table - Actual TS TID_SDT_OTH = 0x46, //!< Table id for Service Description Table - Other TS TID_BAT = 0x4A, //!< Table id for Bouquet Association Table TID_UNT = 0x4B, //!< Table id for Update Notification Table (SSU, ETSI TS 102 006) TID_INT = 0x4C, //!< Table id for IP/MAC Notification Table (MPE, ETSI EN 301 192) TID_EIT_PF_ACT = 0x4E, //!< Table id for EIT present/following - Actual network TID_EIT_PF_OTH = 0x4F, //!< Table id for EIT present/following - Other network TID_EIT_S_ACT_MIN = 0x50, //!< Table id for EIT schedule - Actual network TID_EIT_S_ACT_MAX = 0x5F, //!< Table id for EIT schedule - Actual network TID_EIT_S_OTH_MIN = 0x60, //!< Table id for EIT schedule - Other network TID_EIT_S_OTH_MAX = 0x6F, //!< Table id for EIT schedule - Other network TID_TDT = 0x70, //!< Table id for Time & Date Table TID_RST = 0x71, //!< Table id for Running Status Table TID_ST = 0x72, //!< Table id for Stuffing Table TID_TOT = 0x73, //!< Table id for Time Offset Table TID_AIT = 0x74, //!< Table id for Application Information Table (HbbTV, ETSI TS 102 809) TID_CT = 0x75, //!< Table id for Container Table (TV-Anytime) TID_RCT = 0x76, //!< Table id for Related Content Table (TV-Anytime) TID_CIT = 0x77, //!< Table id for Content Identifier Table (TV-Anytime) TID_MPE_FEC = 0x78, //!< Table id for MPE-FEC Table (Data Broadcasting) TID_RNT = 0x79, //!< Table id for Resolution Notification (TV-Anytime) TID_MPE_IFEC = 0x7A, //!< Table id for MPE-IFEC Table TID_DIT = 0x7E, //!< Table id for Discontinuity Information Table TID_SIT = 0x7F, //!< Table id for Selection Information Table TID_ECM_80 = 0x80, //!< Table id for ECM 80 TID_ECM_81 = 0x81, //!< Table id for ECM 81 TID_EMM_FIRST = 0x82, //!< Start of Table id range for EMM's TID_EMM_LAST = 0x8F, //!< End of Table id range for EMM's // Ranges by type TID_EIT_MIN = 0x4E, //!< Table id for EIT, first TID TID_EIT_MAX = 0x6F, //!< Table id for EIT, last TID TID_CAS_FIRST = 0x80, //!< Start of Table id range for CAS TID_CAS_LAST = 0x8F, //!< End of Table id range for CAS // Valid in SafeAccess CAS context: TID_SA_CECM_82 = 0x82, //!< Table id for SafeAccess Complementary ECM TID_SA_CECM_83 = 0x83, //!< Table id for SafeAccess Complementary ECM TID_SA_EMM_STB_U = 0x84, //!< Table id for SafeAccess STB or CI-CAM unique EMM TID_SA_EMM_STB_G = 0x85, //!< Table id for SafeAccess STB global EMM TID_SA_EMM_A = 0x86, //!< Table id for SafeAccess Global EMM ("all") TID_SA_EMM_U = 0x87, //!< Table id for SafeAccess Unique EMM TID_SA_EMM_S = 0x88, //!< Table id for SafeAccess Group EMM ("shared") TID_SA_EMM_CAM_G = 0x89, //!< Table id for SafeAccess CI-CAM global EMM TID_SA_RECM_8A = 0x8A, //!< Table id for SafeAccess Record ECM TID_SA_RECM_8B = 0x8B, //!< Table id for SafeAccess Record ECM TID_SA_EMM_T = 0x8F, //!< Table id for SafeAccess Technical EMM // Valid in Logiways context: TID_LW_DMT = 0x90, //!< Table id for Logiways Download Marker Table TID_LW_BDT = 0x91, //!< Table id for Logiways Binary Data Table TID_LW_VIT = 0x92, //!< Table id for Logiways VoD Information Table TID_LW_VCT = 0x93, //!< Table id for Logiways VoD Command Table // Valid in Viaccess CAS context: TID_VIA_EMM_FT_E = 0x86, //!< Table id for Viaccess EMM-FT (even) TID_VIA_EMM_FT_O = 0x87, //!< Table id for Viaccess EMM-FT (odd) TID_VIA_EMM_U = 0x88, //!< Table id for Viaccess EMM-U and EMM-D-U TID_VIA_EMM_GA_E = 0x8A, //!< Table id for Viaccess EMM-GA and EMM-D-GA (even) TID_VIA_EMM_GA_O = 0x8B, //!< Table id for Viaccess EMM-GA and EMM-D-GA (odd) TID_VIA_EMM_GH_E = 0x8C, //!< Table id for Viaccess EMM-GH (even) TID_VIA_EMM_GH_O = 0x8D, //!< Table id for Viaccess EMM-GH (odd) TID_VIA_EMM_S = 0x8E, //!< Table id for Viaccess EMM-S // Valid in MediaGuard CAS context: TID_MG_EMM_U = 0x82, //!< Table id for MediaGuard EMM-U TID_MG_EMM_A = 0x83, //!< Table id for MediaGuard EMM-A TID_MG_EMM_G = 0x84, //!< Table id for MediaGuard EMM-G TID_MG_EMM_I = 0x85, //!< Table id for MediaGuard EMM-I TID_MG_EMM_C = 0x86, //!< Table id for MediaGuard EMM-C TID_MG_EMM_CG = 0x89, //!< Table id for MediaGuard EMM-CG // Valid in ATSC / SCTE context: TID_SCTE35_SIT = 0xFC, //!< Table id for SCTE 35 Splice Information Table }; const size_t TID_MAX = 0x100; //!< Maximum number of TID values. //--------------------------------------------------------------------- //! Private data specifier (PDS) values //--------------------------------------------------------------------- enum { PDS_NAGRA = 0x00000009, //!< Private data specifier for Nagra (1). PDS_NAGRA_2 = 0x0000000A, //!< Private data specifier for Nagra (2). PDS_NAGRA_3 = 0x0000000B, //!< Private data specifier for Nagra (3). PDS_NAGRA_4 = 0x0000000C, //!< Private data specifier for Nagra (4). PDS_NAGRA_5 = 0x0000000D, //!< Private data specifier for Nagra (5). PDS_TPS = 0x00000010, //!< Private data specifier for TPS. PDS_EACEM = 0x00000028, //!< Private data specifier for EACEM / EICTA. PDS_EICTA = PDS_EACEM, //!< Private data specifier for EACEM / EICTA. PDS_LOGIWAYS = 0x000000A2, //!< Private data specifier for Logiways. PDS_CANALPLUS = 0x000000C0, //!< Private data specifier for Canal+. PDS_EUTELSAT = 0x0000055F, //!< Private data specifier for EutelSat. PDS_NULL = 0xFFFFFFFF, //!< An invalid private data specifier, can be used as placeholder. }; //! //! Enumeration description of PDS values. //! Typically used to implement PDS-related command line options. //! TSDUCKDLL extern const Enumeration PrivateDataSpecifierEnum; //--------------------------------------------------------------------- //! Descriptor tag values (descriptor identification, DID) //--------------------------------------------------------------------- enum : DID { // Valid in all MPEG contexts: DID_VIDEO = 0x02, //!< DID for video_stream_descriptor DID_AUDIO = 0x03, //!< DID for audio_stream_descriptor DID_HIERARCHY = 0x04, //!< DID for hierarchy_descriptor DID_REGISTRATION = 0x05, //!< DID for registration_descriptor DID_DATA_ALIGN = 0x06, //!< DID for data_stream_alignment_descriptor DID_TGT_BG_GRID = 0x07, //!< DID for target_background_grid_descriptor DID_VIDEO_WIN = 0x08, //!< DID for video_window_descriptor DID_CA = 0x09, //!< DID for CA_descriptor DID_LANGUAGE = 0x0A, //!< DID for ISO_639_language_descriptor DID_SYS_CLOCK = 0x0B, //!< DID for system_clock_descriptor DID_MUX_BUF_USE = 0x0C, //!< DID for multiplex_buffer_utilization_desc DID_COPYRIGHT = 0x0D, //!< DID for copyright_descriptor DID_MAX_BITRATE = 0x0E, //!< DID for maximum bitrate descriptor DID_PRIV_DATA_IND = 0x0F, //!< DID for private data indicator descriptor DID_SMOOTH_BUF = 0x10, //!< DID for smoothing buffer descriptor DID_STD = 0x11, //!< DID for STD_descriptor DID_IBP = 0x12, //!< DID for IBP_descriptor DID_CAROUSEL_IDENTIFIER = 0x13, //!< DID for DSM-CC carousel identifier descriptor DID_ASSOCIATION_TAG = 0x14, //!< DID for DSM-CC association tag descriptor DID_DEFERRED_ASSOC_TAGS = 0x15, //!< DID for DSM-CC deferred association tags descriptor DID_NPT_REFERENCE = 0x17, //!< DID for DSM-CC NPT reference descriptor DID_NPT_ENDPOINT = 0x18, //!< DID for DSM-CC NPT endpoint descriptor DID_STREAM_MODE = 0x19, //!< DID for DSM-CC stream mode descriptor DID_STREAM_EVENT = 0x1A, //!< DID for DSM-CC stream event descriptor DID_MPEG4_VIDEO = 0x1B, //!< DID for MPEG-4_video_descriptor DID_MPEG4_AUDIO = 0x1C, //!< DID for MPEG-4_audio_descriptor DID_IOD = 0x1D, //!< DID for IOD_descriptor DID_SL = 0x1E, //!< DID for SL_descriptor DID_FMC = 0x1F, //!< DID for FMC_descriptor DID_EXT_ES_ID = 0x20, //!< DID for External_ES_id_descriptor DID_MUXCODE = 0x21, //!< DID for MuxCode_descriptor DID_FMX_BUFFER_SIZE = 0x22, //!< DID for FmxBufferSize_descriptor DID_MUX_BUFFER = 0x23, //!< DID for MultiplexBuffer_descriptor DID_CONTENT_LABELING = 0x24, //!< DID for Content_labeling_descriptor DID_METADATA_ASSOC = 0x25, //!< DID for Metadata_association_descriptor DID_METADATA = 0x26, //!< DID for Metadata_descriptor DID_METADATA_STD = 0x27, //!< DID for Metadata_STD_descriptor DID_AVC_VIDEO = 0x28, //!< DID for AVC_video_descriptor DID_MPEG2_IPMP = 0x29, //!< DID for MPEG-2_IPMP_descriptor DID_AVC_TIMING_HRD = 0x2A, //!< DID for AVC_timing_and_HRD_descriptor DID_MPEG2_AAC_AUDIO = 0x2B, //!< DID for MPEG-2 AAC Audio descriptor DID_FLEX_MUX_TIMING = 0x2C, //!< DID for FlexMuxTiming descriptor DID_MPEG4_TEXT = 0x2D, //!< DID for MPEG-4 Text descriptor DID_MPEG4_AUDIO_EXT = 0x2E, //!< DID for MPEG-4 Audio Extension descriptor DID_AUX_VIDEO = 0x2F, //!< DID for Auxiliary Video Stream descriptor DID_SVC_EXT = 0x30, //!< DID for SVC Extension descriptor DID_MVC_EXT = 0x31, //!< DID for MVC Extension descriptor DID_J2K_VIDEO = 0x32, //!< DID for J2K Video descriptor DID_MVC_OPER_POINT = 0x33, //!< DID for MVC Operation Point descriptor DID_STEREO_VIDEO_FORMAT = 0x34, //!< DID for MPEG-2 Stereoscopic Video Format descriptor DID_STEREO_PROG_INFO = 0x35, //!< DID for Stereoscopic Program Info descriptor DID_STEREO_VIDEO_INFO = 0x36, //!< DID for Stereoscopic Video Info descriptor DID_TRANSPORT_PROFILE = 0x37, //!< DID for Transport Profile descriptor DID_HEVC_VIDEO = 0x38, //!< DID for HEVC Video descriptor DID_MPEG_EXTENSION = 0x3F, //!< DID for MPEG-2 Extension descriptor // Valid in DVB context: DID_NETWORK_NAME = 0x40, //!< DID for DVB network_name_descriptor DID_SERVICE_LIST = 0x41, //!< DID for DVB service_list_descriptor DID_STUFFING = 0x42, //!< DID for DVB stuffing_descriptor DID_SAT_DELIVERY = 0x43, //!< DID for DVB satellite_delivery_system_desc DID_CABLE_DELIVERY = 0x44, //!< DID for DVB cable_delivery_system_descriptor DID_VBI_DATA = 0x45, //!< DID for DVB VBI_data_descriptor DID_VBI_TELETEXT = 0x46, //!< DID for DVB VBI_teletext_descriptor DID_BOUQUET_NAME = 0x47, //!< DID for DVB bouquet_name_descriptor DID_SERVICE = 0x48, //!< DID for DVB service_descriptor DID_COUNTRY_AVAIL = 0x49, //!< DID for DVB country_availability_descriptor DID_LINKAGE = 0x4A, //!< DID for DVB linkage_descriptor DID_NVOD_REFERENCE = 0x4B, //!< DID for DVB NVOD_reference_descriptor DID_TIME_SHIFT_SERVICE = 0x4C, //!< DID for DVB time_shifted_service_descriptor DID_SHORT_EVENT = 0x4D, //!< DID for DVB short_event_descriptor DID_EXTENDED_EVENT = 0x4E, //!< DID for DVB extended_event_descriptor DID_TIME_SHIFT_EVENT = 0x4F, //!< DID for DVB time_shifted_event_descriptor DID_COMPONENT = 0x50, //!< DID for DVB component_descriptor DID_MOSAIC = 0x51, //!< DID for DVB mosaic_descriptor DID_STREAM_ID = 0x52, //!< DID for DVB stream_identifier_descriptor DID_CA_ID = 0x53, //!< DID for DVB CA_identifier_descriptor DID_CONTENT = 0x54, //!< DID for DVB content_descriptor DID_PARENTAL_RATING = 0x55, //!< DID for DVB parental_rating_descriptor DID_TELETEXT = 0x56, //!< DID for DVB teletext_descriptor DID_TELEPHONE = 0x57, //!< DID for DVB telephone_descriptor DID_LOCAL_TIME_OFFSET = 0x58, //!< DID for DVB local_time_offset_descriptor DID_SUBTITLING = 0x59, //!< DID for DVB subtitling_descriptor DID_TERREST_DELIVERY = 0x5A, //!< DID for DVB terrestrial_delivery_system_desc DID_MLINGUAL_NETWORK = 0x5B, //!< DID for DVB multilingual_network_name_desc DID_MLINGUAL_BOUQUET = 0x5C, //!< DID for DVB multilingual_bouquet_name_desc DID_MLINGUAL_SERVICE = 0x5D, //!< DID for DVB multilingual_service_name_desc DID_MLINGUAL_COMPONENT = 0x5E, //!< DID for DVB multilingual_component_descriptor DID_PRIV_DATA_SPECIF = 0x5F, //!< DID for DVB private_data_specifier_descriptor DID_SERVICE_MOVE = 0x60, //!< DID for DVB service_move_descriptor DID_SHORT_SMOOTH_BUF = 0x61, //!< DID for DVB short_smoothing_buffer_descriptor DID_FREQUENCY_LIST = 0x62, //!< DID for DVB frequency_list_descriptor DID_PARTIAL_TS = 0x63, //!< DID for DVB partial_transport_stream_desc DID_DATA_BROADCAST = 0x64, //!< DID for DVB data_broadcast_descriptor DID_SCRAMBLING = 0x65, //!< DID for DVB scrambling_descriptor DID_DATA_BROADCAST_ID = 0x66, //!< DID for DVB data_broadcast_id_descriptor DID_TRANSPORT_STREAM = 0x67, //!< DID for DVB transport_stream_descriptor DID_DSNG = 0x68, //!< DID for DVB DSNG_descriptor DID_PDC = 0x69, //!< DID for DVB PDC_descriptor DID_AC3 = 0x6A, //!< DID for DVB AC-3_descriptor DID_ANCILLARY_DATA = 0x6B, //!< DID for DVB ancillary_data_descriptor DID_CELL_LIST = 0x6C, //!< DID for DVB cell_list_descriptor DID_CELL_FREQ_LINK = 0x6D, //!< DID for DVB cell_frequency_link_descriptor DID_ANNOUNCE_SUPPORT = 0x6E, //!< DID for DVB announcement_support_descriptor DID_APPLI_SIGNALLING = 0x6F, //!< DID for DVB application_signalling_descriptor DID_ADAPTFIELD_DATA = 0x70, //!< DID for DVB adaptation_field_data_descriptor DID_SERVICE_ID = 0x71, //!< DID for DVB service_identifier_descriptor DID_SERVICE_AVAIL = 0x72, //!< DID for DVB service_availability_descriptor DID_DEFAULT_AUTHORITY = 0x73, //!< DID for DVB default_authority_descriptor DID_RELATED_CONTENT = 0x74, //!< DID for DVB related_content_descriptor DID_TVA_ID = 0x75, //!< DID for DVB TVA_id_descriptor DID_CONTENT_ID = 0x76, //!< DID for DVB content_identifier_descriptor DID_TIME_SLICE_FEC_ID = 0x77, //!< DID for DVB time_slice_fec_identifier_desc DID_ECM_REPETITION_RATE = 0x78, //!< DID for DVB ECM_repetition_rate_descriptor DID_S2_SAT_DELIVERY = 0x79, //!< DID for DVB S2_satellite_delivery_system_descriptor DID_ENHANCED_AC3 = 0x7A, //!< DID for DVB enhanced_AC-3_descriptor DID_DTS = 0x7B, //!< DID for DVB DTS_descriptor DID_AAC = 0x7C, //!< DID for DVB AAC_descriptor DID_XAIT_LOCATION = 0x7D, //!< DID for DVB XAIT_location_descriptor (DVB-MHP) DID_FTA_CONTENT_MGMT = 0x7E, //!< DID for DVB FTA_content_management_descriptor DID_DVB_EXTENSION = 0x7F, //!< DID for DVB extension_descriptor // Valid in an AIT (Application Information Table, ETSI TS 102 809): DID_AIT_APPLICATION = 0x00, //!< DID for AIT application_descriptor. DID_AIT_APP_NAME = 0x01, //!< DID for AIT application_name_descriptor. DID_AIT_TRANSPORT_PROTO = 0x02, //!< DID for AIT transport_protocol_descriptor. DID_AIT_DVBJ_APP = 0x03, //!< DID for AIT dvb_j_application_descriptor. DID_AIT_DVBJ_APP_LOC = 0x04, //!< DID for AIT dvb_j_application_location_descriptor. DID_AIT_EXT_APP_AUTH = 0x05, //!< DID for AIT external_application_authorisation_descriptor. DID_AIT_APP_RECORDING = 0x06, //!< DID for AIT application_recording_descriptor. DID_AIT_HTML_APP = 0x08, //!< DID for AIT dvb_html_application_descriptor. DID_AIT_HTML_APP_LOC = 0x09, //!< DID for AIT dvb_html_application_location_descriptor. DID_AIT_HTML_APP_BOUND = 0x0A, //!< DID for AIT dvb_html_application_boundary_descriptor. DID_AIT_APP_ICONS = 0x0B, //!< DID for AIT application_icons_descriptor. DID_AIT_PREFETCH = 0x0C, //!< DID for AIT prefetch_descriptor. DID_AIT_DII_LOCATION = 0x0D, //!< DID for AIT DII_location_descriptor. DID_AIT_APP_STORAGE = 0x10, //!< DID for AIT application_storage_descriptor. DID_AIT_IP_SIGNALLING = 0x11, //!< DID for AIT IP_signalling_descriptor. DID_AIT_GRAPHICS_CONST = 0x14, //!< DID for AIT graphics_constraints_descriptor. DID_AIT_APP_LOCATION = 0x15, //!< DID for AIT simple_application_location_descriptor. DID_AIT_APP_USAGE = 0x16, //!< DID for AIT application_usage_descriptor. DID_AIT_APP_BOUNDARY = 0x17, //!< DID for AIT simple_application_boundary_descriptor. // Valid in an INT (IP/MAC Notification Table, ETSI EN 301 192): DID_INT_SMARTCARD = 0x06, //!< DID for INT target_smartcard_descriptor DID_INT_MAC_ADDR = 0x07, //!< DID for INT target_MAC_address_descriptor DID_INT_SERIAL_NUM = 0x08, //!< DID for INT target_serial_number_descriptor DID_INT_IP_ADDR = 0x09, //!< DID for INT target_IP_address_descriptor DID_INT_IPV6_ADDR = 0x0A, //!< DID for INT target_IPv6_address_descriptor DID_INT_PF_NAME = 0x0C, //!< DID for INT IP/MAC_platform_name_descriptor DID_INT_PF_PROVIDER = 0x0D, //!< DID for INT IP/MAC_platform_provider_name_descriptor DID_INT_MAC_ADDR_RANGE = 0x0E, //!< DID for INT target_MAC_address_range_descriptor DID_INT_IP_SLASH = 0x0F, //!< DID for INT target_IP_slash_descriptor DID_INT_IP_SRC_SLASH = 0x10, //!< DID for INT target_IP_source_slash_descriptor DID_INT_IPV6_SLASH = 0x11, //!< DID for INT target_IPv6_slash_descriptor DID_INT_IPV6_SRC_SLASH = 0x12, //!< DID for INT target_IPv6_source_slash_descriptor DID_INT_STREAM_LOC = 0x13, //!< DID for INT IP/MAC_stream_location_descriptor DID_INT_ISP_ACCESS = 0x14, //!< DID for INT ISP_access_mode_descriptor DID_INT_GEN_STREAM_LOC = 0x15, //!< DID for INT IP/MAC_generic_stream_location_descriptor // Valid in a UNT (Update Notification Table, ETSI TS 102 006): DID_UNT_SCHEDULING = 0x01, //!< DID for UNT scheduling_descriptor DID_UNT_UPDATE = 0x02, //!< DID for UNT update_descriptor DID_UNT_SSU_LOCATION = 0x03, //!< DID for UNT ssu_location_descriptor DID_UNT_MESSAGE = 0x04, //!< DID for UNT message_descriptor DID_UNT_SSU_EVENT_NAME = 0x05, //!< DID for UNT ssu_event_name_descriptor DID_UNT_SMARTCARD = 0x06, //!< DID for UNT target_smartcard_descriptor DID_UNT_MAC_ADDR = 0x07, //!< DID for UNT target_MAC_address_descriptor DID_UNT_SERIAL_NUM = 0x08, //!< DID for UNT target_serial_number_descriptor DID_UNT_IP_ADDR = 0x09, //!< DID for UNT target_IP_address_descriptor DID_UNT_IPV6_ADDR = 0x0A, //!< DID for UNT target_IPv6_address_descriptor DID_UNT_SUBGROUP_ASSOC = 0x0B, //!< DID for UNT ssu_subgroup_association_descriptor DID_UNT_ENHANCED_MSG = 0x0C, //!< DID for UNT enhanced_message_descriptor DID_UNT_SSU_URI = 0x0D, //!< DID for UNT ssu_uri_descriptor // Valid in a SIT (Splice Information Table, SCTE 35). DID_SPLICE_AVAIL = 0x00, //!< DID for SCTE 35 SIT avail_descriptor DID_SPLICE_DTMF = 0x01, //!< DID for SCTE 35 SIT DTMF_descriptor DID_SPLICE_SEGMENT = 0x02, //!< DID for SCTE 35 SIT segmentation_descriptor DID_SPLICE_TIME = 0x03, //!< DID for SCTE 35 SIT time_descriptor // Valid in ATSC / SCTE context: DID_ATSC_STUFFING = 0X80, //!< DID for ATSC stuffing_descriptor DID_AC3_AUDIO_STREAM = 0x81, //!< DID for ATSC ac3_audio_stream_descriptor DID_ATSC_PID = 0x85, //!< DID for ATSC program_identifier_descriptor DID_CAPTION = 0x86, //!< DID for ATSC caption_service_descriptor DID_CONTENT_ADVIS = 0x87, //!< DID for ATSC content_advisory_descriptor DID_CUE_IDENTIFIER = 0x8A, //!< DID for SCTE 35 cue_identifier_descriptor DID_EXT_CHAN_NAME = 0xA0, //!< DID for ATSC extended_channel_name_descriptor DID_SERV_LOCATION = 0xA1, //!< DID for ATSC service_location_descriptor DID_ATSC_TIME_SHIFT = 0xA2, //!< DID for ATSC time_shifted_event_descriptor DID_COMPONENT_NAME = 0xA3, //!< DID for ATSC component_name_descriptor DID_ATSC_DATA_BRDCST = 0xA4, //!< DID for ATSC data_broadcast_descriptor DID_PID_COUNT = 0xA5, //!< DID for ATSC pid_count_descriptor DID_DOWNLOAD = 0xA6, //!< DID for ATSC download_descriptor DID_MPROTO_ENCAPS = 0xA7, //!< DID for ATSC multiprotocol_encapsulation_desc // Valid after PDS_LOGIWAYS private_data_specifier DID_LW_SUBSCRIPTION = 0x81, //!< DID for Logiways subscription_descriptor DID_LW_SCHEDULE = 0xB0, //!< DID for Logiways schedule_descriptor DID_LW_PRIV_COMPONENT = 0xB1, //!< DID for Logiways private_component_descriptor DID_LW_PRIV_LINKAGE = 0xB2, //!< DID for Logiways private_linkage_descriptor DID_LW_CHAPTER = 0xB3, //!< DID for Logiways chapter_descriptor DID_LW_DRM = 0xB4, //!< DID for Logiways DRM_descriptor DID_LW_VIDEO_SIZE = 0xB5, //!< DID for Logiways video_size_descriptor DID_LW_EPISODE = 0xB6, //!< DID for Logiways episode_descriptor DID_LW_PRICE = 0xB7, //!< DID for Logiways price_descriptor DID_LW_ASSET_REFERENCE = 0xB8, //!< DID for Logiways asset_reference_descriptor DID_LW_CONTENT_CODING = 0xB9, //!< DID for Logiways content_coding_descriptor DID_LW_VOD_COMMAND = 0xBA, //!< DID for Logiways vod_command_descriptor DID_LW_DELETION_DATE = 0xBB, //!< DID for Logiways deletion_date_descriptor DID_LW_PLAY_LIST = 0xBC, //!< DID for Logiways play_list_descriptor DID_LW_PLAY_LIST_ENTRY = 0xBD, //!< DID for Logiways play_list_entry_descriptor DID_LW_ORDER_CODE = 0xBE, //!< DID for Logiways order_code_descriptor DID_LW_BOUQUET_REFERENCE = 0xBF, //!< DID for Logiways bouquet_reference_descriptor // Valid after PDS_EUTELSAT private_data_specifier DID_EUTELSAT_CHAN_NUM = 0x83, //!< DID for eutelsat_channel_number_descriptor // Valid after PDS_EACEM/EICTA private_data_specifier DID_LOGICAL_CHANNEL_NUM = 0x83, //!< DID for EACEM/EICTA logical_channel_number_descriptor DID_PREF_NAME_LIST = 0x84, //!< DID for EACEM/EICTA preferred_name_list_descriptor DID_PREF_NAME_ID = 0x85, //!< DID for EACEM/EICTA preferred_name_identifier_descriptor DID_EACEM_STREAM_ID = 0x86, //!< DID for EACEM/EICTA eacem_stream_identifier_descriptor DID_HD_SIMULCAST_LCN = 0x88, //!< DID for EACEM/EICTA HD_simulcast_logical_channel_number_descriptor // Valid after PDS_CANALPLUS private_data_specifier DID_DTG_STREAM_IND = 0x80, //!< DID for Canal+ DTG_Stream_indicator_descriptor DID_PIO_OFFSET_TIME = 0X80, //!< DID for Canal+ pio_offset_time_descriptor DID_LOGICAL_CHANNEL_81 = 0x81, //!< DID for Canal+ logical_channel_descriptor DID_PRIVATE2 = 0x82, //!< DID for Canal+ private_descriptor2 DID_LOGICAL_CHANNEL = 0x83, //!< DID for Canal+ logical_channel_descriptor DID_PIO_CONTENT = 0x83, //!< DID for Canal+ pio_content_descriptor DID_PIO_LOGO = 0x84, //!< DID for Canal+ pio_logo_descriptor DID_ADSL_DELIVERY = 0x85, //!< DID for Canal+ adsl_delivery_system_descriptor DID_PIO_FEE = 0x86, //!< DID for Canal+ pio_fee_descriptor DID_PIO_EVENT_RANGE = 0x88, //!< DID for Canal+ pio_event_range_descriptor DID_PIO_COPY_MANAGEMENT = 0x8B, //!< DID for Canal+ pio_copy_management_descriptor DID_PIO_COPY_CONTROL = 0x8C, //!< DID for Canal+ pio_copy_control_descriptor DID_PIO_PPV = 0x8E, //!< DID for Canal+ pio_ppv_descriptor DID_PIO_STB_SERVICE_ID = 0x90, //!< DID for Canal+ pio_stb_service_id_descriptor DID_PIO_MASKING_SERV_ID = 0x91, //!< DID for Canal+ pio_masking_service_id_descriptor DID_PIO_STB_SERVMAP_UPD = 0x92, //!< DID for Canal+ pio_stb_service_map_update_desc DID_NEW_SERVICE_LIST = 0x93, //!< DID for Canal+ new_service_list_descriptor DID_MESSAGE_NAGRA = 0x94, //!< DID for Canal+ message_descriptor_Nagra DID_ITEM_EVENT = 0xA1, //!< DID for Canal+ item_event_descriptor DID_ITEM_ZAPPING = 0xA2, //!< DID for Canal+ item_zapping_descriptor DID_APPLI_MESSAGE = 0xA3, //!< DID for Canal+ appli_message_descriptor DID_LIST = 0xA4, //!< DID for Canal+ list_descriptor DID_KEY_LIST = 0xB0, //!< DID for Canal+ key_list_descriptor DID_PICTURE_SIGNALLING = 0xB1, //!< DID for Canal+ picture_signalling_descriptor DID_COUNTER_BB = 0xBB, //!< DID for Canal+ counter_descriptor DID_DATA_COMPONENT_BD = 0xBD, //!< DID for Canal+ data_component_descriptor DID_SYSTEM_MGMT_BE = 0xBE, //!< DID for Canal+ system_management_descriptor DID_VO_LANGUAGE = 0xC0, //!< DID for Canal+ vo_language_descriptor DID_DATA_LIST = 0xC1, //!< DID for Canal+ data_list_descriptor DID_APPLI_LIST = 0xC2, //!< DID for Canal+ appli_list_descriptor DID_MESSAGE = 0xC3, //!< DID for Canal+ message_descriptor DID_FILE = 0xC4, //!< DID for Canal+ file_descriptor DID_RADIO_FORMAT = 0xC5, //!< DID for Canal+ radio_format_descriptor DID_APPLI_STARTUP = 0xC6, //!< DID for Canal+ appli_startup_descriptor DID_PATCH = 0xC7, //!< DID for Canal+ patch_descriptor DID_LOADER = 0xC8, //!< DID for Canal+ loader_descriptor DID_CHANNEL_MAP_UPDATE = 0xC9, //!< DID for Canal+ channel_map_update_descriptor DID_PPV = 0xCA, //!< DID for Canal+ ppv_descriptor DID_COUNTER_CB = 0xCB, //!< DID for Canal+ counter_descriptor DID_OPERATOR_INFO = 0xCC, //!< DID for Canal+ operator_info_descriptor DID_SERVICE_DEF_PARAMS = 0xCD, //!< DID for Canal+ service_default_parameters_desc DID_FINGER_PRINTING = 0xCE, //!< DID for Canal+ finger_printing_descriptor DID_FINGER_PRINTING_V2 = 0xCF, //!< DID for Canal+ finger_printing_descriptor_v2 DID_CONCEALED_GEO_ZONES = 0xD0, //!< DID for Canal+ concealed_geo_zones_descriptor DID_COPY_PROTECTION = 0xD1, //!< DID for Canal+ copy_protection_descriptor DID_MG_SUBSCRIPTION = 0xD3, //!< DID for Canal+ subscription_descriptor DID_CABLE_BACKCH_DELIV = 0xD4, //!< DID for Canal+ cable_backchannel_delivery_system DID_INTERACT_SNAPSHOT = 0xD5, //!< DID for Canal+ Interactivity_snapshot_descriptor DID_ICON_POSITION = 0xDC, //!< DID for Canal+ icon_position_descriptor DID_ICON_PIXMAP = 0xDD, //!< DID for Canal+ icon_pixmap_descriptor DID_ZONE_COORDINATE = 0xDE, //!< DID for Canal+ Zone_coordinate_descriptor DID_HD_APP_CONTROL_CODE = 0xDF, //!< DID for Canal+ HD_application_control_code_desc DID_EVENT_REPEAT = 0xE0, //!< DID for Canal+ Event_Repeat_descriptor DID_PPV_V2 = 0xE1, //!< DID for Canal+ PPV_V2_descriptor DID_HYPERLINK_REF = 0xE2, //!< DID for Canal+ Hyperlink_ref_descriptor DID_SHORT_SERVICE = 0xE4, //!< DID for Canal+ Short_service_descriptor DID_OPERATOR_TELEPHONE = 0xE5, //!< DID for Canal+ Operator_telephone_descriptor DID_ITEM_REFERENCE = 0xE6, //!< DID for Canal+ Item_reference_descriptor DID_MH_PARAMETERS = 0xE9, //!< DID for Canal+ MH_Parameters_descriptor DID_LOGICAL_REFERENCE = 0xED, //!< DID for Canal+ Logical_reference_descriptor DID_DATA_VERSION = 0xEE, //!< DID for Canal+ Data_Version_descriptor DID_SERVICE_GROUP = 0xEF, //!< DID for Canal+ Service_group_descriptor DID_STREAM_LOC_TRANSP = 0xF0, //!< DID for Canal+ Stream_Locator_Transport_desc DID_DATA_LOCATOR = 0xF1, //!< DID for Canal+ Data_Locator_descriptor DID_RESIDENT_APP = 0xF2, //!< DID for Canal+ resident_application_descriptor DID_RESIDENT_APP_SIGNAL = 0xF3, //!< DID for Canal+ Resident_Application_Signalling DID_MH_LOGICAL_REF = 0xF8, //!< DID for Canal+ MH_Logical_Reference_descriptor DID_RECORD_CONTROL = 0xF9, //!< DID for Canal+ record_control_descriptor DID_CMPS_RECORD_CONTROL = 0xFA, //!< DID for Canal+ cmps_record_control_descriptor DID_EPISODE = 0xFB, //!< DID for Canal+ episode_descriptor DID_CMP_SELECTION = 0xFC, //!< DID for Canal+ CMP_Selection_descriptor DID_DATA_COMPONENT_FD = 0xFD, //!< DID for Canal+ data_component_descriptor DID_SYSTEM_MGMT_FE = 0xFE, //!< DID for Canal+ system_management_descriptor }; //--------------------------------------------------------------------- //! MPEG extended descriptor tag values (in MPEG extension_descriptor) //--------------------------------------------------------------------- enum : DID { MPEG_EDID_OBJ_DESC_UPD = 0x02, //!< Ext.DID for ObjectDescriptorUpdate. MPEG_EDID_HEVC_TIM_HRD = 0x03, //!< Ext.DID for HEVC_timing_and_HRD_descriptor. MPEG_EDID_NULL = 0xFF, //!< Invalid EDID value, can be used as placeholder. }; //--------------------------------------------------------------------- //! DVB extended descriptor tag values (in DVB extension_descriptor) //--------------------------------------------------------------------- enum : DID { EDID_IMAGE_ICON = 0x00, //!< Ext.DID for image_icon_descriptor EDID_CPCM_DELIVERY_SIG = 0x01, //!< Ext.DID for cpcm_delivery_signalling_descriptor EDID_CP = 0x02, //!< Ext.DID for CP_descriptor EDID_CP_IDENTIFIER = 0x03, //!< Ext.DID for CP_identifier_descriptor EDID_T2_DELIVERY = 0x04, //!< Ext.DID for T2_delivery_system_descriptor EDID_SH_DELIVERY = 0x05, //!< Ext.DID for SH_delivery_system_descriptor EDID_SUPPL_AUDIO = 0x06, //!< Ext.DID for supplementary_audio_descriptor EDID_NETW_CHANGE_NOTIFY = 0x07, //!< Ext.DID for network_change_notify_descriptor EDID_MESSAGE = 0x08, //!< Ext.DID for message_descriptor EDID_TARGET_REGION = 0x09, //!< Ext.DID for target_region_descriptor EDID_TARGET_REGION_NAME = 0x0A, //!< Ext.DID for target_region_name_descriptor EDID_SERVICE_RELOCATED = 0x0B, //!< Ext.DID for service_relocated_descriptor EDID_XAIT_PID = 0x0C, //!< Ext.DID for XAIT_PID_descriptor EDID_C2_DELIVERY = 0x0D, //!< Ext.DID for C2_delivery_system_descriptor EDID_DTS_HD_AUDIO = 0x0E, //!< Ext.DID for DTS_HD_audio_stream_descriptor EDID_DTS_NEURAL = 0x0F, //!< Ext.DID for DTS_Neural_descriptor EDID_VIDEO_DEPTH_RANGE = 0x10, //!< Ext.DID for video_depth_range_descriptor EDID_T2MI = 0x11, //!< Ext.DID for T2MI_descriptor EDID_URI_LINKAGE = 0x13, //!< Ext.DID for URI_linkage_descriptor EDID_CI_ANCILLARY_DATA = 0x14, //!< Ext.DID for CI_ancillary_data_descriptor EDID_AC4 = 0x15, //!< Ext.DID for AC4_descriptor EDID_C2_BUNDLE_DELIVERY = 0x16, //!< Ext.DID for C2_bundle_system_delivery_descriptor EDID_NULL = 0xFF, //!< Invalid EDID value, can be used as placeholder. }; //--------------------------------------------------------------------- //! Linkage type values (in linkage_descriptor) //--------------------------------------------------------------------- enum : uint8_t { LINKAGE_INFO = 0x01, //!< Information service LINKAGE_EPG = 0x02, //!< EPG service LINKAGE_CA_REPLACE = 0x03, //!< CA replacement service LINKAGE_TS_NIT_BAT = 0x04, //!< TS containing complet network/bouquet SI LINKAGE_SERVICE_REPLACE = 0x05, //!< Service replacement service LINKAGE_DATA_BROADCAST = 0x06, //!< Data broadcast service LINKAGE_RCS_MAP = 0x07, //!< RCS map LINKAGE_HAND_OVER = 0x08, //!< Mobile hand-over LINKAGE_SSU = 0x09, //!< System software update service LINKAGE_SSU_TABLE = 0x0A, //!< TS containing SSU BAT or NIT LINKAGE_IP_NOTIFY = 0x0B, //!< IP/MAC notification service LINKAGE_INT_BAT_NIT = 0x0C, //!< TS containing INT BAT or NIT LINKAGE_EVENT = 0x0D, //!< Event linkage LINKAGE_EXT_EVENT_MIN = 0x0E, //!< Extented event linkage, first value LINKAGE_EXT_EVENT_MAX = 0x1F, //!< Extented event linkage, last value }; //--------------------------------------------------------------------- //! Scrambling mode values (in scrambling_descriptor) //--------------------------------------------------------------------- enum : uint8_t { SCRAMBLING_DVB_CSA1 = 0x01, //!< DVB-CSA1 SCRAMBLING_DVB_CSA2 = 0x02, //!< DVB-CSA2 SCRAMBLING_DVB_CSA3_STD = 0x03, //!< DVB-CSA3, standard mode SCRAMBLING_DVB_CSA3_MIN = 0x04, //!< DVB-CSA3, minimally enhanced mode SCRAMBLING_DVB_CSA3_FULL = 0x05, //!< DVB-CSA3, fully enhanced mode SCRAMBLING_DVB_CISSA1 = 0x10, //!< DVB-CISSA v1 SCRAMBLING_ATIS_IIF_IDSA = 0x70, //!< ATIS IIF IDSA for MPEG-2 TS }; //--------------------------------------------------------------------- //! Data broadcast id values (in data_broadcast[_id]_descriptor) //--------------------------------------------------------------------- enum : uint16_t { DBID_DATA_PIPE = 0x0001, //!< Data pipe DBID_ASYNC_DATA_STREAM = 0x0002, //!< Asynchronous data stream DBID_SYNC_DATA_STREAM = 0x0003, //!< Synchronous data stream DBID_SYNCED_DATA_STREAM = 0x0004, //!< Synchronised data stream DBID_MPE = 0x0005, //!< Multi protocol encapsulation DBID_DATA_CSL = 0x0006, //!< Data Carousel DBID_OBJECT_CSL = 0x0007, //!< Object Carousel DBID_ATM = 0x0008, //!< DVB ATM streams DBID_HP_ASYNC_DATA_STREAM = 0x0009, //!< Higher Protocols based on asynchronous data streams DBID_SSU = 0x000A, //!< System Software Update service [TS 102 006] DBID_IPMAC_NOTIFICATION = 0x000B, //!< IP/MAC Notification service [EN 301 192] DBID_MHP_OBJECT_CSL = 0x00F0, //!< MHP Object Carousel DBID_MHP_MPE = 0x00F1, //!< Reserved for MHP Multi Protocol Encapsulation DBID_EUTELSAT_DATA_PIPE = 0x0100, //!< Eutelsat Data Piping DBID_EUTELSAT_DATA_STREAM = 0x0101, //!< Eutelsat Data Streaming DBID_SAGEM_IP = 0x0102, //!< SAGEM IP encapsulation in MPEG-2 PES packets DBID_BARCO_DATA_BRD = 0x0103, //!< BARCO Data Broadcasting DBID_CIBERCITY_MPE = 0x0104, //!< CyberCity Multiprotocol Encapsulation DBID_CYBERSAT_MPE = 0x0105, //!< CyberSat Multiprotocol Encapsulation DBID_TDN = 0x0106, //!< The Digital Network DBID_OPENTV_DATA_CSL = 0x0107, //!< OpenTV Data Carousel DBID_PANASONIC = 0x0108, //!< Panasonic DBID_KABEL_DEUTSCHLAND = 0x0109, //!< Kabel Deutschland DBID_TECHNOTREND = 0x010A, //!< TechnoTrend Gorler GmbH DBID_MEDIAHIGHWAY_SSU = 0x010B, //!< NDS France Technologies system software download DBID_GUIDE_PLUS = 0x010C, //!< GUIDE Plus+ Rovi Corporation DBID_ACAP_OBJECT_CSL = 0x010D, //!< ACAP Object Carousel DBID_MICRONAS = 0x010E, //!< Micronas Download Stream DBID_POLSAT = 0x0110, //!< Televizja Polsat DBID_DTG = 0x0111, //!< UK DTG DBID_SKYMEDIA = 0x0112, //!< SkyMedia DBID_INTELLIBYTE = 0x0113, //!< Intellibyte DataBroadcasting DBID_TELEWEB_DATA_CSL = 0x0114, //!< TeleWeb Data Carousel DBID_TELEWEB_OBJECT_CSL = 0x0115, //!< TeleWeb Object Carousel DBID_TELEWEB = 0x0116, //!< TeleWeb DBID_BBC = 0x0117, //!< BBC DBID_ELECTRA = 0x0118, //!< Electra Entertainment Ltd DBID_BBC_2_3 = 0x011A, //!< BBC 2 - 3 DBID_TELETEXT = 0x011B, //!< Teletext DBID_SKY_DOWNLOAD_1_5 = 0x0120, //!< Sky Download Streams 1-5 DBID_ICO = 0x0121, //!< ICO mim DBID_CIPLUS_DATA_CSL = 0x0122, //!< CI+ Data Carousel DBID_HBBTV = 0x0123, //!< HBBTV Carousel DBID_ROVI_PREMIUM = 0x0124, //!< Premium Content from Rovi Corporation DBID_MEDIA_GUIDE = 0x0125, //!< Media Guide from Rovi Corporation DBID_INVIEW = 0x0126, //!< InView Technology Ltd DBID_BOTECH = 0x0130, //!< Botech Elektronik SAN. ve TIC. LTD.STI. DBID_SCILLA_PUSHVOD_CSL = 0x0131, //!< Scilla Push-VOD Carousel DBID_CANAL_PLUS = 0x0140, //!< Canal+ DBID_OIPF_OBJECT_CSL = 0x0150, //!< OIPF Object Carousel - Open IPTV Forum DBID_4TV = 0x4444, //!< 4TV Data Broadcast DBID_NOKIA_IP_SSU = 0x4E4F, //!< Nokia IP based software delivery DBID_BBG_DATA_CSL = 0xBBB1, //!< BBG Data Caroussel DBID_BBG_OBJECT_CSL = 0xBBB2, //!< BBG Object Caroussel DBID_BBG = 0xBBBB, //!< Bertelsmann Broadband Group }; //--------------------------------------------------------------------- //! DVB-assigned Bouquet Identifier values //--------------------------------------------------------------------- enum : uint16_t { BID_TVNUMERIC = 0x0086, //!< Bouquet id for TV Numeric on French TNT network BID_TVNUMERIC_EUTELSAT = 0xC030, //!< Bouquet id for TV Numeric on Eutelsat network BID_TVNUMERIC_ASTRA = 0xC031, //!< Bouquet id for TV Numeric on Astra network }; //--------------------------------------------------------------------- //! DVB-assigned CA System Identifier values //--------------------------------------------------------------------- enum : uint16_t { CASID_MEDIAGUARD_MIN = 0x0100, //!< Minimum CAS Id value for MediaGuard. CASID_MEDIAGUARD_MAX = 0x01FF, //!< Maximum CAS Id value for MediaGuard. CASID_VIACCESS_MIN = 0x0500, //!< Minimum CAS Id value for Viaccess. CASID_VIACCESS_MAX = 0x05FF, //!< Maximum CAS Id value for Viaccess. CASID_NAGRA_MIN = 0x1800, //!< Minimum CAS Id value for Nagravision. CASID_NAGRA_MAX = 0x18FF, //!< Maximum CAS Id value for Nagravision. CASID_THALESCRYPT_MIN = 0x4A80, //!< Minimum CAS Id value for ThalesCrypt. CASID_THALESCRYPT_MAX = 0x4A8F, //!< Maximum CAS Id value for ThalesCrypt. CASID_SAFEACCESS = 0x4ADC, //!< CAS Id value for SafeAccess. }; //--------------------------------------------------------------------- //! DVB-assigned Network Identifier values //--------------------------------------------------------------------- enum : uint16_t { NID_TNT_FRANCE = 0x20FA, //!< Network id for the French national terrestrial network. }; //--------------------------------------------------------------------- //! IEEE-assigned Organizationally Unique Identifier (OUI) values //--------------------------------------------------------------------- enum { OUI_DVB = 0x00015A, //!< OUI for Digital Video Broadcasting OUI_SKARDIN = 0x001222, //!< OUI for Skardin (UK) OUI_LOGIWAYS = 0x002660, //!< OUI for Logiways }; //--------------------------------------------------------------------- //! DVB-MHP transport protocol ids. //--------------------------------------------------------------------- enum : uint16_t { MHP_PROTO_CAROUSEL = 0x0001, //!< MHP Object Carousel MHP_PROTO_MPE = 0x0002, //!< IP via DVB-MPE MHP_PROTO_HTTP = 0x0003, //!< HTTP over interaction channel }; //--------------------------------------------------------------------- // T2-MI (DVB-T2 Modulator Interface) //--------------------------------------------------------------------- //! //! Size in bytes of a T2-MI packet header. //! const size_t T2MI_HEADER_SIZE = 6; //! //! T2-MI packet types. //! @see ETSI EN 102 773, section 5.1. //! enum : uint8_t { T2MI_BASEBAND_FRAME = 0x00, //!< Baseband Frame. T2MI_AUX_IQ_DATA = 0x01, //!< Auxiliary stream I/Q data. T2MI_ARBITRARY_CELL = 0x02, //!< Arbitrary cell insertion. T2MI_L1_CURRENT = 0x10, //!< L1-current. T2MI_L1_FUTURE = 0x11, //!< L1-future. T2MI_P2_BIAS_BALANCING = 0x12, //!< P2 bias balancing cells. T2MI_DVBT2_TIMESTAMP = 0x20, //!< DVB-T2 timestamp. T2MI_INDIVIDUAL_ADDRESSING = 0x21, //!< Individual addressing. T2MI_FEF_NULL = 0x30, //!< FEF part: Null. T2MI_FEF_IQ_DATA = 0x31, //!< FEF part: I/Q data. T2MI_FEF_COMPOSITE = 0x32, //!< FEF part: composite. T2MI_FEF_SUBPART = 0x33, //!< FEF sub-part. T2MI_INVALID_TYPE = 0xFF //!< Invalid T2MI packet (non standard value). }; //! //! Size in bytes of a DVB-T2 Base Band Header. //! See ETSI EN 302 765, section 5.1.7. //! const size_t T2_BBHEADER_SIZE = 10; //--------------------------------------------------------------------- // Teletext PES packets. // See ETSI EN 300 472 V1.3.1, "DVB; Specification for conveying ITU-R // System B Teletext in DVB bitstreams" //--------------------------------------------------------------------- //! //! Size in bytes of a Teletext packet. //! const size_t TELETEXT_PACKET_SIZE = 44; const uint8_t TELETEXT_PES_FIRST_EBU_DATA_ID = 0x10; //!< First EBU data_identifier value in PES packets conveying Teletext. const uint8_t TELETEXT_PES_LAST_EBU_DATA_ID = 0x1F; //!< Last EBU data_identifier value in PES packets conveying Teletext. //! //! Teletext data unit ids. //! @see ETSI EN 300 472 //! enum : uint8_t { TELETEXT_DATA_UNIT_ID_NON_SUBTITLE = 0x02, //!< Data_unit_id for EBU Teletext non-subtitle data. TELETEXT_DATA_UNIT_ID_SUBTITLE = 0x03, //!< Data_unit_id for EBU Teletext subtitle data. TELETEXT_DATA_UNIT_ID_INVERTED = 0x0C, //!< Data_unit_id for EBU EBU Teletext Inverted (extension ?). TELETEXT_DATA_UNIT_ID_VPS = 0xC3, //!< Data_unit_id for VPS (extension ?). TELETEXT_DATA_UNIT_ID_CLOSED_CAPTIONS = 0xC5, //!< Data_unit_id for Closed Caption (extension ?). TELETEXT_DATA_UNIT_ID_STUFFING = 0xFF, //!< Data_unit_id for stuffing data. }; }
54.419263
131
0.596786
[ "object" ]
f07cb9138ff6c4ed1cfc54ccbe8e76d3ee99a3af
3,731
h
C
Engine/source/gfx/gl/gfxGLTextureObject.h
Parcons/Torque3D
516163fd5debea9c91b558046d858f5f56fc198d
[ "MIT" ]
null
null
null
Engine/source/gfx/gl/gfxGLTextureObject.h
Parcons/Torque3D
516163fd5debea9c91b558046d858f5f56fc198d
[ "MIT" ]
null
null
null
Engine/source/gfx/gl/gfxGLTextureObject.h
Parcons/Torque3D
516163fd5debea9c91b558046d858f5f56fc198d
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #ifndef _GFXGLTEXTUREOBJECT_H #define _GFXGLTEXTUREOBJECT_H #include "gfx/gfxTextureObject.h" #include "gfx/gl/tGL/tGL.h" #include "gfx/gfxStateBlock.h" class GFXGLDevice; class GFXGLTextureObject : public GFXTextureObject { public: GFXGLTextureObject(GFXDevice * aDevice, GFXTextureProfile *profile); ~GFXGLTextureObject(); void release(); void reInit(); inline GLuint getHandle() const { return mHandle; } inline GLenum getBinding() const { return mBinding; } inline GLuint getBuffer() const { return mBuffer; } inline bool isZombie() const { return mIsZombie; } /// Binds the texture to the given texture unit /// and applies the current sampler state because GL tracks /// filtering and wrapper per object, while GFX tracks per sampler. void bind(U32 textureUnit); /// @return An array containing the texture data /// @note You are responsible for deleting the returned data! (Use delete[]) U8* getTextureData( U32 mip = 0); virtual F32 getMaxUCoord() const; virtual F32 getMaxVCoord() const; void reloadFromCache(); ///< Reloads texture from zombie cache, used by GFXGLTextureManager to resurrect the texture. #ifdef TORQUE_DEBUG virtual void pureVirtualCrash() {} #endif /// Get/set data from texture (for dynamic textures and render targets) /// @attention DO NOT READ FROM THE RETURNED RECT! It is not guaranteed to work and may incur significant performance penalties. virtual GFXLockedRect* lock(U32 mipLevel = 0, RectI *inRect = NULL); virtual void unlock(U32 mipLevel = 0 ); virtual bool copyToBmp(GBitmap *); ///< Not implemented bool mIsNPoT2; // GFXResource interface virtual void zombify(); virtual void resurrect(); virtual const String describeSelf() const; void initSamplerState(const GFXSamplerStateDesc &ssd); private: friend class GFXGLTextureManager; typedef GFXTextureObject Parent; /// Internal GL object GLuint mHandle; GLuint mBuffer; bool mNeedInitSamplerState; GFXSamplerStateDesc mSampler; GLenum mBinding; U32 mBytesPerTexel; GFXLockedRect mLockedRect; RectI mLockedRectRect; /// Pointer to owner device GFXGLDevice* mGLDevice; bool mIsZombie; U8* mZombieCache; void copyIntoCache(); //FrameAllocator U32 mFrameAllocatorMark; #ifdef TORQUE_DEBUG U32 mFrameAllocatorMarkGuard; #endif U8 *mFrameAllocatorPtr; }; #endif
33.3125
131
0.704369
[ "render", "object" ]
f07d718dd6e3481bd0befa4d13ce6190f0924f15
26,280
c
C
Older_Versions/OpenVLC1.3_revA/kernel/openvlc.c
Andregarciav/OpenVLC
3213190700a2a4e4e313b4a6eb72161fd021d349
[ "BSD-3-Clause" ]
52
2018-10-13T16:39:35.000Z
2022-03-19T18:16:54.000Z
Older_Versions/OpenVLC1.3_revA/kernel/openvlc.c
Andregarciav/OpenVLC
3213190700a2a4e4e313b4a6eb72161fd021d349
[ "BSD-3-Clause" ]
6
2021-06-25T14:42:29.000Z
2021-06-25T21:37:43.000Z
Older_Versions/OpenVLC1.3_revA/kernel/openvlc.c
Andregarciav/OpenVLC
3213190700a2a4e4e313b4a6eb72161fd021d349
[ "BSD-3-Clause" ]
28
2018-10-13T16:39:52.000Z
2022-03-28T19:19:51.000Z
/* Copyright (c) 2014, IMDEA NETWORKS Institute This file is part of the OpenVLC's source codes. OpenVLC's source codes are free: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenVLC's source codes are distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the source codes of OpenVLC. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/sched.h> #include <linux/interrupt.h> // mark_bh #include <linux/in.h> #include <linux/netdevice.h> // struct device, and other headers #include <linux/skbuff.h> #include <linux/in6.h> #include <linux/delay.h> #include <linux/miscdevice.h> #include <linux/gpio.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/mm.h> #include <linux/fs.h> #include <linux/types.h> #include <linux/moduleparam.h> #include <linux/slab.h> #include <linux/errno.h> #include <linux/ioctl.h> #include <linux/cdev.h> #include <linux/string.h> #include <linux/list.h> #include <linux/pci.h> #include <asm/uaccess.h> #include <asm/atomic.h> #include <asm/unistd.h> #include <asm/io.h> #include <asm/delay.h> #include <linux/iio/consumer.h> #include <linux/iio/iio.h> #include <asm/checksum.h> #include <linux/kthread.h> #include <linux/err.h> #include <linux/wait.h> #include <linux/timex.h> #include <linux/clk.h> #include <linux/pinctrl/consumer.h> #include <linux/hrtimer.h> #include <linux/ktime.h> #include <linux/module.h> #include <asm/io.h> // ioremap #include <linux/proc_fs.h> #include <linux/skbuff.h> #include <linux/ip.h> #include <linux/tcp.h> #include <linux/if_arp.h> #include <linux/rslib.h> #include "openvlc.h" #define DEVICE_NAME "vlc" // start for ioctl #include <linux/fs.h> // required for various structures related to files liked fops. #include <linux/semaphore.h> #include <linux/cdev.h> // end for ioctl #include <linux/device.h> // Header to support the kernel Driver Model #include <linux/version.h> #if LINUX_VERSION_CODE == KERNEL_VERSION(4,14,71) #define KERNEL_V4_14_71 1 #else #define KERNEL_V4_14_71 0 #endif #define MAC 0 #define APP 1 static int mac_or_app = 1; module_param(mac_or_app, int, 1); static int block_size = 200; module_param(block_size, int, 0); uint16_t par[ECC_LEN]; int ecc_symsize = 8; int ecc_poly = 0x11d; // the Reed Solomon control structure static struct rs_control *rs_decoder; // Module params static int rx = 0; static int dst_id = 8; static int self_id = 7; static int flag_exit = 0; static int flag_lock = 0; static int mtu = 1500; module_param(flag_lock, int, 0); module_param(self_id, int, 0); module_param(dst_id, int, 0); module_param(rx, int, 0); module_param(mtu, int, 0); const char *name = "any"; // Tasks static struct task_struct *task_mac_tx = NULL; static struct task_struct *task_phy_decoding = NULL; static struct task_struct *task_frames_pru = NULL; // For DATA frame #define DB_BYTE_LEN 2000 #define DB_SYMBOL_LEN 2000*16 static unsigned char data_buffer_byte[DB_BYTE_LEN]; static _Bool data_buffer_symbol[DB_SYMBOL_LEN]; static int data_buffer_byte_len = 0; static int data_buffer_symbol_len = 0; static int tx_data_curr_index = 0; MODULE_AUTHOR("Ander GALISTEO/Diego JUARA"); MODULE_LICENSE("Dual BSD/GPL"); // April 04 enum state {SENSING, RX, TX, ILLUM, CHM, NONE} ; // Short sensing is implemented in tx state enum state phy_state; /////////////////// PRU variables /////////////////////////////////// #define PRU_ADDR 0x4A300000 #define PRU0 0x00000000 #define PRU1 0x00002000 #define PRU_SHARED 0x00010000 unsigned int *tx_pru; unsigned int *rx_pru; struct net_device *vlc_devs; struct vlc_packet { struct vlc_packet *next; struct net_device *dev; int datalen; u8 data[2000+10]; }; struct vlc_packet *tx_pkt; struct vlc_packet *rx_pkt_check_dup; struct vlc_packet *rx_pkt; int pool_size = 10; module_param(pool_size, int, 0); struct vlc_priv { struct net_device_stats stats; int status; struct vlc_packet *ppool; int rx_int_enabled; struct vlc_packet *tx_queue; // List of tx packets int tx_packetlen; u8 *tx_packetdata; struct sk_buff *skb; spinlock_t lock; struct net_device *dev; }; static struct vlchdr *vlc_hdr(const struct sk_buff *skb) { return (struct vlchdr *) skb_mac_header(skb); } int vlc_header(struct sk_buff *skb, struct net_device *dev, unsigned short type, const void *daddr, const void *saddr, unsigned len) { struct vlchdr *vlc = (struct vlchdr *)skb_push(skb, VLC_HLEN); vlc->h_proto = htons(type); memcpy(vlc->h_source, saddr ? saddr : dev->dev_addr, dev->addr_len); memcpy(vlc->h_dest, daddr ? daddr : dev->dev_addr, dev->addr_len); vlc->h_dest[MAC_ADDR_LEN-1] ^= 0x01; /* dest is us xor 1 */ return (dev->hard_header_len); } static const struct header_ops vlc_header_ops= { .create = vlc_header //.rebuild = vlc_rebuild_header }; // Return statistics to the caller struct net_device_stats *vlc_stats(struct net_device *dev) { struct vlc_priv *priv = netdev_priv(dev); return &priv->stats; } // Configuration changes (passed on by ifconfig) int vlc_config(struct net_device *dev, struct ifmap *map) { if (dev->flags & IFF_UP) // can't act on a running interface return -EBUSY; // Don't allow changing the I/O address if (map->base_addr != dev->base_addr) { printk(KERN_WARNING "snull: Can't change I/O address\n"); return -EOPNOTSUPP; } // Allow changing the IRQ if (map->irq != dev->irq) { dev->irq = map->irq; // request_irq() is delayed to open-time } // ignore other fields return 0; } // Ioctl commands int vlc_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { //printk("ioctl\n"); return 0; } //Buffer/pool management. struct vlc_packet *vlc_get_tx_buffer(struct net_device *dev) { struct vlc_priv *priv = netdev_priv(dev); //unsigned long flags; struct vlc_packet *pkt; if (flag_lock) spin_lock_bh(&priv->lock); pkt = priv->ppool; priv->ppool = pkt->next; if (priv->ppool == NULL) { printk(KERN_INFO "The MAC layer queue is full!\n"); netif_stop_queue(dev); } if (flag_lock) spin_unlock_bh(&priv->lock); return pkt; } void vlc_release_buffer(struct vlc_packet *pkt) { //unsigned long flags; struct vlc_priv *priv = netdev_priv(pkt->dev); if (flag_lock) spin_lock_bh(&priv->lock); pkt->next = priv->ppool; priv->ppool = pkt; if (flag_lock) spin_unlock_bh(&priv->lock); if (netif_queue_stopped(pkt->dev) && pkt->next == NULL && flag_exit == 0) netif_wake_queue(pkt->dev); } // Departure a packet from the end of the MAC queue (FIFO) struct vlc_packet *vlc_dequeue_pkt(struct net_device *dev) { //unsigned long flags; struct vlc_priv *priv = netdev_priv(dev); struct vlc_packet *pkt; if (flag_lock) spin_lock_bh(&priv->lock); pkt = priv->tx_queue; if (pkt != NULL) priv->tx_queue = pkt->next; if (flag_lock) spin_unlock_bh(&priv->lock); printk("Dequeue a packet!\n"); return pkt; } // Add a packet from upper layer to the beginning of the MAC queue void vlc_enqueue_pkt(struct net_device *dev, struct vlc_packet *pkt) { //unsigned long flags; struct vlc_priv *priv = netdev_priv(dev); struct vlc_packet *last_pkt; /// Fix the misorder packets if (flag_lock) spin_lock_bh(&priv->lock); last_pkt = priv->tx_queue; if (last_pkt == NULL) { priv->tx_queue = pkt; // Enqueue the new packet } else { while (last_pkt != NULL && last_pkt->next != NULL) { last_pkt = last_pkt->next; } last_pkt->next = pkt; // Put new the pkt to the end of the queue } if (flag_lock) spin_unlock_bh(&priv->lock); printk("Enqueue a packet!\n"); /// } int vlc_tx(struct sk_buff *skb, struct net_device *dev) { struct vlc_packet *tmp_pkt;// TODO Commented so that it doesn't return! #if(KERNEL_V4_14_71) netif_trans_update(dev); // 9.4 linux version #else dev->trans_start = jiffies; //8.7 linux version #endif tmp_pkt = vlc_get_tx_buffer(dev); tmp_pkt->next = NULL; tmp_pkt->datalen = skb->len; memcpy(tmp_pkt->data, skb->data, skb->len); vlc_enqueue_pkt(dev, tmp_pkt); dev_kfree_skb(skb); return 0; // Our simple device can not fail } int vlc_release(struct net_device *dev) { netif_stop_queue(dev); // can't transmit any more return 0; } int vlc_open(struct net_device *dev) { memcpy(dev->dev_addr, "\0\2", MAC_ADDR_LEN); netif_start_queue(dev); return 0; } static const struct net_device_ops vlc_netdev_ops = { .ndo_open = vlc_open, .ndo_stop = vlc_release, .ndo_start_xmit = vlc_tx, .ndo_do_ioctl = vlc_ioctl, .ndo_set_config = vlc_config, .ndo_get_stats = vlc_stats, }; // Setup VLC network device void vlc_setup(struct net_device *dev) { dev->hard_header_len = VLC_HLEN; dev->mtu = mtu; dev->tx_queue_len = 100; dev->priv_flags |= IFF_TX_SKB_SHARING; } //Enable and disable receive interrupts. static void vlc_rx_ints(struct net_device *dev, int enable) { struct vlc_priv *priv = netdev_priv(dev); priv->rx_int_enabled = enable; } //Set up a device's packet pool. void vlc_setup_pool(struct net_device *dev) { struct vlc_priv *priv = netdev_priv(dev); int i; struct vlc_packet *pkt; priv->ppool = NULL; for (i = 0; i < pool_size; i++) { pkt = kmalloc (sizeof (struct vlc_packet), GFP_KERNEL); if (pkt == NULL) { printk (KERN_NOTICE "Ran out of memory allocating packet pool\n"); return; } pkt->dev = dev; pkt->next = priv->ppool; priv->ppool = pkt; } } __be16 vlc_type_trans(struct sk_buff *skb, struct net_device *dev) { struct vlchdr *vlc; skb->dev = dev; skb_reset_mac_header(skb); skb_pull_inline(skb, VLC_HLEN); vlc = vlc_hdr(skb); if (ntohs(vlc->h_proto) >= 1536) return vlc->h_proto; return htons(VLC_P_DEFAULT); } static void construct_frame_header(char* buffer, int buffer_len, int payload_len) { int i; //unsigned short crc; for (i=0; i<PREAMBLE_LEN; i++) buffer[i] = 0xaa; // Preamble // SFD buffer[1]= 0xae; // Added to synchronize correctly with the frame buffer[PREAMBLE_LEN] = 0xa3; //10100011 0110011010100101 // Length of payload buffer[PREAMBLE_LEN+1] = (unsigned char) ((payload_len>>8) & 0xff); buffer[PREAMBLE_LEN+2] = (unsigned char) (payload_len & 0xff); // Destination address buffer[PREAMBLE_LEN+3] = (unsigned char) ((dst_id>>8) & 0xff); buffer[PREAMBLE_LEN+4] = (unsigned char) (dst_id & 0xff); // Source address buffer[PREAMBLE_LEN+5] = (unsigned char) ((self_id>>8) & 0xff); buffer[PREAMBLE_LEN+6] = (unsigned char) (self_id & 0xff); // CRC //crc = crc16(buffer+PREAMBLE_LEN+SFD_LEN, MAC_HDR_LEN+payload_len); //buffer[buffer_len-2] = (char) ((0xff00&crc)>>8); // CRC byte 1 //buffer[buffer_len-1] = (char) ((0x00ff&crc)); // CRC byte 2 } static void OOK_with_Manchester_RLL(char *buffer_before_coding, _Bool *buffer_after_coding, int len_before_coding) { int byte_index, symbol_index = 0; unsigned char curr_byte, mask; // Convert the preamble -- OOK w/o Manchester RLL code for (byte_index=0; byte_index<PREAMBLE_LEN; byte_index++) { mask = 0x80; curr_byte = buffer_before_coding[byte_index] & 0xff; while (mask) { buffer_after_coding[symbol_index++] = (_Bool) (curr_byte & mask); mask >>= 1; } } // Convert the parts after the preamble -- OOK w Manchester RLL code for (byte_index=PREAMBLE_LEN; byte_index<len_before_coding; byte_index++) { mask = 0x80; curr_byte = buffer_before_coding[byte_index] & 0xff; while (mask) { if ((_Bool) (curr_byte & mask)) { // Bit 1 -- LOW-HIGH buffer_after_coding[symbol_index++] = false; buffer_after_coding[symbol_index++] = true; } else { // Bit 0 -- HIGH-LOW buffer_after_coding[symbol_index++] = true; buffer_after_coding[symbol_index++] = false; } mask >>= 1; } } } static int write_to_pru(_Bool *symbols_to_send, int symbol_length) { unsigned int mask = 0x80000000, actual_value = 0; int ind_pru = 1, i = 0; while(i<symbol_length) { if(symbols_to_send[i]) actual_value += mask; mask = mask >> 1; if((mask==0)||(i==(symbol_length-1))) { tx_pru[ind_pru++]=actual_value; //printk("%x",actual_value); /*mask = 0x80000000; while(mask!=0) { if(mask&actual_value) { printk("1"); }else{ printk("0"); } mask = mask >> 1; }*/ actual_value = 0; mask = 0x80000000; } i++; } tx_pru[0]=data_buffer_symbol_len; return ind_pru-1; } static void generate_DATA_frame(struct vlc_packet *pkt) { //printk("VLC: Generating DATA frame\n"); int i, payload_len, index_block, encoded_len, num_of_blocks = 0, symbol_last_index = 0, group_32bit = 0; payload_len = pkt->datalen-(MAC_HDR_LEN-OCTET_LEN); encoded_len = payload_len+2*MAC_ADDR_LEN+PROTOCOL_LEN; // Calculate the number of blocks if (encoded_len % block_size) num_of_blocks = encoded_len / block_size + 1; else num_of_blocks = encoded_len / block_size; data_buffer_byte_len = FRAME_LEN_WO_PAYLOAD + payload_len + ECC_LEN*(num_of_blocks-1); memset (data_buffer_byte, 0, sizeof (unsigned char) * data_buffer_byte_len); data_buffer_symbol_len = (data_buffer_byte_len-PREAMBLE_LEN)*8*2 + PREAMBLE_LEN*8 + 1; // Send a BIT more, why? -- Avoid phy error if (data_buffer_byte==NULL || data_buffer_symbol==NULL) { printk ("Ran out of memory generating new frames.\n"); return; } // Construct a new data frame memcpy(data_buffer_byte+PREAMBLE_LEN+SFD_LEN+OCTET_LEN, pkt->data, pkt->datalen); // Copy the payload vlc_release_buffer(pkt); // Return the buffer to the pool construct_frame_header(data_buffer_byte, data_buffer_byte_len, data_buffer_symbol_len);//construct_frame_header(data_buffer_byte, data_buffer_byte_len, payload_len); /// Encode the blocks of a frame for (index_block = 0; index_block < num_of_blocks; index_block++) { for (i = 0; i < ECC_LEN; i++) par[i] = 0; if (index_block < num_of_blocks-1) { encode_rs8(rs_decoder, data_buffer_byte+PREAMBLE_LEN+SFD_LEN+OCTET_LEN+index_block*block_size, block_size, par, 0); } else { encode_rs8(rs_decoder, data_buffer_byte+PREAMBLE_LEN+SFD_LEN+OCTET_LEN+index_block*block_size, encoded_len%block_size, par, 0); } for (i = 0; i < ECC_LEN; i++) data_buffer_byte[FRAME_LEN_WO_PAYLOAD+payload_len+(index_block-1)*ECC_LEN+i] = par[i]; } //Show data after coding /*for(i = 7;i<=data_buffer_byte_len;i++) { int mask = 0x00000080; unsigned int last = data_buffer_byte[i]; //printk("%x",last); while(mask!=0) { if(mask&last) { printk("1"); }else{ printk("0"); } mask = mask >> 1; } //printk("Data val %d\n",rx_data[i+2]); }*/ //printk("\n\n"); // Encoding the frame OOK_with_Manchester_RLL(data_buffer_byte, data_buffer_symbol, data_buffer_byte_len); tx_data_curr_index = data_buffer_symbol_len; //printk("VLC-> Data current index: %d\n",data_buffer_symbol_len); group_32bit = write_to_pru(data_buffer_symbol, tx_data_curr_index); } static int mac_tx(void *data) { struct vlc_priv *priv = netdev_priv(vlc_devs); int backoff_timer = 0; start: for (; ;) { if (kthread_should_stop()) { goto ret; } if(phy_state == TX) { if (mac_or_app == APP) { if ((!priv->tx_queue) | (tx_pru[0]!=0)) { usleep_range(20,50); goto start; } else{ tx_pkt = vlc_dequeue_pkt(vlc_devs); /// Transmit the packet generate_DATA_frame(tx_pkt); // Generate MAC frame } }else if (mac_or_app == MAC) { } } } ret: printk("\n=======EXIT mac_tx=======\n"); return 0; } //Receive a packet: retrieve, encapsulate and pass over to upper levels void mac_rx(struct net_device *dev, struct vlc_packet *pkt) { struct sk_buff *skb; struct vlc_priv *priv = netdev_priv(dev); skb = dev_alloc_skb(pkt->datalen + 2); if (!skb) { if (printk_ratelimit()) printk(KERN_NOTICE "snull rx: low on mem - packet dropped\n"); priv->stats.rx_dropped++; goto out; } skb_reserve(skb, 2); // align IP on 16B boundary memcpy(skb_put(skb, pkt->datalen), pkt->data, pkt->datalen); // Write metadata, and then pass to the receive level skb->dev = dev; skb->protocol = vlc_type_trans(skb, dev); skb->ip_summed = CHECKSUM_UNNECESSARY; // don't check it priv->stats.tx_packets++; priv->stats.tx_bytes += pkt->datalen; netif_rx(skb); //kfree(pkt); out: return; } static int cmp_packets(char *pkt_1, char *pkt_2, int len) { int i = 0; for (i=0; i<len; i++) { if (pkt_1[i] != pkt_2[i]) return 1; // Packets are not equal } return 0; // Packets are equal } static void get_the_data_rx(char * rx_data) { uint16_t par_rx[ECC_LEN]; struct vlc_priv *priv = netdev_priv(vlc_devs); unsigned int payload_len_rx = ((rx_data[0] & 0xff) << 8) | (rx_data[1] & 0xff); int encoded_len = payload_len_rx+2*MAC_ADDR_LEN+PROTOCOL_LEN; int num_of_blocks; int i,index_block, num_err=0; int j = OCTET_LEN+2*MAC_ADDR_LEN+PROTOCOL_LEN+payload_len_rx; int total_num_err = 0; // Calculate the number of blocks if (encoded_len % block_size) num_of_blocks = encoded_len / block_size + 1; else num_of_blocks = encoded_len / block_size; //printk("payload_len_rx=%d\n",payload_len_rx); //return; for (index_block=0; index_block < num_of_blocks; index_block++) { for (i = 0; i < ECC_LEN; i++) { par_rx[i] = rx_data[j+index_block*ECC_LEN+i]; //printk(" %02x", par[i]); } if (index_block < num_of_blocks-1) { num_err = decode_rs8(rs_decoder, rx_data+OCTET_LEN+index_block*block_size, par_rx, block_size, NULL, 0, NULL, 0, NULL); } else { // The last block num_err = decode_rs8(rs_decoder, rx_data+OCTET_LEN+index_block*block_size, par_rx, encoded_len % block_size, NULL, 0, NULL, 0, NULL); } if (num_err < 0) { printk("*** ECC error. ***\n"); //f_adjust_slot = 1; goto end; } total_num_err += num_err; } if (total_num_err > 0) { //printk("*** Has corrected %d error(s) *** ", total_num_err); } if (payload_len_rx>0) { // Data frame if (mac_or_app == APP) {// To upper layer //rx_pkt = kmalloc (sizeof (struct vlc_packet), GFP_KERNEL); rx_pkt->datalen = MAC_HDR_LEN-OCTET_LEN+payload_len_rx; // Copy the received data (omit the datalen octet) memcpy(rx_pkt->data, rx_data+OCTET_LEN, rx_pkt->datalen); if (cmp_packets(rx_pkt->data,rx_pkt_check_dup->data,rx_pkt->datalen)) { // Frist copy the packet; the rx_pkt will be released in max_rx memcpy(rx_pkt_check_dup->data, rx_pkt->data, rx_pkt->datalen); rx_pkt_check_dup->datalen = rx_pkt->datalen; mac_rx(vlc_devs, rx_pkt); //printk("Sent to the Internet layer.\n"); priv->stats.rx_packets++; priv->stats.rx_bytes += rx_pkt->datalen;/**/ } //else printk("Repeated packet\n"); } } end: return; } static int phy_decoding(void *data) { char rx_data[2000]; int symbol_len,byte_len,thelen1,thelen2,numofblocks, len_bit, group_32bit, rest_32bit, j = 0; int i=0; unsigned int last, current_reg, value, bits, l, mask; for (; ;) { if(rx_pru[0] != 0){ symbol_len = rx_pru[1]; //printk("Symbols received : %d\n",rx_pru[1]); if((symbol_len > 32000) || (symbol_len < 200)) // To avoid false frames { rx_pru[0] = 0; rx_pru[1] = 0; goto payload_error; } byte_len = ((symbol_len-1-32)/16)+3; len_bit = ((symbol_len-81)/2); // subtract 73 = 24 (preamble) + 16 (SFD) + 32 (length) + 1 (added at TX) group_32bit = (len_bit+31)/32; // add 31 to round up rest_32bit = len_bit%(32); j=1; while(j<1000){//todo! numofblocks=j; thelen1=(byte_len-28)-16*(j-1); if (thelen1%200) numofblocks=(thelen1+6)/200 +1; else numofblocks=(thelen1+6)/200; if (numofblocks==j) break; j++; } if((thelen1>mtu)||(thelen1<0)) // To avoid false frames { rx_pru[0] = 0; rx_pru[1] = 0; goto payload_error; } rx_data[0] = ((thelen1 >> 8) & 0xFF); rx_data[1] = (thelen1 & 0xFF); //printk("Payload %d\n", thelen1); memcpy(&rx_data[2],&rx_pru[2],group_32bit*sizeof(unsigned int)); // //Show data before decoding /*for(i = 2;i<group_32bit*sizeof(unsigned int);i++) { mask = 0x00000080; last = rx_data[i]; while(mask!=0) { if(mask&last) { printk("1"); }else{ printk("0"); } mask = mask >> 1; } }*/ //printk("\n\n"); rx_pru[0] = 0; get_the_data_rx(rx_data); }else{ payload_error: usleep_range(20,50); } error: if (kthread_should_stop()) goto ret; } ret: printk("\n=======EXIT phy_decoding=======\n"); return 0; } void vlc_init(struct net_device *dev) { struct vlc_priv *priv; dev->addr_len = MAC_ADDR_LEN; dev->type = ARPHRD_LOOPBACK ; // ARPHRD_IEEE802154 vlc_setup(dev); // assign some of the fields dev->netdev_ops = &vlc_netdev_ops; dev->header_ops = &vlc_header_ops; // keep the default flags, just add NOARP dev->flags |= IFF_NOARP; dev->features |= NETIF_F_HW_CSUM; priv = netdev_priv(dev); memset(priv, 0, sizeof(struct vlc_priv)); if (mac_or_app == APP) { vlc_rx_ints(dev, 1); /* enable receive interrupts */ tx_pkt = kmalloc (sizeof (struct vlc_packet), GFP_KERNEL); rx_pkt = kmalloc (sizeof (struct vlc_packet), GFP_KERNEL); rx_pkt_check_dup = kmalloc (sizeof (struct vlc_packet), GFP_KERNEL); if (tx_pkt==NULL || rx_pkt_check_dup==NULL || rx_pkt==NULL) { printk (KERN_NOTICE "Ran out of memory allocating packet pool\n"); return ; } rx_pkt_check_dup->datalen = 0; vlc_setup_pool(dev); priv->tx_queue = NULL; flag_exit = 0; } } void vlc_teardown_pool(struct net_device *dev) { struct vlc_priv *priv = netdev_priv(dev); struct vlc_packet *pkt; //unsigned long flags; while ((pkt = priv->ppool)) { priv->ppool = pkt->next; if (pkt) kfree (pkt); /* FIXME - in-flight packets ? */ } } void vlc_cleanup(void) { struct vlc_packet *pkt; struct vlc_priv *priv = netdev_priv(vlc_devs); int ret; flag_exit = 1; netif_stop_queue(vlc_devs); // Clean the threads if (task_mac_tx) { ret = kthread_stop(task_mac_tx); if(!ret) printk(KERN_INFO "Thread stopped\n"); task_mac_tx = NULL; } if (task_phy_decoding) { ret = kthread_stop(task_phy_decoding); if(!ret) printk(KERN_INFO "Thread stopped\n"); task_phy_decoding = NULL; } ///////////// Unmap memory for communicating with PRU /////////// memunmap(tx_pru); memunmap(rx_pru); printk("Memory unmapped correctly\n"); //Clean devices if (vlc_devs) { if (mac_or_app == APP) { printk("Cleaning the pool\n"); while(priv->tx_queue) { pkt = vlc_dequeue_pkt(vlc_devs); vlc_release_buffer(pkt); } vlc_teardown_pool(vlc_devs); kfree(rx_pkt); kfree(rx_pkt_check_dup); kfree(tx_pkt); } printk("unregister the devs\n"); unregister_netdev(vlc_devs); // Free the network device printk("Free the devs\n"); free_netdev(vlc_devs); } // Free the reed solomon resources if (rs_decoder) { free_rs(rs_decoder); } printk(KERN_INFO "EBBChar: Goodbye from the LKM!\n"); return 0; } int vlc_init_module(void) { int ret = -ENOMEM; printk("Initializing the VLC module...\n"); phy_state = TX; ///////////// Map memory for communicating with PRU ///////////// rx_pru = memremap(PRU_ADDR+PRU0, 0x10000 ,MEMREMAP_WT); tx_pru = memremap(PRU_ADDR+PRU1, 0x10000 ,MEMREMAP_WT); printk("Memory mapped correctly: %x\n",tx_pru); printk("Memory mapped correctly: %x\n",rx_pru); /// Create the device and register it vlc_devs = alloc_netdev(sizeof(struct vlc_priv), "vlc0", NET_NAME_UNKNOWN, vlc_init); if (vlc_devs == NULL) goto out; ret = register_netdev(vlc_devs); if (ret) printk("VLC: error registering device \"%s\"\n", vlc_devs->name); else printk("VLC: Device registered!\n"); // Create the TX and RX threads task_mac_tx = kthread_run(mac_tx,"TX thread","VLC_TX"); if (IS_ERR(task_mac_tx)){ printk("Unable to start kernel threads. \n"); ret= PTR_ERR(task_phy_decoding); task_mac_tx = NULL; task_phy_decoding = NULL; goto out; } task_phy_decoding = kthread_run(phy_decoding,"RX thread","VLC_RX"); if (IS_ERR(task_phy_decoding)){ printk("Unable to start kernel threads. \n"); ret= PTR_ERR(task_phy_decoding); task_mac_tx = NULL; task_phy_decoding = NULL; goto out; }else printk("Started Kernel Threads! \n"); // Init the RS coding rs_decoder = init_rs(ecc_symsize, ecc_poly, 0, 1, ECC_LEN); // 0---FCR if (!rs_decoder) { printk(KERN_ERR "Could not create a RS decoder\n"); ret = -ENOMEM; goto out; } out: printk("------EXIT vlc_init_module------\n"); if (ret) vlc_cleanup(); return ret; } module_init(vlc_init_module); module_exit(vlc_cleanup);
27.692308
169
0.649734
[ "model" ]
f080864c945f16d0a99ec67e34f6f70884374e86
1,128
h
C
include/vision_module/object_recognition/ImageProc.h
karaage-pp/vision_module
0f8c39f99abbc309f09031046d6fbc93d17af6fa
[ "MIT" ]
2
2017-08-26T18:55:35.000Z
2017-10-03T10:49:53.000Z
include/vision_module/object_recognition/ImageProc.h
karaage-pp/vision_module
0f8c39f99abbc309f09031046d6fbc93d17af6fa
[ "MIT" ]
1
2017-08-26T18:55:57.000Z
2017-08-26T18:55:57.000Z
include/vision_module/object_recognition/ImageProc.h
karaage-pp/vision_module
0f8c39f99abbc309f09031046d6fbc93d17af6fa
[ "MIT" ]
2
2018-10-18T04:10:57.000Z
2018-10-29T06:54:20.000Z
#ifndef _IMAGEPROC #define _IMAGEPROC #include <opencv2/opencv.hpp> class CImageProc{ public: struct histLabel{ unsigned int bin; unsigned int intensity; histLabel(const unsigned int &b, const unsigned int &i){ bin = b; intensity = i; } bool operator>(const histLabel &right) const { return intensity == right.intensity ? bin > right.bin : intensity > right.intensity; } }; CImageProc(); ~CImageProc(); protected: std::vector<int> m_hist; std::vector<histLabel> m_result; cv::Mat m_mat; public: int calcHistAsHSV(const cv::Mat &mat); unsigned int getNBest(const unsigned int &n); std::string getNBestName(const unsigned int &n); std::string labelToName(const unsigned int &label); int hsvToLabel(const uint8_t &h, const uint8_t &s, const uint8_t &v); cv::Mat makeMatFromHSV(const uint8_t &h, const uint8_t &s, const uint8_t &v); }; #endif
24.521739
74
0.557624
[ "vector" ]
f08f7e057be0d40b2380dbd423a932851b9d3805
4,379
h
C
components/bookmarks/browser/bookmark_client.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/bookmarks/browser/bookmark_client.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/bookmarks/browser/bookmark_client.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_CLIENT_H_ #define COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_CLIENT_H_ #include <cstdint> #include <string> #include <unordered_map> #include <utility> #include "base/callback_forward.h" #include "base/task/cancelable_task_tracker.h" #include "components/bookmarks/browser/bookmark_node.h" #include "components/favicon_base/favicon_callback.h" #include "components/keyed_service/core/keyed_service.h" class GURL; namespace base { struct UserMetricsAction; } namespace bookmarks { class BookmarkModel; class BookmarkPermanentNode; // A callback that generates a std::unique_ptr<BookmarkPermanentNode>, given a // max ID to use. The max ID argument will be updated after if a new node has // been created and assigned an ID. using LoadManagedNodeCallback = base::OnceCallback<std::unique_ptr<BookmarkPermanentNode>(int64_t*)>; // This class abstracts operations that depends on the embedder's environment, // e.g. Chrome. class BookmarkClient { public: // Type representing a mapping from URLs to the number of times the URL has // been typed by the user in the Omnibox. using UrlTypedCountMap = std::unordered_map<const GURL*, int>; virtual ~BookmarkClient() {} // Called during initialization of BookmarkModel. virtual void Init(BookmarkModel* model); // Requests a favicon from the history cache for the web page at |page_url| // for icon type favicon_base::IconType::kFavicon. |callback| is run when the // favicon has been fetched, which returns gfx::Image is a multi-resolution // image of gfx::kFaviconSize DIP width and height. The data from the history // cache is resized if need be. virtual base::CancelableTaskTracker::TaskId GetFaviconImageForPageURL( const GURL& page_url, favicon_base::FaviconImageCallback callback, base::CancelableTaskTracker* tracker); // Returns true if the embedder supports typed count for URL. virtual bool SupportsTypedCountForUrls(); // Retrieves the number of times each bookmark URL has been typed in // the Omnibox by the user. For each key (URL) in |url_typed_count_map|, // the corresponding value will be updated with the typed count of that URL. // |url_typed_count_map| must not be null. virtual void GetTypedCountForUrls(UrlTypedCountMap* url_typed_count_map); // Returns whether the embedder wants permanent node of type |type| // to always be visible or to only show them when not empty. virtual bool IsPermanentNodeVisibleWhenEmpty(BookmarkNode::Type type) = 0; // Wrapper around RecordAction defined in base/metrics/user_metrics.h // that ensure that the action is posted from the correct thread. virtual void RecordAction(const base::UserMetricsAction& action) = 0; // Returns a task that will be used to load a managed root node. This task // will be invoked in the Profile's IO task runner. virtual LoadManagedNodeCallback GetLoadManagedNodeCallback() = 0; // Returns true if the |permanent_node| can have its title updated. virtual bool CanSetPermanentNodeTitle(const BookmarkNode* permanent_node) = 0; // Returns true if |node| should sync. virtual bool CanSyncNode(const BookmarkNode* node) = 0; // Returns true if this node can be edited by the user. // TODO(joaodasilva): the model should check this more aggressively, and // should give the client a means to temporarily disable those checks. // http://crbug.com/49598 virtual bool CanBeEditedByUser(const BookmarkNode* node) = 0; // Encodes the bookmark sync data into a string blob. It's used by the // bookmark model to persist the sync metadata together with the bookmark // model. virtual std::string EncodeBookmarkSyncMetadata() = 0; // Decodes a string represeting the sync metadata stored in |metadata_str|. // The model calls this method after it has loaded the model data. // |schedule_save_closure| is a repeating call back to trigger a model and // metadata persistence process. virtual void DecodeBookmarkSyncMetadata( const std::string& metadata_str, const base::RepeatingClosure& schedule_save_closure) = 0; }; } // namespace bookmarks #endif // COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_CLIENT_H_
40.174312
80
0.765472
[ "model" ]
0001106bf3b3444cce20d254c249489b2f9419b9
2,086
h
C
src/external_plugins/scintilla_editor_data_handler/scintilla_editor_impl_decl.h
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
12
2017-11-23T16:02:41.000Z
2019-12-29T08:36:36.000Z
src/external_plugins/scintilla_editor_data_handler/scintilla_editor_impl_decl.h
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
9
2017-12-04T15:55:51.000Z
2019-11-01T13:08:21.000Z
src/external_plugins/scintilla_editor_data_handler/scintilla_editor_impl_decl.h
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
5
2018-09-02T07:35:13.000Z
2019-12-29T08:36:37.000Z
#pragma once #include <pybind11/embed.h> #include <deque> #include "cap_manager.h" #include "read_write_queue.h" #include "parse_termdata.h" #include "plugin_base.h" using TermDataQueue = moodycamel::BlockingReaderWriterQueue<unsigned char, 4096>; class __attribute__ ((visibility ("hidden"))) ScintillaEditorDataHandlerImpl : public virtual PluginBase , public virtual TermDataHandler , public virtual PortableThread::IPortableRunnable { public: ScintillaEditorDataHandlerImpl() : PluginBase("scintilla_editor_data_handler", "scintilla editor data handler", 1) , TermDataHandler() , PortableThread::IPortableRunnable() , m_DataHandlerThread(this) , m_TermDataQueue {4096} , m_Stopped{true} { } virtual ~ScintillaEditorDataHandlerImpl() = default; MultipleInstancePluginPtr NewInstance() override { return MultipleInstancePluginPtr{new ScintillaEditorDataHandlerImpl}; } void InitPlugin(ContextPtr context, AppConfigPtr plugin_config) override { PluginBase::InitPlugin(context, plugin_config); m_DataContext.cap_debug = m_Debug; LoadNativeDataHandler(); } unsigned long Run(void * /*pArgument*/) override; void OnData(const std::vector<unsigned char> & data, size_t data_len) override; void Start() override; void Stop() override; private: void LoadNativeDataHandler(); void ProcessSingleChar(const char * ch); void ProcessAllChars(char ch); void ProcessSingleCharNative(const char * ch); void HandleCap(bool check_unknown = true, char c = 0); PortableThread::CPortableThread m_DataHandlerThread; TermDataQueue m_TermDataQueue; bool m_Stopped; pybind11::object m_DataHandler; term_data_context_s m_DataContext; CapPtr m_Cap; ControlDataParserContextPtr m_ParseContext; ControlDataStatePtr m_State; std::vector<char> m_ControlData; std::deque<std::tuple<ControlDataStatePtr, term_data_param_vector_t, std::vector<char>>> m_CapStateStack; };
30.231884
109
0.719559
[ "object", "vector" ]
000114e42695ea168c6f2be49af674de01c182eb
1,222
h
C
src/typedefs.h
odeke-em/sym
bd646c10cfbcffe659a3ad74e59981399fd90f3e
[ "Apache-2.0" ]
null
null
null
src/typedefs.h
odeke-em/sym
bd646c10cfbcffe659a3ad74e59981399fd90f3e
[ "Apache-2.0" ]
null
null
null
src/typedefs.h
odeke-em/sym
bd646c10cfbcffe659a3ad74e59981399fd90f3e
[ "Apache-2.0" ]
null
null
null
// Author: Emmanuel Odeke <odeke@ualberta.ca> #ifndef _TYPEDEFS_H #define _TYPEDEFS_H #define raiseError(msg){\ fprintf(stderr, "%s::%s \033[91m%s on line %d\n\033[00m",\ __FILE__, __func__, #msg, __LINE__\ );\ exit(-1);\ } typedef int int32; typedef long int int64; typedef unsigned int uint32; typedef unsigned long int uint64; #ifndef _BOOL_D #define _BOOL_D typedef enum { False=0, True=1 } Bool; #endif typedef enum { IntTag, LIntTag, CharArrayTag, ObjTag, Undefined, KeyValueTag, DoubleTag, PadTag, HashMapTag } TypeTag; typedef enum { Heapd, Stackd } MemTag; typedef struct { void *data; Bool isFreed; MemTag memTag; uint32 refCount; TypeTag typeTag; } Object; typedef struct { Object *key, *value; } KeyValue; typedef struct Chain_ { Object *value; struct Chain_ *next; } Chain; typedef struct { void *pass; void *fail; unsigned int _freed:1; unsigned int _heapd:1; } BinaryVote; typedef struct { uint32 size; Chain **list; Bool canCollide; } HashMap; typedef Bool (*Quantifier)(const Object *o); typedef void (*KeyPairOp)(const char *key, Object *o); #endif
18.8
62
0.645663
[ "object" ]
000344dc07be423c339dec1dde0ee971caf16654
546
h
C
src/knn.h
fernandochafim/cpprtools
ef7628c35fa857dc2a1693b5cab9ec15fde8f4a0
[ "MIT" ]
null
null
null
src/knn.h
fernandochafim/cpprtools
ef7628c35fa857dc2a1693b5cab9ec15fde8f4a0
[ "MIT" ]
null
null
null
src/knn.h
fernandochafim/cpprtools
ef7628c35fa857dc2a1693b5cab9ec15fde8f4a0
[ "MIT" ]
null
null
null
int knn( const double *train_inputs_ptr, //n_observations x n_features (Matrix) const double *train_label_ptr, //n_observations (vector) const double *test_input_ptr, //n_features (vector) const int n_observations, const int n_features, const int max_neighbors, double *test_predictions_ptr //max_neighbors (vector) ); int Predict1toMaxNeighbors( double *train_inputs_ptr, double *train_label_ptr, int nrow, int ncol, int max_neighbors, double *test_input_ptr, double *test_prediction_ptr );
36.4
76
0.732601
[ "vector" ]
0009dd57fac249560e6f2d666d67f4a0a427f4fc
4,668
h
C
src/vm/luavm/luavmrunenv.h
GreenVentures/GreenVenturesChain
6c438e884fe07bd247f82a704bd3767dd5848c7e
[ "MIT" ]
1
2020-03-10T13:29:05.000Z
2020-03-10T13:29:05.000Z
src/vm/luavm/luavmrunenv.h
GreenVentures/GreenVenturesChain
6c438e884fe07bd247f82a704bd3767dd5848c7e
[ "MIT" ]
null
null
null
src/vm/luavm/luavmrunenv.h
GreenVentures/GreenVenturesChain
6c438e884fe07bd247f82a704bd3767dd5848c7e
[ "MIT" ]
null
null
null
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2017-2019 The GreenVenturesChain Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef LUA_VM_RUNENV_H #define LUA_VM_RUNENV_H #include "luavm.h" #include "appaccount.h" #include "commons/serialize.h" #include "entities/account.h" #include "entities/receipt.h" #include "persistence/leveldbwrapper.h" #include "persistence/cachewrapper.h" #include "commons/json/json_spirit_utils.h" #include "commons/json/json_spirit_value.h" #include "commons/json/json_spirit_writer_template.h" #include <memory> using namespace std; class CVmOperate; struct lua_State; class CLuaVMContext { public: CCacheWrapper* p_cw; uint32_t height = 0; uint32_t block_time = 0; uint32_t prev_block_time = 0; CBaseTx* p_base_tx = nullptr; uint64_t fuel_limit = 0; TokenSymbol transfer_symbol; uint64_t transfer_amount = 0; // amount of tx user transfer to contract account CAccount* p_tx_user_account = nullptr; CAccount* p_app_account = nullptr; CUniversalContract* p_contract = nullptr; string* p_arguments = nullptr; }; struct AssetTransfer { bool isContractAccount; // Is contract account or tx sender' account CUserID toUid; // to address of the transfer TokenSymbol tokenType; // Token type of the transfer uint64_t tokenAmount; // Token amount of the transfer }; class CLuaVMRunEnv { private: CLuaVMContext *p_context; /** * Run the script object */ std::shared_ptr<CLuaVM> pLua; /** * vm before the app account state */ vector<std::shared_ptr<CAppUserAccount>> rawAppUserAccount; /** * vm operate the app account state */ vector<std::shared_ptr<CAppUserAccount>> newAppUserAccount; vector<CReceipt> receipts; vector<CVmOperate> vmOperateOutput; // save operate output uint32_t transfer_count; bool isCheckAccount; // check account balance map<vector<uint8_t>, vector<CAppFundOperate>> mapAppFundOperate; // vector<unsigned char > 存的是accountId private: bool Init(); bool CheckOperateAccountLimit(); bool CheckOperate(); /** * * @param operates: through the vm return code, The accounts add/minus money * @param accountCache: * @param contractCache * @return true operate account success */ bool OperateAccount(const vector<CVmOperate>& operates); /** * @brief get the account id * @param value: argument * @return:Return account id */ UnsignedCharArray GetAccountID(const CVmOperate& value); bool OperateAppAccount(const map<vector<uint8_t>, vector<CAppFundOperate>> opMap); std::shared_ptr<CAppUserAccount> GetAppAccount(std::shared_ptr<CAppUserAccount>& appAccount); public: /** * A constructor. */ CLuaVMRunEnv(); virtual ~CLuaVMRunEnv(); vector<std::shared_ptr<CAppUserAccount>>& GetRawAppUserAccount(); vector<std::shared_ptr<CAppUserAccount>>& GetNewAppUserAccount(); const vector<CReceipt>& GetReceipts() const { return receipts; } /** * execute contract * @param pContextIn: run context * @param fuel: burned fuel amount * @return: nullptr if run success, else error string */ std::shared_ptr<string> ExecuteContract(CLuaVMContext *pContextIn, uint64_t& uRunStep); /** * @brief just for test * @return: */ // shared_ptr<vector<CVmOperate> > GetOperate() const; const CRegID& GetContractRegID(); const CRegID& GetTxUserRegid(); uint64_t GetValue() const; const string& GetTxContract(); CCacheWrapper* GetCw(); CContractDBCache* GetScriptDB(); CAccountDBCache* GetCatchView(); int32_t GetConfirmHeight(); // Get burn version for fuel burning int32_t GetBurnVersion(); uint256 GetCurTxHash(); bool InsertOutputData(const vector<CVmOperate>& source); /** * transfer account asset * @param transfers: transfer info vector * @return transfer success or not */ bool TransferAccountAsset(lua_State *L, const vector<AssetTransfer> &transfers); void InsertOutAPPOperte(const vector<uint8_t>& userId, const CAppFundOperate& source); bool GetAppUserAccount(const vector<uint8_t>& id, std::shared_ptr<CAppUserAccount>& pAppUserAccount); bool CheckAppAcctOperate(); void SetCheckAccount(bool bCheckAccount); CLuaVMContext &GetContext() const { assert(p_context != nullptr); return *p_context; } }; #endif // LUA_VM_RUNENV_H
30.913907
108
0.698586
[ "object", "vector" ]
000ba0cd6aeff065cad1a47c122e7a51c0910ab8
17,182
h
C
clicks/dac10/lib/include/dac10.h
StrahinjaJacimovic/mikrosdk_click_v2
f8002047c96605f340957a0d3fdbde33706d02ac
[ "MIT" ]
31
2020-10-02T14:15:14.000Z
2022-03-24T08:33:21.000Z
clicks/dac10/lib/include/dac10.h
greghol/mikrosdk_click_v2
76e5dec265dce5fca72c4b93f77afd668dde5dfa
[ "MIT" ]
4
2020-10-27T14:05:00.000Z
2022-03-10T09:38:57.000Z
clicks/dac10/lib/include/dac10.h
greghol/mikrosdk_click_v2
76e5dec265dce5fca72c4b93f77afd668dde5dfa
[ "MIT" ]
32
2020-11-28T07:56:42.000Z
2022-03-14T19:42:29.000Z
/**************************************************************************** ** Copyright (C) 2020 MikroElektronika d.o.o. ** Contact: https://www.mikroe.com/contact ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** copies of the Software, and to permit persons to whom the Software is ** furnished to do so, subject to the following conditions: ** The above copyright notice and this permission notice shall be ** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ** OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, ** DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT ** OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE ** USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /*! * @file dac10.h * @brief This file contains API for DAC 10 Click Driver. */ #ifndef DAC10_H #define DAC10_H #ifdef __cplusplus extern "C"{ #endif #include "drv_digital_out.h" #include "drv_digital_in.h" #include "drv_i2c_master.h" /*! * @addtogroup dac10 DAC 10 Click Driver * @brief API for configuring and manipulating DAC 10 Click driver. * @{ */ /** * @defgroup dac10_reg DAC 10 Registers List * @brief List of registers of DAC 10 Click driver. */ /** * @addtogroup dac10_reg * @{ */ /** * @brief DAC 10 Register Map. * @details List of registers of DAC 10 Click driver. */ #define DAC10_REG_STATUS 0xD0 #define DAC10_REG_GENERAL_CONFIG 0xD1 #define DAC10_REG_TRIGGER 0xD3 #define DAC10_REG_DAC_DATA 0x21 #define DAC10_REG_DAC_MARGIN_HIGH 0x25 #define DAC10_REG_DAC_MARGIN_LOW 0x26 #define DAC10_REG_PMBUS_OPERATION 0x01 #define DAC10_REG_PMBUS_STATUS_BYTE 0x78 #define DAC10_REG_PMBUS_VERSION 0x98 /*! @} */ // dac10_reg /** * @defgroup dac10_set DAC 10 Registers Settings * @brief Settings for registers of DAC 10 Click driver. */ /** * @addtogroup dac10_set * @{ */ /** * @brief DAC 10 status register values. * @details Specified values for status register of DAC 10 Click driver. */ #define DAC10_STATUS_NVM_CRC_ALARM_USER 0x8000 #define DAC10_STATUS_NVM_CRC_ALARM_INTERNAL 0x4000 #define DAC10_STATUS_NVM_BUSY 0x2000 #define DAC10_STATUS_DAC_UPDATE_BUSY 0x1000 #define DAC10_STATUS_DEVICE_ID 0x000C #define DAC10_STATUS_DEVICE_ID_MASK 0x003C #define DAC10_STATUS_VERSION_ID_MASK 0x0003 /** * @brief DAC 10 general config register setting. * @details Specified settings for general config register of DAC 10 Click driver. */ #define DAC10_GEN_CONFIG_FCFG_TRIANGLE_WAVE 0x0000 #define DAC10_GEN_CONFIG_FCFG_SAW_TOOTH_WAVE_RISING 0x4000 #define DAC10_GEN_CONFIG_FCFG_SAW_TOOTH_WAVE_FALLING 0x8000 #define DAC10_GEN_CONFIG_FCFG_SQUARE_WAVE 0xC000 #define DAC10_GEN_CONFIG_FCFG_CLR_MASK 0xC000 #define DAC10_GEN_CONFIG_DEVICE_LOCKED 0x2000 #define DAC10_GEN_CONFIG_DEVICE_NOT_LOCKED 0x0000 #define DAC10_GEN_CONFIG_DEVICE_LOCK_MASK 0x2000 #define DAC10_GEN_CONFIG_PMBUS_ENABLE 0x1000 #define DAC10_GEN_CONFIG_PMBUS_DISABLE 0x0000 #define DAC10_GEN_CONFIG_PMBUS_EN_MASK 0x1000 #define DAC10_GEN_CONFIG_CODE_STEP_1LSB 0x0000 #define DAC10_GEN_CONFIG_CODE_STEP_2LSB 0x0200 #define DAC10_GEN_CONFIG_CODE_STEP_3LSB 0x0400 #define DAC10_GEN_CONFIG_CODE_STEP_4LSB 0x0600 #define DAC10_GEN_CONFIG_CODE_STEP_6LSB 0x0800 #define DAC10_GEN_CONFIG_CODE_STEP_8LSB 0x0A00 #define DAC10_GEN_CONFIG_CODE_STEP_16LSB 0x0C00 #define DAC10_GEN_CONFIG_CODE_STEP_32LSB 0x0E00 #define DAC10_GEN_CONFIG_CODE_STEP_MASK 0x0E00 #define DAC10_GEN_CONFIG_SLEW_RATE_25p6US 0x0000 #define DAC10_GEN_CONFIG_SLEW_RATE_25p6USx1p25 0x0020 #define DAC10_GEN_CONFIG_SLEW_RATE_25p6USx1p50 0x0040 #define DAC10_GEN_CONFIG_SLEW_RATE_25p6USx1p75 0x0060 #define DAC10_GEN_CONFIG_SLEW_RATE_204p8US 0x0080 #define DAC10_GEN_CONFIG_SLEW_RATE_204p8USx1p25 0x00A0 #define DAC10_GEN_CONFIG_SLEW_RATE_204p8USx1p50 0x00C0 #define DAC10_GEN_CONFIG_SLEW_RATE_204p8USx1p75 0x00E0 #define DAC10_GEN_CONFIG_SLEW_RATE_1p6384MS 0x0100 #define DAC10_GEN_CONFIG_SLEW_RATE_1p6384MSx1p25 0x0120 #define DAC10_GEN_CONFIG_SLEW_RATE_1p6384MSx1p50 0x0140 #define DAC10_GEN_CONFIG_SLEW_RATE_1p6384MSx1p75 0x0160 #define DAC10_GEN_CONFIG_SLEW_RATE_12US 0x0180 #define DAC10_GEN_CONFIG_SLEW_RATE_8US 0x01A0 #define DAC10_GEN_CONFIG_SLEW_RATE_4US 0x01C0 #define DAC10_GEN_CONFIG_SLEW_RATE_NO_SLEW 0x01E0 #define DAC10_GEN_CONFIG_SLEW_RATE_MASK 0x01E0 #define DAC10_GEN_CONFIG_DAC_PDN_POWER_UP 0x0000 #define DAC10_GEN_CONFIG_DAC_PDN_POWER_DOWN_10K 0x0008 #define DAC10_GEN_CONFIG_DAC_PDN_POWER_DOWN_HIGH_Z 0x0010 #define DAC10_GEN_CONFIG_DAC_PDN_MASK 0x0018 #define DAC10_GEN_CONFIG_INT_REF_ENABLE 0x0004 #define DAC10_GEN_CONFIG_INT_REF_DISABLE 0x0000 #define DAC10_GEN_CONFIG_INT_REF_EN_MASK 0x0004 #define DAC10_GEN_CONFIG_DAC_SPAN_GAIN_1p5X 0x0000 #define DAC10_GEN_CONFIG_DAC_SPAN_GAIN_2X 0x0001 #define DAC10_GEN_CONFIG_DAC_SPAN_GAIN_3X 0x0002 #define DAC10_GEN_CONFIG_DAC_SPAN_GAIN_4X 0x0003 #define DAC10_GEN_CONFIG_DAC_SPAN_MASK 0x0003 /** * @brief DAC 10 trigger register setting. * @details Specified settings for trigger register of DAC 10 Click driver. */ #define DAC10_TRIGGER_DEVICE_UNLOCK_CODE 0x5000 #define DAC10_TRIGGER_DEVICE_UNLOCK_CODE_MASK 0xF000 #define DAC10_TRIGGER_DEVICE_CONFIG_RESET_INITIATED 0x0200 #define DAC10_TRIGGER_DEVICE_CONFIG_RESET_NOT_INITIATED 0x0000 #define DAC10_TRIGGER_DEVICE_CONFIG_RESET_MASK 0x0200 #define DAC10_TRIGGER_START_FUNC_GEN_ENABLE 0x0100 #define DAC10_TRIGGER_START_FUNC_GEN_DISABLE 0x0000 #define DAC10_TRIGGER_START_FUNC_GEN_MASK 0x0100 #define DAC10_TRIGGER_PMBUS_MARGIN_HIGH_INITIATED 0x0080 #define DAC10_TRIGGER_PMBUS_MARGIN_HIGH_NOT_INITIATED 0x0000 #define DAC10_TRIGGER_PMBUS_MARGIN_HIGH_MASK 0x0080 #define DAC10_TRIGGER_PMBUS_MARGIN_LOW_INITIATED 0x0040 #define DAC10_TRIGGER_PMBUS_MARGIN_LOW_NOT_INITIATED 0x0000 #define DAC10_TRIGGER_PMBUS_MARGIN_LOW_MASK 0x0040 #define DAC10_TRIGGER_NWM_RELOAD_INITIATED 0x0020 #define DAC10_TRIGGER_NWM_RELOAD_NOT_INITIATED 0x0000 #define DAC10_TRIGGER_NWM_RELOAD_MASK 0x0020 #define DAC10_TRIGGER_NWM_PROG_INITIATED 0x0010 #define DAC10_TRIGGER_NWM_PROG_NOT_INITIATED 0x0000 #define DAC10_TRIGGER_NWM_PROG_MASK 0x0010 #define DAC10_TRIGGER_SW_RESET_INITIATED 0x0008 #define DAC10_TRIGGER_SW_RESET_NOT_INITIATED 0x000A #define DAC10_TRIGGER_SW_RESET_MASK 0x000F /** * @brief DAC 10 PMBus operation register setting. * @details Specified settings for PMBus operation register of DAC 10 Click driver. */ #define DAC10_PMBUS_OPERATION_CMD_TURN_OFF 0x0000 #define DAC10_PMBUS_OPERATION_CMD_TURN_ON 0x8000 #define DAC10_PMBUS_OPERATION_CMD_MARGIN_HIGH 0xA400 #define DAC10_PMBUS_OPERATION_CMD_MARGIN_LOW 0x9400 #define DAC10_PMBUS_OPERATION_CMD 0xFF00 /** * @brief DAC 10 PMBus status byte register setting. * @details Specified settings for PMBus status byte register of DAC 10 Click driver. */ #define DAC10_PMBUS_STATUS_BYTE_CML_NO_FAULT 0x0000 #define DAC10_PMBUS_STATUS_BYTE_CML_FAULT 0x0200 #define DAC10_PMBUS_STATUS_BYTE_CML_MASK 0x0200 /** * @brief DAC 10 PMBus version register setting. * @details Specified settings for PMBus version register of DAC 10 Click driver. */ #define DAC10_PMBUS_VERSION_DEFAULT 0x2200 #define DAC10_PMBUS_VERSION_MASK 0xFF00 /** * @brief DAC 10 range values. * @details DAC range values of DAC 10 Click driver. */ #define DAC10_MIN_DAC_VALUE 0x0000 #define DAC10_MAX_DAC_VALUE 0x03FF /** * @brief DAC 10 vref values. * @details DAC vref values of DAC 10 Click driver. */ #define DAC10_VREF_3V3 3.3 #define DAC10_VREF_5V 5 #define DAC10_VREF_INT 1.21 /** * @brief DAC 10 device address setting. * @details Specified setting for device slave address selection of * DAC 10 Click driver. */ #define DAC10_DEV_ADDR_GND 0x48 #define DAC10_DEV_ADDR_VCC 0x49 #define DAC10_DEV_ADDR_SDA 0x4A #define DAC10_DEV_ADDR_SCL 0x4B #define DAC10_DEV_ADDR_BROADCAST 0x47 /*! @} */ // dac10_set /** * @defgroup dac10_map DAC 10 MikroBUS Map * @brief MikroBUS pin mapping of DAC 10 Click driver. */ /** * @addtogroup dac10_map * @{ */ /** * @brief MikroBUS pin mapping. * @details Mapping pins of DAC 10 Click to the selected MikroBUS. */ #define DAC10_MAP_MIKROBUS( cfg, mikrobus ) \ cfg.scl = MIKROBUS( mikrobus, MIKROBUS_SCL ); \ cfg.sda = MIKROBUS( mikrobus, MIKROBUS_SDA ); /*! @} */ // dac10_map /*! @} */ // dac10 /** * @brief DAC 10 Click context object. * @details Context object definition of DAC 10 Click driver. */ typedef struct { // Modules i2c_master_t i2c; /**< I2C driver object. */ // I2C slave address uint8_t slave_address; /**< Device slave address (used for I2C driver). */ } dac10_t; /** * @brief DAC 10 Click configuration object. * @details Configuration object definition of DAC 10 Click driver. */ typedef struct { pin_name_t scl; /**< Clock pin descriptor for I2C driver. */ pin_name_t sda; /**< Bidirectional data pin descriptor for I2C driver. */ uint32_t i2c_speed; /**< I2C serial speed. */ uint8_t i2c_address; /**< I2C slave address. */ } dac10_cfg_t; /** * @brief DAC 10 Click return value data. * @details Predefined enum values for driver return values. */ typedef enum { DAC10_OK = 0, DAC10_ERROR = -1 } dac10_return_value_t; /*! * @addtogroup dac10 DAC 10 Click Driver * @brief API for configuring and manipulating DAC 10 Click driver. * @{ */ /** * @brief DAC 10 configuration object setup function. * @details This function initializes click configuration structure to initial * values. * @param[out] cfg : Click configuration structure. * See #dac10_cfg_t object definition for detailed explanation. * @return Nothing. * @note The all used pins will be set to unconnected state. */ void dac10_cfg_setup ( dac10_cfg_t *cfg ); /** * @brief DAC 10 initialization function. * @details This function initializes all necessary pins and peripherals used * for this click board. * @param[out] ctx : Click context object. * See #dac10_t object definition for detailed explanation. * @param[in] cfg : Click configuration structure. * See #dac10_cfg_t object definition for detailed explanation. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. */ err_t dac10_init ( dac10_t *ctx, dac10_cfg_t *cfg ); /** * @brief DAC 10 I2C writing function. * @details This function writes a two bytes of data to the selected register * by using I2C serial interface. * @param[in] ctx : Click context object. * See #dac10_t object definition for detailed explanation. * @param[in] reg : Register address. * @param[in] data_in : Data to be written. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. */ err_t dac10_reg_write ( dac10_t *ctx, uint8_t reg, uint16_t data_in ); /** * @brief DAC 10 I2C reading function. * @details This function reads two bytes of data from the selected register * by using I2C serial interface. * @param[in] ctx : Click context object. * See #dac10_t object definition for detailed explanation. * @param[in] reg : Register address. * @param[out] data_in : Output read data. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. */ err_t dac10_reg_read ( dac10_t *ctx, uint8_t reg, uint16_t *data_in ); /** * @brief DAC 10 set dac value function. * @details This function sets the DAC DATA register to a desired value. * @param[in] ctx : Click context object. * See #dac10_t object definition for detailed explanation. * @param[in] data_in : 10-bit DAC data. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. */ err_t dac10_set_dac_value ( dac10_t *ctx, uint16_t data_in ); /** * @brief DAC 10 set output voltage function. * @details This function sets the output voltage depending on the vref value defined by * the VCC SEL on-board jumper. VREF and Voltage values can be either in Volts or Milivolts. * @param[in] ctx : Click context object. * See #dac10_t object definition for detailed explanation. * @param[in] vref : VREF value defined by VCC SEL on-board jumper. * @param[in] voltage : Float value to be set as output voltage. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. */ err_t dac10_set_output_voltage ( dac10_t *ctx, float vref, float voltage ); /** * @brief DAC 10 set output voltage with internal reference function. * @details This function sets the output voltage with the internal reference enabled. * @param[in] ctx : Click context object. * See #dac10_t object definition for detailed explanation. * @param[in] voltage : Float value to be set as output voltage ( in Volts ). * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. */ err_t dac10_set_output_voltage_int_vref ( dac10_t *ctx, float voltage ); /** * @brief DAC 10 set dac margin high function. * @details This function sets the DAC MARGIH HIGH register to a desired value. * @param[in] ctx : Click context object. * See #dac10_t object definition for detailed explanation. * @param[in] data_in : 10-bit data input. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. */ err_t dac10_set_dac_margin_high ( dac10_t *ctx, uint16_t data_in ); /** * @brief DAC 10 set dac margin low function. * @details This function sets the DAC MARGIH LOW register to a desired value. * @param[in] ctx : Click context object. * See #dac10_t object definition for detailed explanation. * @param[in] data_in : 10-bit data input. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. */ err_t dac10_set_dac_margin_low ( dac10_t *ctx, uint16_t data_in ); /** * @brief DAC 10 check device ID function. * @details This function checks the communication by reading and verifying the device ID. * @param[in] ctx : Click context object. * See #dac10_t object definition for detailed explanation. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. */ err_t dac10_check_device_id ( dac10_t *ctx ); /** * @brief DAC 10 enable DAC output function. * @details This function enables the DAC output. * @param[in] ctx : Click context object. * See #dac10_t object definition for detailed explanation. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. */ err_t dac10_enable_dac ( dac10_t *ctx ); #ifdef __cplusplus } #endif #endif // DAC10_H /*! @} */ // dac10 // ------------------------------------------------------------------------ END
37.352174
92
0.680654
[ "object" ]
000c24dae81158981d61d723a2284ad9f3bea015
2,033
h
C
OS2Project/OS2Project/h/Slab.h
nikolabebic95/OS2Project
38cb36ac19a62b2e07f4cf86fffd8aa46ae3c37c
[ "MIT" ]
null
null
null
OS2Project/OS2Project/h/Slab.h
nikolabebic95/OS2Project
38cb36ac19a62b2e07f4cf86fffd8aa46ae3c37c
[ "MIT" ]
null
null
null
OS2Project/OS2Project/h/Slab.h
nikolabebic95/OS2Project
38cb36ac19a62b2e07f4cf86fffd8aa46ae3c37c
[ "MIT" ]
null
null
null
/** * \file Slab.h * \brief Interface for the cache system provided by the professors */ #ifndef _slab_h_ #define _slab_h_ typedef struct kmem_cache_s kmem_cache_t; const size_t BLOCK_SIZE = 4096; const size_t CACHE_L1_LINE_SIZE = 64; /** * \brief Initialize the allocator * \param space Pointer to the memory which the allocator can use * \param block_num Size of the memory in blocks */ void kmem_init(void *space, int block_num); /** * \brief Allocate cache * \param name Name of the cache * \param size Size of the object in cache * \param ctor Constructor * \param dtor Destructor * \return Cache object * * If there is no need for a constructor or destructor, * the user should pass nullptr in their place */ kmem_cache_t *kmem_cache_create(const char *name, size_t size, void(*ctor)(void *), void(*dtor)(void *)); /** * \brief Shrink cache * \param cachep Pointer to the cache * \return Number of deallocated blocks */ int kmem_cache_shrink(kmem_cache_t *cachep); /** * \brief Allocate one object from cache * \param cachep Pointer to the cache * \return Allocated object */ void *kmem_cache_alloc(kmem_cache_t *cachep); /** * \brief Deallocate one object from cache * \param cachep Pointer to the cache * \param objp Pointer to the object */ void kmem_cache_free(kmem_cache_t *cachep, void *objp); /** * \brief Allocate one small memory buffer * \param size Size of the buffer * \return Pointer to the allocated buffer */ void *kmalloc(size_t size); /** * \brief Deallocate one small memory buffer * \param objp Pointer to a buffer obtained by \c kmalloc */ void kfree(const void *objp); /** * \brief Deallocate cache * \param cachep Pointer to the cache */ void kmem_cache_destroy(kmem_cache_t *cachep); /** * \brief Print cache info * \param cachep Pointer to the cache */ void kmem_cache_info(kmem_cache_t *cachep); /** * \brief Print error message * \param cachep Pointer to the cache * \return Error code */ int kmem_cache_error(kmem_cache_t *cachep); #endif
23.102273
105
0.722577
[ "object" ]
00105fbdd10d12aa7a7662676616b2a6653d3352
2,003
h
C
adh/primitive.h
smallduckinette/engine
6161c48db3de1c8562885df0041d89f83e8f5233
[ "Apache-2.0" ]
null
null
null
adh/primitive.h
smallduckinette/engine
6161c48db3de1c8562885df0041d89f83e8f5233
[ "Apache-2.0" ]
null
null
null
adh/primitive.h
smallduckinette/engine
6161c48db3de1c8562885df0041d89f83e8f5233
[ "Apache-2.0" ]
null
null
null
#ifndef __ADH_PRIMITIVE_H__ #define __ADH_PRIMITIVE_H__ #include <optional> #include <GL/glew.h> #include "engine/adh/node.h" namespace engine::adh { class Shader; class Texture; class Primitive : public Node { public: Primitive(GLenum mode); ~Primitive(); /// Call bind before setting arrays of data void bind(); /// Optionally call unbind after setting arrays of data void unbind(); /// Set vertex data void setVertexData(const char * data, size_t size); /// Describe vertex data - Call it for each type of data in the vertex data void describeVertexData(size_t index, size_t typeSize, GLenum componentType, size_t stride, size_t offset); /// Set geometry data size_t setDataBuffer(const char * data, size_t size, GLint componentCount, GLenum componentType, bool normalize, size_t stride, size_t offset); /// Set index data void setIndicesBuffer(const char * data, size_t size, size_t count, GLenum type); /// Set texture void setTexture(const std::shared_ptr<Texture> & texture, GLenum textureIndex); /// Set color void setColor(const std::string & label, const glm::vec4 & color); /// Set shader void setShader(const std::shared_ptr<Shader> & shader); private: void draw(Context & context) const override; GLuint _vertexArray; std::optional<GLuint> _elements; std::vector<GLuint> _buffers; std::vector<std::pair<GLenum, std::shared_ptr<Texture> > > _textures; std::vector<std::pair<std::string, glm::vec4> > _colors; GLenum _mode; GLsizei _count; GLenum _type; std::shared_ptr<Shader> _shader; }; } #endif
25.35443
83
0.57314
[ "geometry", "vector" ]
0012387f73e6326ebe8f4ee8c81138cb0b943ba2
4,811
h
C
include/vob/misc/type/applicator.h
voblivion/misc
876ab2238b08198a94015ac0570a75ebf4e5e32a
[ "MIT" ]
null
null
null
include/vob/misc/type/applicator.h
voblivion/misc
876ab2238b08198a94015ac0570a75ebf4e5e32a
[ "MIT" ]
null
null
null
include/vob/misc/type/applicator.h
voblivion/misc
876ab2238b08198a94015ac0570a75ebf4e5e32a
[ "MIT" ]
null
null
null
#pragma once #include "../std/conditional_const.h" #include <cassert> #include <memory> #include <type_traits> #include <typeindex> #include <unordered_map> namespace vob::misty { namespace detail { /// @brief TODO template <bool t_const, typename... TArgs> class type_applicator_base { public: #pragma region CREATORS virtual ~type_applicator_base() = default; #pragma endregion #pragma region ACCESSORS /// @brief Applies inner logic to provided object and arguments. virtual void apply(mistd::conditional_const_t<t_const, void>* a_object, TArgs&&... a_args) const = 0; #pragma endregion }; /// @brief An applicator of TFunc to TValue and TArgs template < typename TValue, template <typename> typename TFunc, bool t_const, typename... TArgs > class basic_type_applicator final : public type_applicator_base<t_const, TArgs...> { public: #pragma region CREATORS /// @brief Constructs a basic_type_applicator from the functor that should be applied to provided objects. explicit basic_type_applicator(TFunc<TValue> a_functor) : m_functor{ std::move(a_functor) } {} #pragma endregion #pragma region ACCESSORS /// @brief Applies inner logic to provided object and arguments. /// Caller must guarantee that provided object is a TValue pointer. void apply(mistd::conditional_const_t<t_const, void>* a_object, TArgs&&... a_args) const override { using Type = mistd::conditional_const_t<t_const, TValue>; auto& t_object = *reinterpret_cast<Type*>(a_object); m_functor(t_object, std::forward<TArgs>(a_args)...); } #pragma endregion private: #pragma region PRIVATE_DATA TFunc<TValue> m_functor; #pragma endregion }; } /// @brief A templated class to apply some logic to a type unknown at compile time. template < template <typename> typename TFunc, typename TAllocator, bool t_const, typename... TArgs> class basic_applicator { #pragma region PRIVATE_TYPES using type_applicator_base = detail::type_applicator_base<t_const, TArgs...>; template <typename TValue> using basic_type_applicator = detail::basic_type_applicator<TValue, TFunc, t_const, TArgs...>; #pragma endregion public: #pragma region CREATORS /// @brief Constructs a basic_applicator from the allocator used to allocate the typed applicators. explicit basic_applicator(TAllocator const& a_allocator = {}) : m_typeApplicators{ allocator{ a_allocator } } {} #pragma endregion #pragma region ACCESSORS /// @brief Returns whether or not a type has been registered to be handled by this applicator. bool is_registered(std::type_index const a_typeIndex) const { return m_typeApplicators.find(a_typeIndex) != m_typeApplicators.end(); } /// @brief Returns whether or not a type has been registered to be handled by this applicator. template <typename TValue> bool is_registered() const { return is_registered(typeid(TValue)); } /// @brief Applies this applicator to the exact type of passed object. /// Does nothing if object's type hasn't been registered. template <typename TValue> void apply(TValue& a_object, TArgs&&... a_args) const { assert(is_registered(typeid(a_object))); auto const t_it = m_typeApplicators.find(typeid(a_object)); if(t_it != m_typeApplicators.end()) { t_it->second->apply(&a_object, std::forward<TArgs>(a_args)...); } } #pragma endregion #pragma region MANIPULATORS /// @brief Registers a type to be later handled by this applicator. template <typename TValue> void register_type(TFunc<TValue> a_functor = {}) { assert(!is_registered<TValue>()); auto allocator = m_typeApplicators.get_allocator(); m_typeApplicators.emplace( typeid(TValue) , std::allocate_shared<basic_type_applicator<TValue>>(allocator, a_functor) ); } #pragma endregion private: #pragma region PRIVATE_TYPES using allocator = typename std::allocator_traits<TAllocator>::template rebind_alloc< std::pair<std::type_index const, std::shared_ptr<type_applicator_base>> >; #pragma endregion #pragma region PRIVATE_DATA std::unordered_map< std::type_index , std::shared_ptr<type_applicator_base> , std::hash<std::type_index> , std::equal_to<> , allocator > m_typeApplicators; #pragma endregion }; /// @brief A basic_applicator using C++'s default allocator. template < template <typename> typename TFunc, bool t_const, typename... TArgs> using applicator = basic_applicator<TFunc, std::allocator<char>, t_const, TArgs...>; namespace pmr { /// @brief A basic_applicator using C++'s polymorphic allocator. template < template <typename> typename TFunc, bool t_const, typename... TArgs> using applicator = basic_applicator<TFunc, std::pmr::polymorphic_allocator<char>, t_const, TArgs...>; } }
28.981928
109
0.730409
[ "object" ]
00179b05b307560be520114003ce4a6c8780fb02
7,216
c
C
src/mice/src/cspice/lnkini.c
jared711/meteoroid_orbits
84428bc33a695fb4bebee383f5094b80ae1d7193
[ "MIT" ]
9
2018-03-28T16:03:28.000Z
2022-01-30T20:36:00.000Z
src/mice/src/cspice/lnkini.c
jared711/meteoroid_orbits
84428bc33a695fb4bebee383f5094b80ae1d7193
[ "MIT" ]
null
null
null
src/mice/src/cspice/lnkini.c
jared711/meteoroid_orbits
84428bc33a695fb4bebee383f5094b80ae1d7193
[ "MIT" ]
2
2021-01-25T10:11:10.000Z
2022-01-09T06:37:06.000Z
/* lnkini.f -- translated by f2c (version 19980913). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #include "f2c.h" /* $Procedure LNKINI ( LNK, initialize ) */ /* Subroutine */ int lnkini_(integer *size, integer *pool) { /* System generated locals */ integer i__1; /* Local variables */ integer i__; extern /* Subroutine */ int chkin_(char *, ftnlen), sigerr_(char *, ftnlen), chkout_(char *, ftnlen), setmsg_(char *, ftnlen), errint_(char *, integer *, ftnlen); /* $ Abstract */ /* Initialize a doubly linked list pool. */ /* $ Disclaimer */ /* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */ /* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */ /* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */ /* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */ /* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */ /* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */ /* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */ /* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */ /* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */ /* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */ /* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */ /* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */ /* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */ /* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */ /* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */ /* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */ /* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */ /* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */ /* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */ /* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */ /* $ Required_Reading */ /* LNK */ /* $ Keywords */ /* LIST */ /* $ Declarations */ /* $ Brief_I/O */ /* Variable I/O Description */ /* -------- --- -------------------------------------------------- */ /* SIZE I Number of nodes in the pool. */ /* POOL I-O An array that is a linked pool on output. */ /* LBPOOL P Lower bound of pool column indices. */ /* $ Detailed_Input */ /* SIZE is the number of nodes in the pool. */ /* POOL is an integer array that will contain the linked */ /* pool on output. */ /* $ Detailed_Output */ /* POOL is an initialized doubly linked list pool. */ /* The status of the pool is as follows: */ /* -- All nodes in the pool are on the free list. */ /* -- The free pointer indicates the first node. */ /* -- The total node count is set to the input */ /* value, SIZE. */ /* -- The free node count is the input value, SIZE. */ /* $ Parameters */ /* LBPOOL is the lower bound of the column indices of the POOL */ /* array. The columns indexed LBPOOL to 0 are reserved */ /* as a control area for the pool. */ /* $ Exceptions */ /* 1) If the requested number of nodes is nonpositive, the error */ /* SPICE(INVALIDCOUNT) is signalled. */ /* $ Files */ /* None. */ /* $ Particulars */ /* LNKINI must be called once to initialize a doubly linked list */ /* pool before the pool is used. LNKINI can be called at any time */ /* to re-initialize a doubly linked list pool. */ /* The functions */ /* LNKNFN ( LNK, number of free nodes ) and */ /* LNKSIZ ( LNK, size of pool ) */ /* will both return the value PLSIZE if called immediately after a */ /* call to LNKINI. */ /* $ Examples */ /* 1) Let POOL be a doubly linked list pool with a maximum of */ /* 100 nodes. POOL should be declared as follows: */ /* INTEGER LBPOOL */ /* PARAMETER ( LBPOOL = -5 ) */ /* INTEGER PLSIZE */ /* PARAMETER ( PLSIZE = 100 ) */ /* INTEGER POOL ( 2, LBPOOL : PLSIZE ) */ /* To initialize POOL, use the call */ /* CALL LNKINI ( PLSIZE, POOL ) */ /* $ Restrictions */ /* None. */ /* $ Literature_References */ /* None. */ /* $ Author_and_Institution */ /* N.J. Bachman (JPL) */ /* W.L. Taber (JPL) */ /* $ Version */ /* - SPICELIB Version 1.0.0, 19-DEC-1995 (NJB) (WLT) */ /* -& */ /* $ Index_Entries */ /* initialize linked list pool */ /* -& */ /* Local parameters */ /* The control area contains 3 elements. They are: */ /* The "size" of the pool, that is, the number */ /* of nodes in the pool. */ /* The number of free nodes in the pool. */ /* The "free pointer," which is the column index of the first free */ /* node. */ /* Parameters defining the row and column indices of these control */ /* elements are given below. */ /* Each assigned node consists of a backward pointer and a forward */ /* pointer. */ /* +-------------+ +-------------+ +-------------+ */ /* | forward--> | | forward--> | | forward--> | */ /* +-------------+ ... +-------------+ ... +-------------+ */ /* | <--backward | | <--backward | | <--backward | */ /* +-------------+ +-------------+ +-------------+ */ /* node 1 node I node SIZE */ /* Free nodes say that that's what they are. The way they say it */ /* is by containing the value FREE in their backward pointers. */ /* Needless to say, FREE is a value that cannot be a valid pointer. */ /* Local variables */ /* Use discovery check-in. */ /* The requested number of nodes must be valid. */ if (*size < 1) { chkin_("LNKINI", (ftnlen)6); setmsg_("A linked list cannot have # nodes.", (ftnlen)34); errint_("#", size, (ftnlen)1); sigerr_("SPICE(INVALIDCOUNT)", (ftnlen)19); chkout_("LNKINI", (ftnlen)6); return 0; } /* Initialize the pool. The free list occupies the whole pool at */ /* this point. */ /* POOL( SIZROW, SIZCOL ) is the pool size. */ pool[10] = *size; /* POOL( NFRROW, NFRCOL ) is the number of free nodes. */ pool[11] = *size; /* POOL( FREROW, FRECOL) is the "free" pointer. It points to the */ /* first free node, which is node 1. */ pool[8] = 1; /* Initialize the backward and forward pointers. The last forward */ /* pointer is zero. All of the backward pointers contain the value */ /* FREE. */ i__1 = *size - 1; for (i__ = 1; i__ <= i__1; ++i__) { pool[(i__ << 1) + 10] = i__ + 1; pool[(i__ << 1) + 11] = 0; } pool[(*size << 1) + 10] = 0; pool[(*size << 1) + 11] = 0; return 0; } /* lnkini_ */
29.695473
76
0.542544
[ "object" ]
0018a3567dba74e187c30ff5d79791a00380234f
15,800
h
C
keyvi/3rdparty/tpie/tpie/btree/btree.h
vvucetic/keyvi
e6f02373350fea000aa3d20be9cc1d0ec09441f7
[ "Apache-2.0" ]
147
2015-10-06T19:10:01.000Z
2021-08-19T07:52:02.000Z
keyvi/3rdparty/tpie/tpie/btree/btree.h
vvucetic/keyvi
e6f02373350fea000aa3d20be9cc1d0ec09441f7
[ "Apache-2.0" ]
148
2015-10-06T09:24:56.000Z
2018-12-08T08:42:54.000Z
keyvi/3rdparty/tpie/tpie/btree/btree.h
vvucetic/keyvi
e6f02373350fea000aa3d20be9cc1d0ec09441f7
[ "Apache-2.0" ]
34
2015-10-09T06:55:52.000Z
2021-01-05T18:43:57.000Z
// -*- mode: c++; tab-width: 4; indent-tabs-mode: t; eval: (progn (c-set-style "stroustrup") (c-set-offset 'innamespace 0)); -*- // vi:set ts=4 sts=4 sw=4 noet : // Copyright 2014 The TPIE development team // // This file is part of TPIE. // // TPIE is free software: you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License as published by the // Free Software Foundation, either version 3 of the License, or (at your // option) any later version. // // TPIE is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public // License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with TPIE. If not, see <http://www.gnu.org/licenses/> #ifndef _TPIE_BTREE_TREE_H_ #define _TPIE_BTREE_TREE_H_ #include <tpie/portability.h> #include <tpie/btree/base.h> #include <tpie/btree/node.h> #include <cstddef> #include <vector> namespace tpie { namespace bbits { /** * \brief External or internal augmented btree * */ template <typename T, typename O> class tree { public: typedef tree_state<T, O> state_type; static const bool is_internal = state_type::is_internal; static const bool is_static = state_type::is_static; static const bool is_ordered = state_type::is_ordered; typedef typename state_type::augmenter_type augmenter_type; /** * \brief Type of value stored */ typedef typename state_type::value_type value_type; typedef typename state_type::keyextract_type keyextract_type; typedef typename state_type::augment_type augment_type; /** * \brief The type of key used */ typedef typename state_type::key_type key_type; typedef typename O::C comp_type; typedef typename state_type::store_type store_type; /** * \brief Type of node wrapper */ typedef btree_node<state_type> node_type; /** * \brief Type of the size */ typedef typename store_type::size_type size_type; /** * \brief Iterator type */ typedef btree_iterator<state_type> iterator; private: typedef typename store_type::leaf_type leaf_type; typedef typename store_type::internal_type internal_type; size_t count_child(internal_type node, size_t i, leaf_type) const { return m_state.store().count_child_leaf(node, i); } size_t count_child(internal_type node, size_t i, internal_type) const { return m_state.store().count_child_internal(node, i); } internal_type get_child(internal_type node, size_t i, internal_type) const { return m_state.store().get_child_internal(node, i); } leaf_type get_child(internal_type node, size_t i, leaf_type) const { return m_state.store().get_child_leaf(node, i); } template <bool upper_bound = false, typename K> leaf_type find_leaf(std::vector<internal_type> & path, K k) const { path.clear(); if (m_state.store().height() == 1) return m_state.store().get_root_leaf(); internal_type n = m_state.store().get_root_internal(); for (size_t i=2;; ++i) { path.push_back(n); for (size_t j=0; ; ++j) { if (j+1 == m_state.store().count(n) || (upper_bound ? m_comp(k, m_state.min_key(n, j+1)) : !m_comp(m_state.min_key(n, j+1), k))) { if (i == m_state.store().height()) return m_state.store().get_child_leaf(n, j); n = m_state.store().get_child_internal(n, j); break; } } } } void augment(leaf_type l, internal_type p) { m_state.store().set_augment(l, p, m_state.m_augmenter(node_type(&m_state, l))); } void augment(value_type, leaf_type) { } void augment(internal_type l, internal_type p) { m_state.store().set_augment(l, p, m_state.m_augmenter(node_type(&m_state, l))); } size_t max_size(internal_type) const throw() { return m_state.store().max_internal_size(); } size_t max_size(leaf_type) const throw() { return m_state.store().max_leaf_size(); } size_t min_size(internal_type) const throw() { return m_state.store().min_internal_size(); } size_t min_size(leaf_type) const throw() { return m_state.store().min_leaf_size(); } template <typename N> N split(N left) { tp_assert(m_state.store().count(left) == max_size(left), "Node not full"); size_t left_size = max_size(left)/2; size_t right_size = max_size(left)-left_size; N right = m_state.store().create(left); for (size_t i=0; i < right_size; ++i) m_state.store().move(left, left_size+i, right, i); m_state.store().set_count(left, left_size); m_state.store().set_count(right, right_size); return right; }; template <typename NT, typename VT> void insert_part(NT n, VT v) { size_t z = m_state.store().count(n); size_t i = z; for (;i > 0 && m_comp(m_state.min_key(v), m_state.min_key(n, i-1)); --i) m_state.store().move(n, i-1, n, i); m_state.store().set(n, i, v); m_state.store().set_count(n, z+1); augment(v, n); } template <typename CT, typename NT> NT split_and_insert(CT c, NT p) { tp_assert(m_state.store().count(p) == max_size(p), "Node not full"); NT p2=split(p); if (m_comp(m_state.min_key(c), m_state.min_key(p2))) insert_part(p, c); else insert_part(p2, c); return p2; } void augment_path(leaf_type) { //NOOP } void augment_path(std::vector<internal_type> & path) { while (path.size() >= 2) { internal_type c=path.back(); path.pop_back(); augment(c, path.back()); } path.pop_back(); } template <typename CT, typename PT> bool remove_fixup_round(CT c, PT p) { size_t z=m_state.store().count(c); size_t i=m_state.store().index(c, p); if (i != 0 && count_child(p, i-1, c) > min_size(c)) { //We can steel a value from left CT left = get_child(p, i-1, c); size_t left_size = m_state.store().count(left); for (size_t j=0; j < z; ++j) m_state.store().move(c, z-j-1, c, z-j); m_state.store().move(left, left_size-1, c, 0); m_state.store().set_count(left, left_size-1); m_state.store().set_count(c, z+1); augment(c, p); augment(left, p); return true; } if (i +1 != m_state.store().count(p) && count_child(p, i+1, c) > min_size(c)) { // We can steel from right CT right = get_child(p, i+1, c); size_t right_size = m_state.store().count(right); m_state.store().move(right, 0, c, z); for (size_t i=0; i+1 < right_size ; ++i) m_state.store().move(right, i+1, right, i); m_state.store().set_count(right, right_size-1); m_state.store().set_count(c, z+1); augment(c, p); augment(right, p); return true; } CT c1; CT c2; if (i == 0) { c1 = c; c2 = get_child(p, i+1, c); } else { c1 = get_child(p, i-1, c); c2 = c; } //Merge l2 into l1 size_t z1 = m_state.store().count(c1); size_t z2 = m_state.store().count(c2); for (size_t i=0; i < z2; ++i) m_state.store().move(c2, i, c1, i+z1); m_state.store().set_count(c1, z1+z2); m_state.store().set_count(c2, 0); // And remove c2 from p size_t id = m_state.store().index(c2, p); size_t z_ = m_state.store().count(p) -1; for (; id != z_; ++id) m_state.store().move(p, id+1, p, id); m_state.store().set_count(p, z_); m_state.store().destroy(c2); augment(c1, p); return z_ >= min_size(p); } public: /** * \brief Returns an iterator pointing to the beginning of the tree */ iterator begin() const { iterator i(&m_state); i.goto_begin(); return i; } /** * \brief Returns an iterator pointing to the end of the tree */ iterator end() const { iterator i(&m_state); i.goto_end(); return i; } /** * \brief Insert given value into the btree */ template <typename X=enab> void insert(value_type v, enable<X, !is_static> =enab()) { m_state.store().set_size(m_state.store().size() + 1); // Handle the special case of the empty tree if (m_state.store().height() == 0) { leaf_type n = m_state.store().create_leaf(); m_state.store().set_count(n, 1); m_state.store().set(n, 0, v); m_state.store().set_height(1); m_state.store().set_root(n); augment_path(n); return; } std::vector<internal_type> path; // Find the leaf contaning the value leaf_type l = find_leaf(path, m_state.min_key(v)); //If there is room in the leaf if (m_state.store().count(l) != m_state.store().max_leaf_size()) { insert_part(l, v); if (!path.empty()) augment(l, path.back()); augment_path(path); return; } // We split the leaf leaf_type l2 = split_and_insert(v, l); // If the leaf was a root leef we create a new root if (path.empty()) { internal_type i=m_state.store().create_internal(); m_state.store().set_count(i, 2); m_state.store().set(i, 0, l); m_state.store().set(i, 1, l2); m_state.store().set_root(i); m_state.store().set_height(m_state.store().height()+1); augment(l, i); augment(l2, i); path.push_back(i); augment_path(path); return; } internal_type p = path.back(); augment(l, p); //If there is room in the parent to insert the extra leave if (m_state.store().count(p) != m_state.store().max_internal_size()) { insert_part(p, l2); augment_path(path); return; } path.pop_back(); internal_type n2 = split_and_insert(l2, p); internal_type n1 = p; while (!path.empty()) { internal_type p = path.back(); augment(n1, p); if (m_state.store().count(p) != m_state.store().max_internal_size()) { insert_part(p, n2); augment_path(path); return; } path.pop_back(); n2 = split_and_insert(n2, p); n1 = p; } //We need a new root internal_type i=m_state.store().create_internal(); m_state.store().set_count(i, 2); m_state.store().set(i, 0, n1); m_state.store().set(i, 1, n2); m_state.store().set_root(i); m_state.store().set_height(m_state.store().height()+1); augment(n1, i); augment(n2, i); path.push_back(i); augment_path(path); } /** * \brief Return an iterator to the first item with the given key */ template <typename K, typename X=enab> iterator find(K v, enable<X, is_ordered> =enab()) const { iterator itr(&m_state); if(m_state.store().height() == 0) { itr.goto_end(); return itr; } std::vector<internal_type> path; leaf_type l = find_leaf<true>(path, v); size_t i=0; size_t z = m_state.store().count(l); while (true) { if (i == z) { itr.goto_end(); return itr; } if (!m_comp(m_state.min_key(l, i), v) && !m_comp(v, m_state.min_key(l, i))) break; ++i; } itr.goto_item(path, l, i); return itr; } /** * \brief Return an interator to the first element that is "not less" than * the given key */ template <typename K, typename X=enab> iterator lower_bound(K v, enable<X, is_ordered> =enab()) const { iterator itr(&m_state); if (m_state.store().height() == 0) { itr.goto_end(); return itr; } std::vector<internal_type> path; leaf_type l = find_leaf(path, v); const size_t z = m_state.store().count(l); for (size_t i = 0 ; i < z ; ++i) { if (!m_comp(m_state.min_key(l, i), v)) { itr.goto_item(path, l, i); return itr; } } itr.goto_item(path, l, z-1); return ++itr; } /** * \brief Return an interator to the first element that is "greater" than * the given key */ template <typename K, typename X=enab> iterator upper_bound(K v, enable<X, is_ordered> =enab()) const { iterator itr(&m_state); if (m_state.store().height() == 0) { itr.goto_end(); return itr; } std::vector<internal_type> path; leaf_type l = find_leaf<true>(path, v); const size_t z = m_state.store().count(l); for (size_t i = 0 ; i < z ; ++i) { if (m_comp(v, m_state.min_key(l, i))) { itr.goto_item(path, l, i); return itr; } } itr.goto_item(path, l, z-1); return ++itr; } /** * \brief remove item at iterator */ template <typename X=enab> void erase(const iterator & itr, enable<X, !is_static> =enab()) { std::vector<internal_type> path=itr.m_path; leaf_type l = itr.m_leaf; size_t z = m_state.store().count(l); size_t i = itr.m_index; m_state.store().set_size(m_state.store().size()-1); --z; for (; i != z; ++i) m_state.store().move(l, i+1, l, i); m_state.store().set_count(l, z); // If we still have a large enough size if (z >= m_state.store().min_leaf_size()) { // We are the lone root if (path.empty()) { augment_path(l); return; } augment(l, path.back()); augment_path(path); return; } // We are too small but the root if (path.empty()) { // We are now the empty tree if (z == 0) { m_state.store().destroy(l); m_state.store().set_height(0); return; } augment_path(l); return; } // Steal or merge if (remove_fixup_round(l, path.back())) { augment_path(path); return; } // If l is now the only child of the root, make l the root if (path.size() == 1) { if (m_state.store().count(path.back()) == 1) { l = m_state.store().get_child_leaf(path.back(), 0); m_state.store().set_count(path.back(), 0); m_state.store().destroy(path.back()); m_state.store().set_height(1); m_state.store().set_root(l); augment_path(l); return; } augment_path(path); return; } while (true) { // We need to handle the parent internal_type p = path.back(); path.pop_back(); if (remove_fixup_round(p, path.back())) { augment_path(path); return; } if (path.size() == 1) { if (m_state.store().count(path.back()) == 1) { p = m_state.store().get_child_internal(path.back(), 0); m_state.store().set_count(path.back(), 0); m_state.store().destroy(path.back()); m_state.store().set_height(m_state.store().height()-1); m_state.store().set_root(p); path.clear(); path.push_back(p); augment_path(path); return; } augment_path(path); return; } } } /** * \brief remove all items with given key */ template <typename X=enab> size_type erase(key_type v, enable<X, !is_static && is_ordered> =enab()) { size_type count = 0; iterator i = find(v); while(i != end()) { erase(i); ++count; i = find(v); } return count; } /** * \brief Return the root node * \pre !empty() */ node_type root() const { if (m_state.store().height() == 1) return node_type(&m_state, m_state.store().get_root_leaf()); return node_type(&m_state, m_state.store().get_root_internal()); } /** * \brief Return the number of elements in the tree */ size_type size() const throw() { return m_state.store().size(); } /** * \brief Check if the tree is empty */ bool empty() const throw() { return m_state.store().size() == 0; } void set_metadata(const std::string & data) { m_state.store().set_metadata(data); } std::string get_metadata() { return m_state.store().get_metadata(); } /** * Construct a btree with the given storage */ template <typename X=enab> explicit tree(std::string path, comp_type comp=comp_type(), augmenter_type augmenter=augmenter_type(), enable<X, !is_internal> =enab() ): m_state(store_type(path), std::move(augmenter), keyextract_type()), m_comp(comp) {} /** * Construct a btree with the given storage */ template <typename X=enab> explicit tree(comp_type comp=comp_type(), augmenter_type augmenter=augmenter_type(), enable<X, is_internal> =enab() ): m_state(store_type(), std::move(augmenter), keyextract_type()), m_comp(comp) {} friend class bbits::builder<T, O>; private: explicit tree(state_type state, comp_type comp): m_state(std::move(state)), m_comp(comp) {} state_type m_state; comp_type m_comp; }; } //namespace bbits template <typename T, typename ... Opts> using btree = bbits::tree<T, typename bbits::OptComp<Opts...>::type>; } //namespace tpie #endif /*_TPIE_BTREE_TREE_H_*/
25.401929
139
0.647089
[ "vector" ]
001b90c98f0de71d8c896f25f173a5d6393afa58
985
c
C
uw_cse333/exs/ex5/ex5.c
tavaresdong/courses-notes
7fb89103bca679f5ef9b14cbc777152daac1402e
[ "MIT" ]
null
null
null
uw_cse333/exs/ex5/ex5.c
tavaresdong/courses-notes
7fb89103bca679f5ef9b14cbc777152daac1402e
[ "MIT" ]
1
2017-07-31T08:15:26.000Z
2017-07-31T08:15:26.000Z
uw_cse333/exs/ex5/ex5.c
tavaresdong/courses-notes
7fb89103bca679f5ef9b14cbc777152daac1402e
[ "MIT" ]
1
2019-10-06T16:52:31.000Z
2019-10-06T16:52:31.000Z
#include "vector.h" #include <assert.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> static void PrintIntVector(vector_t v); #define INIT_VEC_SIZE 4 #define FINAL_VEC_SIZE 10 int main(int argc, char *argv[]) { size_t i; vector_t v = VectorCreate(INIT_VEC_SIZE); if(v == NULL) return EXIT_FAILURE; for(i = 0; i < FINAL_VEC_SIZE; ++i) { int *x = (int*) malloc(sizeof(int)); if(x == NULL) return EXIT_FAILURE; *x = i; element_t old; bool ok = VectorSet(v, i ,x, &old); if(!ok) return EXIT_FAILURE; } PrintIntVector(v); printf("\n"); for(i = 0; i < VectorLength(v); ++i) free(VectorGet(v, i)); VectorFree(v); return EXIT_SUCCESS; } static void PrintIntVector(vector_t v) { size_t i; size_t length; assert(v != NULL); length = VectorLength(v); printf("["); if(length > 0) { printf("%d", *((int*)VectorGet(v, 0))); for(i = 1; i < VectorLength(v); ++i) printf(",%d", *((int*)VectorGet(v, i))); } printf("]"); }
16.416667
43
0.618274
[ "vector" ]
001f76335f4d9c8b36b5255de6b29c1045a12f59
2,977
c
C
gdb-7.3/sim/cris/crisv10f.c
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
1
2016-04-09T02:58:13.000Z
2016-04-09T02:58:13.000Z
gdb-7.3/sim/cris/crisv10f.c
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
gdb-7.3/sim/cris/crisv10f.c
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
/* CRIS v10 simulator support code Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc. Contributed by Axis Communications. This file is part of the GNU simulators. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* The infrastructure is based on that of i960.c. */ #define WANT_CPU_CRISV10F #define BASENUM 10 #define CRIS_TLS_REGISTER 14 #include "cris-tmpl.c" #if WITH_PROFILE_MODEL_P /* Model function for u-multiply unit. */ int MY (XCONCAT3 (f_model_crisv,BASENUM, _u_multiply)) (SIM_CPU *current_cpu ATTRIBUTE_UNUSED, const IDESC *idesc ATTRIBUTE_UNUSED, int unit_num ATTRIBUTE_UNUSED, int referenced ATTRIBUTE_UNUSED) { return 1; } #endif /* WITH_PROFILE_MODEL_P */ /* Do the interrupt sequence if possible, and return 1. If interrupts are disabled or some other lockout is active, return 0 and do nothing. Beware, the v10 implementation is incomplete and doesn't properly lock out interrupts e.g. after special-register access and doesn't handle user-mode. */ int MY (deliver_interrupt) (SIM_CPU *current_cpu, enum cris_interrupt_type type, unsigned int vec) { unsigned char entryaddr_le[4]; int was_user; SIM_DESC sd = CPU_STATE (current_cpu); unsigned32 entryaddr; /* We haven't implemented other interrupt-types yet. */ if (type != CRIS_INT_INT) abort (); /* We're supposed to be called outside of prefixes and branch delay-slots etc, but why not check. */ if (GET_H_INSN_PREFIXED_P ()) abort (); if (!GET_H_IBIT ()) return 0; /* User mode isn't supported for interrupts. (And we shouldn't see this as 1 anyway. The user-mode bit isn't visible from user mode. It doesn't make it into the U bit until the next interrupt/exception.) */ if (GET_H_UBIT ()) abort (); SET_H_PBIT (1); if (sim_core_read_buffer (sd, current_cpu, read_map, entryaddr_le, GET_H_SR (H_SR_PRE_V32_IBR) + vec * 4, 4) == 0) { /* Nothing to do actually; either abort or send a signal. */ sim_core_signal (sd, current_cpu, CIA_GET (current_cpu), 0, 4, GET_H_SR (H_SR_PRE_V32_IBR) + vec * 4, read_transfer, sim_core_unmapped_signal); return 0; } entryaddr = bfd_getl32 (entryaddr_le); SET_H_SR (H_SR_PRE_V32_IRP, GET_H_PC ()); SET_H_PC (entryaddr); return 1; }
28.902913
73
0.708767
[ "model" ]
0020df8f4051f254e85d3b07e70a9389d651bebe
70,274
h
C
lib/lf/fe/hierarchic_fe.h
Fytch/lehrfempp
c804b3e350aa893180f1a02ce57a93b3d7686e91
[ "MIT" ]
16
2018-08-30T19:55:43.000Z
2022-02-16T16:38:06.000Z
lib/lf/fe/hierarchic_fe.h
Fytch/lehrfempp
c804b3e350aa893180f1a02ce57a93b3d7686e91
[ "MIT" ]
151
2018-05-27T13:01:50.000Z
2021-08-04T14:50:50.000Z
lib/lf/fe/hierarchic_fe.h
Fytch/lehrfempp
c804b3e350aa893180f1a02ce57a93b3d7686e91
[ "MIT" ]
20
2018-11-13T13:46:38.000Z
2022-02-18T17:33:52.000Z
#ifndef LF_USCALFE_HP_FE_H_ #define LF_USCALFE_HP_FE_H_ /** * @file * @brief Data structures representing HP finite elements * @author Tobias Rohner * @date May 2020 * @copyright MIT License */ #define _USE_MATH_DEFINES #include <lf/assemble/assemble.h> #include <lf/mesh/mesh.h> #include <lf/quad/quad.h> #include <cmath> #include <memory> #include <vector> #include "fe_point.h" #include "scalar_reference_finite_element.h" namespace lf::fe { /** * @brief computes the `n`-th degree scaled Legendre Polynomial \f$ P_n(x;t) *\f$ * @param n The degree of the polynomial * @param x The evaluation coordinate * @param t The scaling parameter * * To evaluate the scaled Legendre Polynomials \f$ P_n(x;t) \f$, we use that * \f[ \begin{aligned} * P_0(x;t) &= 1 \\ * P_1(x;t) &= 2x - t \\ * nP_n(x;t) &= (2n-1)(2x-t)P_{n-1}(x;t) - (n-1)t^2P_{p-2}(x;t) * \end{aligned} \f] */ double legendre(unsigned n, double x, double t = 1); /** * @brief computes the integral of the (n-1)-th degree scaled Legendre *Polynomial * @param n The degree of the integrated polynomial * @param x The evaluation coordinate * @param t The scaling parameter * * The integral is evaluated using * \f[ * \begin{aligned} * L_1(x) &= x \\ * 2(2n-1)L_n(x) &= P_n(x) - t^2P_{n-2}(x) * \end{aligned} * \f] */ double ilegendre(unsigned n, double x, double t = 1); /** * @brief Computes \f$ \frac{\partial}{\partial x} L(x;t) \f$ * @param n The degree of the integrated scaled Legendre polynomial * @param x The evaluation coordinate * @param t The scaling parameter * * The derivative is simply given by \f$ \frac{\partial}{\partial x} L_n(x;t) = * P_{n-1}(x;t) \f$ */ double ilegendre_dx(unsigned n, double x, double t = 1); /** * @brief Computes \f$ \frac{\partial}{\partial t} L(x;t) \f$ * @param n The degree of the integrated scaled Legendre polynomial * @param x The evaluation coordinate * @param t The scaling parameter * * The derivative is given by * \f[ * \begin{aligned} * \frac{\partial}{\partial t} L_1(x;t) &= 0 \\ * \frac{\partial}{\partial t} L_n(x;t) &= -\frac{1}{2} \left( *P_{n-1}(x;t) + tP_{n-2}(x;t) \right) \end{aligned} \f] */ double ilegendre_dt(unsigned n, double x, double t = 1); /** * @brief Computes the derivative of the n-th degree scaled Legendre polynomial * @param n The degree of the polynomial * @param x The evaluation coordinate * @param t The scaling parameter * * The derivative is given by * \f[ * \begin{aligned} * \frac{\partial}{\partial x} L_0(x;t) &= 0 \\ * \frac{\partial}{\partial x} L_n(x;t) &= 2nP_{n-1}(x;t) + *(2x-t)\frac{\partial}{\partial x}P_{n-1}(x;t) \\ \end{aligned} \f] */ double legendre_dx(unsigned n, double x, double t = 1); /** * @brief Computes the n-th degree shifted Jacobi polynomial * @param n The degree of the polynomial * @param alpha The \f$ \alpha \f$ parameter of the Jacobi polynomial * @param beta The \f$ \beta \f$ parameter of the Jacobi polynomial * @param x The evaluation coordinate * * We use the recurrence relation for non-shifted Jacobi polynomials * \f[ * \begin{aligned} * P_0^{(\alpha,\beta)}(x) &= 1 \\ * P_1^{(\alpha,\beta)}(x) &= \frac{1}{2} \left( \alpha - \beta + *(\alpha + \beta + 2)x \right) \\ P_{n+1}^{(\alpha,\beta)}(x) &= \frac{1}{a_n} *\left( (b_n+c_nx)P_n^{(\alpha,\beta)}(x) - d_nP_{n-1}^{(\alpha,\beta)}(x) *\right) \end{aligned} \f] where \f[ \begin{aligned} * a_n &= 2(n+1)(n+\alpha+\beta+1)(2n+\alpha+\beta) \\ * b_n &= (2n+\alpha+\beta+1)(\alpha^2-\beta^2) \\ * c_n &= (2n+\alpha+\beta)(2n+\alpha+\beta+1)(2n+\alpha+\beta+2) \\ * d_n &= 2(n+\alpha)(n+\beta)(2n+\alpha+\beta+2) * \end{aligned} * \f] */ double jacobi(unsigned n, double alpha, double beta, double x); /** * @brief Computes the n-th degree shifted Jacobi polynomial for \f$ \beta = 0 * \f$ * @param n The degree of the polynomial * @param alpha The \f$ \alpha \f$ parameter of the Jacobi polynomial * @param x The evaluation coordinate */ double jacobi(unsigned n, double alpha, double x); /** * @brief Evaluate the integral of the (n-1)-th degree Jacobi Polynomial for \f$ *\beta = 0 \f$ * @param n The degree of the integrated polynomial * @param alpha The \f$ \alpha \f$ parameter of the Jacobi polynomial * @param x The evaluation coordinate * * The integral is evaluated using * \f[ * \begin{aligned} * L_1^\alpha(x) &= x \\ * L_p^\alpha(x) &= a_pP_p^\alpha(x) + b_pP_{p-1}^\alpha(x) - *c_pP_{p-2}^\alpha(x) \end{aligned} \f] where the coefficients are defined as * \f[ * \begin{aligned} * a_p &= \frac{p+\alpha}{(2p+\alpha-1)(2p+\alpha)} \\ * b_p &= \frac{\alpha}{(2p+\alpha-1)(2p+\alpha)} \\ * c_p &= \frac{p-1}{(2p+\alpha-2)(2p+\alpha-1)} * \end{aligned} * \f] */ double ijacobi(unsigned n, double alpha, double x); /** * @brief Computes the derivative of the n-th integrated scaled Jacobi * polynomial * @param n The degree of the integrated scaled Jacobi polynomial * @param alpha The \f$ \alpha \f$ parameter of the Jacobi polynomial * @param x The evaluation coordinate * * The derivative is simply given by \f$ \frac{\partial}{\partial x} * L_n^{(\alpha,0)}(x) = P_{n-1}^{(\alpha,0)}(x) \f$ */ double ijacobi_dx(unsigned n, double alpha, double x); /** * @brief Computes the derivative of the n-th degree Jacobi Polynomial for \f$ *\beta = 0 \f$ * @param n The degree of the differentiated polynomial * @param alpha The \f$ \alpha \f$ parameter of the Jacobi Polynomial * @param x The evaluation coordinate * * The derivative is evaluated using * \f[ * {P^{(\alpha,0)}_n}'(x) = \frac{\alpha+n+1}{2} P^{(\alpha+1,1)}_{n-1}(x) * \f] */ double jacobi_dx(unsigned n, double alpha, double x); /** * @headerfile lf/fe/fe.h * @brief Hierarchic Finite Elements of arbitrary degree on segments * * The shape functions associated with the vertices are given by * \f[ * \begin{align*} * \widehat{b^\cdot}^1(\widehat{x}) &= 1 - \widehat{x} \\ * \widehat{b^\cdot}^2(\widehat{x}) &= \widehat{x} * \end{align*} * \f] * and the interior basis functions associated with the segment itself * are given by the integrated shifted Legendre polynomials * \f[ * \widehat{b^-}^i(\widehat{x}) = L_i(\widehat{x}) = \int_0^{\widehat{x}}\! *P_{i-1}(\xi) \,\mathrm{d}\xi \quad\mbox{ for }\quad i= 2, \cdots, p \f] where *\f$P_i : [0, 1] \to \mathbb{R}\f$ is the shifted Legendre polynomial of degree *\f$i\f$. * * To compute the basis function coefficients from point evaluations of a *function, we make use of the dual basis given by \f[ \lambda_i^-[f] = *\begin{cases} * f(0) &\mbox{ for } i = 0 \\ * f(1) &\mbox{ for } i = 1 \\ * \frac{1}{2i - 1} \left [P_{i-1}(1)f(1) - P_{i-1}(0)f(0) - \int_0^1\! *P_{i-1}'(x)f(x) \,\mathrm{d}x \right] &\mbox{ for } i \geq 2 \end{cases} \f] * * @attention Note that the local coordinate \f$\widehat{x}\f$ may be flipped by *applying an affine transformation \f$\widehat{x} \mapsto 1 - \widehat{x}\f$. * This must be done if the relative orientation of the edge is *`lf::mesh::Orientation::negative` in order to keep a global ordering of DOFs *on the cell interfaces. * * @note The Shape Functions are taken from the following paper: * https://arxiv.org/pdf/1504.03025.pdf * * @see ScalarReferenceFiniteElement */ template <typename SCALAR> class FeHierarchicSegment final : public ScalarReferenceFiniteElement<SCALAR> { public: FeHierarchicSegment(const FeHierarchicSegment &) = default; FeHierarchicSegment(FeHierarchicSegment &&) noexcept = default; FeHierarchicSegment &operator=(const FeHierarchicSegment &) = default; FeHierarchicSegment &operator=(FeHierarchicSegment &&) noexcept = default; ~FeHierarchicSegment() override = default; FeHierarchicSegment(unsigned degree, const quad::QuadRuleCache &qr_cache) : ScalarReferenceFiniteElement<SCALAR>(), degree_(degree), qr_dual_(&qr_cache.Get(RefEl(), 2 * (degree - 1))) {} [[nodiscard]] lf::base::RefEl RefEl() const override { return lf::base::RefEl::kSegment(); } [[nodiscard]] unsigned Degree() const override { return degree_; } /** * @brief The local shape functions * @copydoc ScalarReferenceFiniteElement::NumRefShapeFunctions() */ [[nodiscard]] lf::base::size_type NumRefShapeFunctions() const override { return degree_ + 1; } /** * @brief One shape function for each vertex, p-1 shape functions for the * segment * @copydoc ScalarReferenceFiniteElement::NumRefShapeFunctions(dim_t) const */ [[nodiscard]] lf::base::size_type NumRefShapeFunctions( dim_t codim) const override { LF_ASSERT_MSG(codim >= 0 && codim <= 1, "codim out of range."); return codim == 0 ? degree_ - 1 : 2; } // clang-format off /** * @brief One shape function for each vertex, p-1 shape functions for the * segment * @copydoc ScalarReferenceFiniteElement::NumRefShapeFunctions(dim_t, sub_idx_t) const */ // clang-format on [[nodiscard]] lf::base::size_type NumRefShapeFunctions( dim_t codim, sub_idx_t subidx) const override { LF_ASSERT_MSG((codim == 0 && subidx == 0) || (codim == 1 && subidx < 2), "codim/subidx out of range."); return NumRefShapeFunctions(codim); } [[nodiscard]] Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> EvalReferenceShapeFunctions(const Eigen::MatrixXd &refcoords) const override { LF_ASSERT_MSG(refcoords.rows() == 1, "refcoords must be a row vector"); Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> result( NumRefShapeFunctions(), refcoords.cols()); // Get the shape functions associated with the vertices result.row(0) = refcoords.unaryExpr([&](double x) -> SCALAR { return 1 - x; }); result.row(1) = refcoords; // Get the shape functions associated with the interior of the segment for (int i = 0; i < degree_ - 1; ++i) { result.row(i + 2) = refcoords.unaryExpr( [&](double x) -> SCALAR { return ilegendre(i + 2, x); }); } return result; } [[nodiscard]] Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> GradientsReferenceShapeFunctions( const Eigen::MatrixXd &refcoords) const override { LF_ASSERT_MSG(refcoords.rows() == 1, "refcoords must be a row vector"); Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> result( NumRefShapeFunctions(), refcoords.cols()); // Get the gradient of the shape functions associated with the vertices result.row(0) = refcoords.unaryExpr([&](double /*x*/) -> SCALAR { return -1; }); result.row(1) = refcoords.unaryExpr([&](double /*x*/) -> SCALAR { return 1; }); // Get the shape functions associated with the interior of the segment for (int i = 0; i < degree_ - 1; ++i) { result.row(i + 2) = refcoords.unaryExpr( [&](double x) -> SCALAR { return ilegendre_dx(i + 2, x); }); } return result; } /** * @brief Evaluation nodes are the endpoints of the segment and the Chebyshev * nodes of degree p-1 on the segment * @copydoc ScalarReferenceFiniteElement::EvaluationNodes() */ [[nodiscard]] Eigen::MatrixXd EvaluationNodes() const override { // First two nodes are vertices of the segment Eigen::MatrixXd nodes(1, NumEvaluationNodes()); nodes(0, 0) = 0; nodes(0, 1) = 1; // The other nodes are quadrature points nodes.block(0, 2, 1, qr_dual_->NumPoints()) = qr_dual_->Points(); return nodes; } /** * @copydoc ScalarReferenceFiniteElement::NumEvaluationNodes() */ [[nodiscard]] lf::base::size_type NumEvaluationNodes() const override { return qr_dual_->NumPoints() + 2; } /** * @brief Maps function evaluations to basis function coefficients * @param nodevals The value of the function at the evaluation nodes * * This function computes the basis function coefficients using the dual * basis of the basis functions on the segment. It is given by * \f[ * \lambda_i^-[f] = \begin{cases} * f(0) &\mbox{ for } i = 0 \\ * f(1) &\mbox{ for } i = 1 \\ * \frac{1}{2i - 1} \left [P_{i-1}(1)f(1) - P_{i-1}(0)f(0) - \int_0^1\! *P_{i-1}'(x)f(x) \,\mathrm{d}x \right] &\mbox{ for } i \geq 2 \end{cases} \f] */ [[nodiscard]] Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> NodalValuesToDofs( const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> &nodevals) const override { Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> dofs(NumRefShapeFunctions()); // Compute the first and second basis function coefficients dofs[0] = nodevals[0]; dofs[1] = nodevals[1]; // Compute the other basis function coefficients for (lf::base::size_type i = 2; i < NumRefShapeFunctions(); ++i) { const SCALAR P0 = ilegendre_dx(i, 0); const SCALAR P1 = ilegendre_dx(i, 1); const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> psidd = qr_dual_->Points().unaryExpr( [&](double x) -> SCALAR { return legendre_dx(i - 1, x); }); // Evaluate the integral from the dual basis const SCALAR integ = (qr_dual_->Weights().transpose().array() * psidd.array() * nodevals.tail(qr_dual_->NumPoints()).array()) .sum(); // Compute the basis function coefficient dofs[i] = (P1 * nodevals[1] - P0 * nodevals[0] - integ) * (2 * i - 1); } return dofs; } private: unsigned degree_; const lf::quad::QuadRule *qr_dual_; }; /** * @headerfile lf/fe/fe.h * @brief Hierarchic Finite Elements of arbitrary degree on triangles * * The shape functions associated with the vertices are given by the barycentric *coordinates \f[ \begin{align*} * \widehat{b^{\cdot}}^1(\widehat{x}, \widehat{y}) &= \lambda_1 = 1 - *\widehat{x} - \widehat{y} \\ * \widehat{b^{\cdot}}^2(\widehat{x}, \widehat{y}) &= \lambda_2 = *\widehat{x} \\ \widehat{b^{\cdot}}^3(\widehat{x}, \widehat{y}) &= \lambda_3 = *\widehat{y} \end{align*} \f] * * The basis functions associated with the triangle edges are given by the *homogenized integrated Legendre polynomials \f[ \begin{align*} * \widehat{b^-}^i(\widehat{x}, \widehat{y}) &= (\lambda_1 + \lambda_2)^i *L_i\left(\frac{\lambda_2}{\lambda_1+\lambda_2}\right) &\mbox{ for edge 1 and } *i = 2, \cdots, p \\ * \widehat{b^-}^i(\widehat{x}, \widehat{y}) &= (\lambda_2 + \lambda_3)^i *L_i\left(\frac{\lambda_3}{\lambda_2+\lambda_3}\right) &\mbox{ for edge 2 and } *i = 2, \cdots, p \\ \widehat{b^-}^i(\widehat{x}, \widehat{y}) &= (\lambda_3 + *\lambda_1)^i L_i\left(\frac{\lambda_1}{\lambda_3+\lambda_1}\right) &\mbox{ for *edge 3 and } i = 2, \cdots, p \end{align*} \f] Note that the basis function on *a specific edge is always zero on the other two edges. This is needed to *guarantee continuity of the function space. * * The basis functions associated with the interior of the triangle are given by *the edge basis functions multiplied with an integrated Jacobi polynomial to *force the value of the basis function to be zero on all edges. \f[ * \widehat{b^{\triangle}}^{ij}(\widehat{x}, \widehat{y}) = (\lambda_1 + *\lambda_2)^i L_i\left(\frac{\lambda_2}{\lambda_1+\lambda_2}\right) *L_j^{2i}(\lambda_3) \quad\mbox{ for } i \geq 2, j \geq 1, i+j = 3, \cdots, p * \f] * where \f$L_i : [0, 1] \to \mathbb{R}\f$ and \f$L_i^{\alpha} : [0, 1] \to *\mathbb{R}\f$ are the integrated shifted Legendre and integrated shifted *Jacobi polynomials respectively: \f[ \begin{align*} * L_i(x) &= \int_0^x\! P_{i-1}(\xi) \,\mathrm{d}\xi \\ * L_i^{\alpha}(x) &= \int_0^x\! P_{i-1}^{(\alpha, 0)}(\xi) \,\mathrm{d}\xi * \end{align*} * \f] * * To compute the basis function coefficientsfrom point evaluations of a *function, we make use of the dual basis. For the vertices it is simply given *by \f[ \lambda_i^{\cdot}[f] = \begin{cases} * f(0, 0) &\mbox{ for } i = 1 \\ * f(1, 0) &\mbox{ for } i = 2 \\ * f(0, 1) &\mbox{ for } i = 3 * \end{cases} * \f] * For the dual basis on the edges, we simply apply the segment dual basis along *the edges of the triangle \f[ \lambda_i^-[f] = \begin{cases} * \frac{1}{2i-1} \left[ P_{i-1}(1)f(1, 0) - P_{i-1}(0)f(0, 0) - \int_0^1\! *P_{i-1}'(x)f(x, 0) \,\mathrm{d}x \right] &\mbox{ for edge 1} \\ * \frac{1}{2i-1} \left[ P_{i-1}(1)f(0, 1) - P_{i-1}(0)f(1, 0) - \int_0^1\! *P_{i-1}'(x)f(1-x, x) \,\mathrm{d}{x} \right] &\mbox{ for edge 2} \\ * \frac{1}{2i-1} \left[ P_{i-1}(1)f(0, 0) - P_{i-1}(0)f(0, 1) - \int_0^1\! *P_{i-1}'(x)f(0, 1-x) \,\mathrm{d}x \right] &\mbox{ for edge 2} \end{cases} \f] * The dual basis for the interior shape functions is quite a bit more involved. *It is given by \f[ \lambda_{ij}^{\triangle}[f] = \frac{1}{(2i-1)(2i+2j-1)} *\left[ \int_0^1\! \int_0^{1-y}\! f(x, y) \left( (1-y)^{i-1}{L_j^{2i}}''(y) - *2i(1-y)^{i-2}{L_j^{2i}}'(y) \right) L_{j+1}''\left(\frac{x}{1-y}\right) *\,\mathrm{d}x \,\mathrm{d}y \right] \f] and must additionally be *orthogonalized with respect to the dual basis on the vertices and edges of the *triangle by subtracting them accordingly. * * @attention Note that for the basis functions associated with the edges, *depending on the `lf::mesh::Orientation` of the according edge, the local *coordinate may be flipped to ensure continuity of the function space over the *cell interfaces of the mesh. The basis functions and the dual basis must be * adjusted accordingly in this case. * * @note The Shape Functions are taken from the following paper: * https://arxiv.org/pdf/1504.03025.pdf * * @see ScalarReferenceFiniteElement */ template <typename SCALAR> class FeHierarchicTria final : public ScalarReferenceFiniteElement<SCALAR> { public: FeHierarchicTria(const FeHierarchicTria &) = default; FeHierarchicTria(FeHierarchicTria &&) noexcept = default; FeHierarchicTria &operator=(const FeHierarchicTria &) = default; FeHierarchicTria &operator=(FeHierarchicTria &&) noexcept = default; ~FeHierarchicTria() override = default; FeHierarchicTria(unsigned interior_degree, std::array<unsigned, 3> edge_degrees, const quad::QuadRuleCache &qr_cache, nonstd::span<const lf::mesh::Orientation> rel_orient) : ScalarReferenceFiniteElement<SCALAR>(), interior_degree_(interior_degree), edge_degrees_(edge_degrees), qr_dual_edge_( {&qr_cache.Get(base::RefEl::kSegment(), 2 * (edge_degrees_[0] - 1)), &qr_cache.Get(base::RefEl::kSegment(), 2 * (edge_degrees_[1] - 1)), &qr_cache.Get(base::RefEl::kSegment(), 2 * (edge_degrees_[2] - 1))}), qr_dual_tria_(&qr_cache.Get(lf::base::RefEl::kTria(), 2 * (interior_degree_ - 1))), rel_orient_(rel_orient) { LF_ASSERT_MSG(interior_degree_ >= 0, "illegal interior degree."); LF_ASSERT_MSG(edge_degrees_[0] >= 0, "illegal degree for edge 0"); LF_ASSERT_MSG(edge_degrees_[1] >= 0, "illegal degree for edge 1"); LF_ASSERT_MSG(edge_degrees_[2] >= 0, "illegal degree for edge 2"); } [[nodiscard]] lf::base::RefEl RefEl() const override { return lf::base::RefEl::kTria(); } [[nodiscard]] unsigned Degree() const override { return std::max({interior_degree_, edge_degrees_[0], edge_degrees_[1], edge_degrees_[2], 1U}); } /** * @brief The local shape functions * @copydoc ScalarReferenceFiniteElement::NumRefShapeFunctions() */ [[nodiscard]] lf::base::size_type NumRefShapeFunctions() const override { return NumRefShapeFunctions(0) + NumRefShapeFunctions(1, 0) + NumRefShapeFunctions(1, 1) + NumRefShapeFunctions(1, 2) + 3; } /** * @brief One shape function for each vertex, p-1 shape functions on the edges * and max(0, (p-2)*(p-1)/2) shape functions on the triangle * @copydoc ScalarReferenceFiniteElement::NumRefShapeFunctions(dim_t) const */ [[nodiscard]] lf::base::size_type NumRefShapeFunctions( dim_t codim) const override { switch (codim) { case 0: if (interior_degree_ <= 2) { return 0; } else { return (interior_degree_ - 2) * (interior_degree_ - 1) / 2; } case 1: LF_VERIFY_MSG( edge_degrees_[0] == edge_degrees_[1] && edge_degrees_[0] == edge_degrees_[2], "You cannot call this method with codim=1 if the edges of the " "triangle have a differing number of shape functions."); return edge_degrees_[0] - 1; case 2: return 1; default: LF_ASSERT_MSG(false, "Illegal codim " << codim); // Silence compiler warnings return 0; } } // clang-format off /** * @brief One shape function for each vertex, p-1 shape functions on the edges * and max(0, (p-2)*(p-1)/2) shape functions on the triangle * @copydoc ScalarReferenceFiniteElement::NumRefShapeFunctions(dim_t, sub_idx_t) const */ // clang-format on [[nodiscard]] lf::base::size_type NumRefShapeFunctions( dim_t codim, sub_idx_t subidx) const override { switch (codim) { case 0: LF_ASSERT_MSG(subidx == 0, "illegal codim and subidx."); return NumRefShapeFunctions(0); case 1: LF_ASSERT_MSG(subidx >= 0 && subidx <= 2, "illegal codim/subidx combination."); return edge_degrees_[subidx] - 1; case 2: LF_ASSERT_MSG(subidx >= 0 && subidx <= 2, "illegal codim/subidx combination."); return 1; default: LF_VERIFY_MSG(false, "Illegal codim " << codim); // Silence compiler warnings return 0; } } [[nodiscard]] Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> EvalReferenceShapeFunctions(const Eigen::MatrixXd &refcoords) const override { Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> result( NumRefShapeFunctions(), refcoords.cols()); // Compute the barycentric coordinate functions const Eigen::RowVectorXd l1 = Eigen::RowVectorXd::Ones(refcoords.cols()) - refcoords.row(0) - refcoords.row(1); const Eigen::RowVectorXd l2 = refcoords.row(0); const Eigen::RowVectorXd l3 = refcoords.row(1); // Get the basis functions associated with the vertices result.row(0) = l1; result.row(1) = l2; result.row(2) = l3; int current_dof = 3; // counter for the next row in the result. // Get the basis functions associated with the first edge for (unsigned i = 0; i < edge_degrees_[0] - 1; ++i) { if (rel_orient_[0] == lf::mesh::Orientation::positive) { // L_{i+2}(\lambda_2 ; \lambda_1+\lambda_2) for (long j = 0; j < refcoords.cols(); ++j) { result(3 + i, j) = ilegendre(i + 2, l2[j], l1[j] + l2[j]); } } else { // L_{i+2}(\lambda_1 ; \lambda_1+\lambda_2) for (long j = 0; j < refcoords.cols(); ++j) { result(edge_degrees_[0] + 1 - i, j) = ilegendre(i + 2, l1[j], l1[j] + l2[j]); } } } current_dof += edge_degrees_[0] - 1; // Get the basis functions associated with the second edge for (unsigned i = 0; i < edge_degrees_[1] - 1; ++i) { if (rel_orient_[1] == lf::mesh::Orientation::positive) { // L_{i+2}(\lambda_3 ; \lambda_2+\lambda_3) for (long j = 0; j < refcoords.cols(); ++j) { result(current_dof + i, j) = ilegendre(i + 2, l3[j], l2[j] + l3[j]); } } else { // L_{i+2}(\lambda_2 ; \lambda_2+\lambda_3) for (long j = 0; j < refcoords.cols(); ++j) { result(current_dof + edge_degrees_[1] - 2 - i, j) = ilegendre(i + 2, l2[j], l2[j] + l3[j]); } } } current_dof += edge_degrees_[1] - 1; // Get the basis functions associated with the third edge for (unsigned i = 0; i < edge_degrees_[2] - 1; ++i) { if (rel_orient_[2] == lf::mesh::Orientation::positive) { // L_{i+2}(\lambda_1 ; \lambda_3+\lambda_1) for (long j = 0; j < refcoords.cols(); ++j) { result(current_dof + i, j) = ilegendre(i + 2, l1[j], l3[j] + l1[j]); } } else { // L_{i+2}(\lambda_3 ; \lambda_3+\lambda_1) for (long j = 0; j < refcoords.cols(); ++j) { result(current_dof + edge_degrees_[2] - 2 - i, j) = ilegendre(i + 2, l3[j], l3[j] + l1[j]); } } } current_dof += edge_degrees_[2] - 1; // Get the basis functions associated with the interior of the triangle if (interior_degree_ > 2) { // i is the degree of the edge function for (unsigned i = 0; i < interior_degree_ - 2; ++i) { // value of the edge function (agrees with the values computed above, // but since the degrees of the edge and interior are not linked at all, // we cannot make any assumptions. Eigen::Array<SCALAR, 1, Eigen::Dynamic> edge(refcoords.cols()); for (Eigen::Index j = 0; j < refcoords.cols(); ++j) { if (rel_orient_[0] == mesh::Orientation::positive) { edge(j) = ilegendre(i + 2, l2[j], l1[j] + l2[j]); } else { edge(j) = ilegendre(i + 2, l1[j], l1[j] + l2[j]); } } // j is the degree of the blending // polynomial for (unsigned j = 0; j < interior_degree_ - i - 2; ++j) { if (rel_orient_[0] == lf::mesh::Orientation::positive) { // L_{i+2}(\lambda_3 ; \lambda_2+\lambda_3) * // P_{j+1}^{2i+4}(\lambda_1) result.row(current_dof++) = (edge * l3.array().unaryExpr([&](double x) -> SCALAR { return ijacobi(j + 1, 2 * i + 4, x); })).matrix(); } else { // L_{i+2}(\lambda_2 ; \lambda_2+\lambda_3) * // P_{j+1}^{2i+4}(\lambda_1) result.row(current_dof++) = (edge * l3.array().unaryExpr([&](double x) -> SCALAR { return ijacobi(j + 1, 2 * i + 4, x); })).matrix(); } } } } LF_ASSERT_MSG(current_dof == result.rows(), "Something's wrong, not all rows have been filled."); return result; } [[nodiscard]] Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> GradientsReferenceShapeFunctions( const Eigen::MatrixXd &refcoords) const override { Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> result( NumRefShapeFunctions(), 2 * refcoords.cols()); // Compute the barycentric coordinate functions const Eigen::RowVectorXd l1 = Eigen::RowVectorXd::Ones(refcoords.cols()) - refcoords.row(0) - refcoords.row(1); const Eigen::RowVectorXd l2 = refcoords.row(0); const Eigen::RowVectorXd l3 = refcoords.row(1); // Comput the gradients of the barycentrc coordinate functions const Eigen::RowVectorXd l1_dx = Eigen::RowVectorXd::Constant(refcoords.cols(), -1); const Eigen::RowVectorXd l1_dy = Eigen::RowVectorXd::Constant(refcoords.cols(), -1); const Eigen::RowVectorXd l2_dx = Eigen::RowVectorXd::Constant(refcoords.cols(), 1); const Eigen::RowVectorXd l2_dy = Eigen::RowVectorXd::Constant(refcoords.cols(), 0); const Eigen::RowVectorXd l3_dx = Eigen::RowVectorXd::Constant(refcoords.cols(), 0); const Eigen::RowVectorXd l3_dy = Eigen::RowVectorXd::Constant(refcoords.cols(), 1); // Iterate over all refcoords for (Eigen::Index i = 0; i < refcoords.cols(); ++i) { int current_dof = 3; // Get the gradient of the basis functions associated with the vertices result(0, 2 * i + 0) = l1_dx[i]; result(0, 2 * i + 1) = l1_dy[i]; result(1, 2 * i + 0) = l2_dx[i]; result(1, 2 * i + 1) = l2_dy[i]; result(2, 2 * i + 0) = l3_dx[i]; result(2, 2 * i + 1) = l3_dy[i]; // Get the gradient of the basis functions associated with the first edge for (int j = 0; j < edge_degrees_[0] - 1; ++j) { if (rel_orient_[0] == lf::mesh::Orientation::positive) { result(current_dof + j, 2 * i + 0) = ilegendre_dx(j + 2, l2[i], l1[i] + l2[i]) * l2_dx[i] + ilegendre_dt(j + 2, l2[i], l1[i] + l2[i]) * (l1_dx[i] + l2_dx[i]); result(current_dof + j, 2 * i + 1) = ilegendre_dx(j + 2, l2[i], l1[i] + l2[i]) * l2_dy[i] + ilegendre_dt(j + 2, l2[i], l1[i] + l2[i]) * (l1_dy[i] + l2_dy[i]); } else { result(current_dof + edge_degrees_[0] - 2 - j, 2 * i + 0) = ilegendre_dx(j + 2, l1[i], l1[i] + l2[i]) * l1_dx[i] + ilegendre_dt(j + 2, l1[i], l1[i] + l2[i]) * (l1_dx[i] + l2_dx[i]); result(current_dof + edge_degrees_[0] - 2 - j, 2 * i + 1) = ilegendre_dx(j + 2, l1[i], l1[i] + l2[i]) * l1_dy[i] + ilegendre_dt(j + 2, l1[i], l1[i] + l2[i]) * (l1_dy[i] + l2_dy[i]); } } current_dof += edge_degrees_[0] - 1; // Get the gradient of the basis functions associated with the second edge for (int j = 0; j < edge_degrees_[1] - 1; ++j) { if (rel_orient_[1] == lf::mesh::Orientation::positive) { result(current_dof + j, 2 * i + 0) = ilegendre_dx(j + 2, l3[i], l2[i] + l3[i]) * l3_dx[i] + ilegendre_dt(j + 2, l3[i], l2[i] + l3[i]) * (l2_dx[i] + l3_dx[i]); result(current_dof + j, 2 * i + 1) = ilegendre_dx(j + 2, l3[i], l2[i] + l3[i]) * l3_dy[i] + ilegendre_dt(j + 2, l3[i], l2[i] + l3[i]) * (l2_dy[i] + l3_dy[i]); } else { result(current_dof + edge_degrees_[1] - 2 - j, 2 * i + 0) = ilegendre_dx(j + 2, l2[i], l2[i] + l3[i]) * l2_dx[i] + ilegendre_dt(j + 2, l2[i], l2[i] + l3[i]) * (l2_dx[i] + l3_dx[i]); result(current_dof + edge_degrees_[1] - 2 - j, 2 * i + 1) = ilegendre_dx(j + 2, l2[i], l2[i] + l3[i]) * l2_dy[i] + ilegendre_dt(j + 2, l2[i], l2[i] + l3[i]) * (l2_dy[i] + l3_dy[i]); } } current_dof += edge_degrees_[1] - 1; // Get the gradient of the basis functions associated with the third edge for (int j = 0; j < edge_degrees_[2] - 1; ++j) { if (rel_orient_[2] == lf::mesh::Orientation::positive) { result(current_dof + j, 2 * i + 0) = ilegendre_dx(j + 2, l1[i], l3[i] + l1[i]) * l1_dx[i] + ilegendre_dt(j + 2, l1[i], l3[i] + l1[i]) * (l3_dx[i] + l1_dx[i]); result(current_dof + j, 2 * i + 1) = ilegendre_dx(j + 2, l1[i], l3[i] + l1[i]) * l1_dy[i] + ilegendre_dt(j + 2, l1[i], l3[i] + l1[i]) * (l3_dy[i] + l1_dy[i]); } else { result(current_dof + edge_degrees_[2] - 2 - j, 2 * i + 0) = ilegendre_dx(j + 2, l3[i], l3[i] + l1[i]) * l3_dx[i] + ilegendre_dt(j + 2, l3[i], l3[i] + l1[i]) * (l3_dx[i] + l1_dx[i]); result(current_dof + edge_degrees_[2] - 2 - j, 2 * i + 1) = ilegendre_dx(j + 2, l3[i], l3[i] + l1[i]) * l3_dy[i] + ilegendre_dt(j + 2, l3[i], l3[i] + l1[i]) * (l3_dy[i] + l1_dy[i]); } } current_dof += edge_degrees_[2] - 1; // Get the gradient of the basis functions associated with the interior of // the triangle if (interior_degree_ > 2) { for (unsigned j = 0; j < interior_degree_ - 2; ++j) { SCALAR edge_eval; SCALAR edge_dx; SCALAR edge_dy; if (rel_orient_[0] == lf::mesh::Orientation::positive) { edge_eval = ilegendre(j + 2, l2[i], l1[i] + l2[i]); edge_dx = ilegendre_dx(j + 2, l2[i], l1[i] + l2[i]) * l2_dx[i] + ilegendre_dt(j + 2, l2[i], l1[i] + l2[i]) * (l1_dx[i] + l2_dx[i]); edge_dy = ilegendre_dx(j + 2, l2[i], l1[i] + l2[i]) * l2_dy[i] + ilegendre_dt(j + 2, l2[i], l1[i] + l2[i]) * (l1_dy[i] + l2_dy[i]); } else { edge_eval = ilegendre(j + 2, l1[i], l1[i] + l2[i]); edge_dx = ilegendre_dx(j + 2, l1[i], l1[i] + l2[i]) * l1_dx[i] + ilegendre_dt(j + 2, l1[i], l1[i] + l2[i]) * (l1_dx[i] + l2_dx[i]); edge_dy = ilegendre_dx(j + 2, l1[i], l1[i] + l2[i]) * l1_dy[i] + ilegendre_dt(j + 2, l1[i], l1[i] + l2[i]) * (l1_dy[i] + l2_dy[i]); } for (unsigned k = 0; k < interior_degree_ - j - 2; ++k) { SCALAR jackinte = ijacobi(k + 1, 2 * j + 4, l3[i]); SCALAR jackeval = ijacobi_dx(k + 1, 2 * j + 4, l3[i]); result(current_dof, 2 * i + 0) = jackinte * edge_dx + edge_eval * jackeval * l3_dx[i]; result(current_dof++, 2 * i + 1) = jackinte * edge_dy + edge_eval * jackeval * l3_dy[i]; } } } LF_ASSERT_MSG(current_dof == NumRefShapeFunctions(), "internal error, not all rows have been filled."); } return result; } /** * @brief Evaluation nodes are the vertices, the points of a Gauss * quadrature rule for each edge and the points of a quadrature rule * on the interior of the triangle. * @copydoc ScalarReferenceFiniteElement::EvaluationNodes() */ [[nodiscard]] Eigen::MatrixXd EvaluationNodes() const override { const auto Ns0 = edge_degrees_[0] > 1 ? qr_dual_edge_[0]->NumPoints() : 0; const auto Ns1 = edge_degrees_[1] > 1 ? qr_dual_edge_[1]->NumPoints() : 0; const auto Ns2 = edge_degrees_[2] > 1 ? qr_dual_edge_[2]->NumPoints() : 0; const lf::base::size_type Nt = qr_dual_tria_->NumPoints(); Eigen::MatrixXd nodes(2, 3 + Ns0 + Ns1 + Ns2 + Nt); // Add the vertices nodes(0, 0) = 0; nodes(1, 0) = 0; nodes(0, 1) = 1; nodes(1, 1) = 0; nodes(0, 2) = 0; nodes(1, 2) = 1; // Add the quadrature points on the first edge if (Ns0 > 0) { if (rel_orient_[0] == lf::mesh::Orientation::positive) { nodes.block(0, 3, 1, Ns0) = qr_dual_edge_[0]->Points(); } else { nodes.block(0, 3, 1, Ns0) = Eigen::RowVectorXd::Ones(Ns0) - qr_dual_edge_[0]->Points(); } nodes.block(1, 3, 1, Ns0).setZero(); } // Add the quadrature points on the second edge if (Ns1 > 0) { if (rel_orient_[1] == lf::mesh::Orientation::positive) { nodes.block(0, 3 + Ns0, 1, Ns1) = Eigen::RowVectorXd::Ones(Ns1) - qr_dual_edge_[1]->Points(); nodes.block(1, 3 + Ns0, 1, Ns1) = qr_dual_edge_[1]->Points(); } else { nodes.block(0, 3 + Ns0, 1, Ns1) = qr_dual_edge_[1]->Points(); nodes.block(1, 3 + Ns0, 1, Ns1) = Eigen::RowVectorXd::Ones(Ns1) - qr_dual_edge_[1]->Points(); } } // Add the quadrature points on the third edge if (Ns2 > 0) { nodes.block(0, 3 + Ns0 + Ns1, 1, Ns2).setZero(); if (rel_orient_[2] == lf::mesh::Orientation::positive) { nodes.block(1, 3 + Ns0 + Ns1, 1, Ns2) = Eigen::RowVectorXd::Ones(Ns2) - qr_dual_edge_[2]->Points(); } else { nodes.block(1, 3 + Ns0 + Ns1, 1, Ns2) = qr_dual_edge_[2]->Points(); } } if (Nt > 0) { // Add the quadrature points for the interior nodes.block(0, 3 + Ns0 + Ns1 + Ns2, 2, Nt) = qr_dual_tria_->Points(); } return nodes; } /** * @copydoc ScalarReferenceFiniteElement::NumEvaluationNodes() */ [[nodiscard]] lf::base::size_type NumEvaluationNodes() const override { const auto Ns0 = edge_degrees_[0] > 1 ? qr_dual_edge_[0]->NumPoints() : 0; const auto Ns1 = edge_degrees_[1] > 1 ? qr_dual_edge_[1]->NumPoints() : 0; const auto Ns2 = edge_degrees_[2] > 1 ? qr_dual_edge_[2]->NumPoints() : 0; const lf::base::size_type Nt = qr_dual_tria_->NumPoints(); return 3 + Ns0 + Ns1 + Ns2 + Nt; } [[nodiscard]] Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> NodalValuesToDofs( const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> &nodevals) const override { const auto d0 = edge_degrees_[0] - 1; const auto d1 = edge_degrees_[1] - 1; const auto d2 = edge_degrees_[2] - 1; Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> dofs(NumRefShapeFunctions()); // Compute the basis function coefficients of the vertex basis functions dofs.segment(0, 3) = NodalValuesToVertexDofs(nodevals); // Compute the basis function coefficients on the edges dofs.segment(3, d0 + d1 + d2) = NodalValuesToEdgeDofs(nodevals); // Compute the basis function coefficients for the face bubbles dofs.segment(3 + d0 + d1 + d2, NumRefShapeFunctions(0)) = NodalValuesToFaceDofs(nodevals); // We need to orthogonalize the face bubble dual basis w.r.t. the // dual basis on the vertices and edges const Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> basis_functions = EvalReferenceShapeFunctions(EvaluationNodes()); const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> boundary_function = dofs.segment(0, 3 + d0 + d1 + d2) * basis_functions.block(0, 0, 3 + d0 + d1 + d2, basis_functions.cols()); const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> boundary_face_dofs = NodalValuesToFaceDofs(boundary_function); dofs.segment(3 + d0 + d1 + d2, NumRefShapeFunctions(0)) -= boundary_face_dofs; return dofs; } private: unsigned interior_degree_; // degree for inner shape functions std::array<unsigned, 3> edge_degrees_; // degree of the edges. std::array<const quad::QuadRule *, 3> qr_dual_edge_; // Quadrature rules for the edges. const lf::quad::QuadRule *qr_dual_tria_; nonstd::span<const lf::mesh::Orientation> rel_orient_; /* * @brief Compute the DOFs of the vertex functions from some * given nodal evaluations */ [[nodiscard]] Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> NodalValuesToVertexDofs( const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> &nodevals) const { Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> dofs(3); dofs[0] = nodevals[0]; dofs[1] = nodevals[1]; dofs[2] = nodevals[2]; return dofs; } /* * @brief Compute the DOFs of the edge functions from some * given nodal evaluations */ [[nodiscard]] Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> NodalValuesToEdgeDofs( const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> &nodevals) const { const auto Ns0 = edge_degrees_[0] > 1 ? qr_dual_edge_[0]->NumPoints() : 0; const auto Ns1 = edge_degrees_[1] > 1 ? qr_dual_edge_[1]->NumPoints() : 0; const auto Ns2 = edge_degrees_[2] > 1 ? qr_dual_edge_[2]->NumPoints() : 0; const lf::base::size_type Nt = qr_dual_tria_->NumPoints(); Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> dofs( edge_degrees_[0] + edge_degrees_[1] + edge_degrees_[2] - 3); // Compute the basis function coefficients on the edges // by applying the dual basis of the segment // first edge: for (base::size_type i = 2; i < edge_degrees_[0] + 1; ++i) { const SCALAR P0 = ilegendre_dx(i, 0); const SCALAR P1 = ilegendre_dx(i, 1); Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> psidd = qr_dual_edge_[0]->Points().unaryExpr( [&](double x) -> SCALAR { return legendre_dx(i - 1, x); }); const SCALAR integ1 = (qr_dual_edge_[0]->Weights().transpose().array() * psidd.array() * nodevals.segment(3, Ns0).array()) .sum(); if (rel_orient_[0] == lf::mesh::Orientation::positive) { dofs[1 + i - 3] = (P1 * nodevals[1] - P0 * nodevals[0] - integ1) * (2 * i - 1); } else { dofs[4 - i + (edge_degrees_[0] - 1) - 3] = (P1 * nodevals[0] - P0 * nodevals[1] - integ1) * (2 * i - 1); } } // Compute the basis function coefficients for the second edge for (base::size_type i = 2; i < edge_degrees_[1] + 1; ++i) { const SCALAR P0 = ilegendre_dx(i, 0); const SCALAR P1 = ilegendre_dx(i, 1); Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> psidd = qr_dual_edge_[1]->Points().unaryExpr( [&](double x) -> SCALAR { return legendre_dx(i - 1, x); }); const SCALAR integ2 = (qr_dual_edge_[1]->Weights().transpose().array() * psidd.array() * nodevals.segment(3 + Ns0, Ns1).array()) .sum(); if (rel_orient_[1] == lf::mesh::Orientation::positive) { dofs[1 + i + (edge_degrees_[0] - 1) - 3] = (P1 * nodevals[2] - P0 * nodevals[1] - integ2) * (2 * i - 1); } else { dofs[4 - i + (edge_degrees_[0] + edge_degrees_[1] - 2) - 3] = (P1 * nodevals[1] - P0 * nodevals[2] - integ2) * (2 * i - 1); } } // Compute the basis function coefficients for the second edge for (base::size_type i = 2; i < edge_degrees_[2] + 1; ++i) { const SCALAR P0 = ilegendre_dx(i, 0); const SCALAR P1 = ilegendre_dx(i, 1); Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> psidd = qr_dual_edge_[2]->Points().unaryExpr( [&](double x) -> SCALAR { return legendre_dx(i - 1, x); }); const SCALAR integ3 = (qr_dual_edge_[2]->Weights().transpose().array() * psidd.array() * nodevals.segment(3 + Ns0 + Ns1, Ns2).array()) .sum(); if (rel_orient_[2] == lf::mesh::Orientation::positive) { dofs[1 + i + (edge_degrees_[0] + edge_degrees_[1] - 2) - 3] = (P1 * nodevals[0] - P0 * nodevals[2] - integ3) * (2 * i - 1); } else { dofs[4 - i + (edge_degrees_[0] + edge_degrees_[1] + edge_degrees_[2] - 3) - 3] = (P1 * nodevals[2] - P0 * nodevals[0] - integ3) * (2 * i - 1); } } return dofs; } /* * @brief Compute the non-orthogonalized DOFs of the face bubbles from some * given nodal evaluations */ [[nodiscard]] Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> NodalValuesToFaceDofs( const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> &nodevals) const { const auto Ns0 = edge_degrees_[0] > 1 ? qr_dual_edge_[0]->NumPoints() : 0; const auto Ns1 = edge_degrees_[1] > 1 ? qr_dual_edge_[1]->NumPoints() : 0; const auto Ns2 = edge_degrees_[2] > 1 ? qr_dual_edge_[2]->NumPoints() : 0; const lf::base::size_type Ns = Ns0 + Ns1 + Ns2; const lf::base::size_type Nt = qr_dual_tria_->NumPoints(); Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> dofs(NumRefShapeFunctions(0)); if (interior_degree_ > 2) { unsigned idx = 0; const Eigen::Matrix<double, 1, Eigen::Dynamic> xnorm = (qr_dual_tria_->Points().row(0).array() / qr_dual_tria_->Points().row(1).array().unaryExpr([&](double y) { return 1 - y; })).matrix(); // We need to flip the local coordinates in case the // relative orientation is negative const Eigen::Matrix<double, 1, Eigen::Dynamic> xnorm_adj = rel_orient_[0] == lf::mesh::Orientation::positive ? xnorm : Eigen::RowVectorXd::Ones(Nt) - xnorm; const Eigen::Matrix<double, 1, Eigen::Dynamic> y = qr_dual_tria_->Points().row(1); // i is the degree of the edge function for (unsigned i = 0; i < interior_degree_ - 2; ++i) { const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> ypow = y.array() .unaryExpr( [&](double y) -> SCALAR { return std::pow(1 - y, i); }) .matrix(); const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> ypowp1 = y.array() .unaryExpr( [&](double y) -> SCALAR { return std::pow(1 - y, i + 1); }) .matrix(); const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> psidd = xnorm_adj.unaryExpr( [&](double x) -> SCALAR { return legendre_dx(i + 1, x); }); // j is the degree of the blending Jacobi polynomial for (unsigned j = 0; j < interior_degree_ - i - 2; ++j) { const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> jacdd = qr_dual_tria_->Points().row(1).unaryExpr([&](double y) -> SCALAR { return jacobi_dx(j, 2 * i + 4, y); }); const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> jacd = qr_dual_tria_->Points().row(1).unaryExpr([&](double y) -> SCALAR { return ijacobi_dx(j + 1, 2 * i + 4, y); }); dofs[idx] = (qr_dual_tria_->Weights().transpose().array() * nodevals.block(0, 3 + Ns, 1, Nt).array() * psidd.array() * (ypowp1.array() * jacdd.array() - (2 * i + 4) * ypow.array() * jacd.array())) .sum(); dofs[idx] *= 2 * i + 3; // Normalization factor for the Legendre polynomial dofs[idx] *= 2 * j + 2 * i + 5; // Normalization factor for the Jacobi Polynomial ++idx; } } } return dofs; } }; /** * @headerfile lf/fe/fe.h * @brief Hierarchic Finite Elements of arbitrary degree on quadrilaterals * * The basis functions on the quadrilateral has a tensor product structure and * can thus be represented by products of basis functions on segments. * The basis functions are therefore given by * \f[ * \widehat{b^{\square}}^{ij}(\widehat{x}, \widehat{y}) = * \widehat{b}^i(\widehat{x})\widehat{b}^j(\widehat{y}) \f] where * \f$\widehat{b}^i(\widehat{x})\f$ and \f$\widehat{b}^j(\widehat{y})\f$ are the * basis functions on a segment. * * The dual basis is therefore also quite simple, as we can recycle the one from * the segments by first applying the dual basis along the \f$x\f$-axis and then * apply the dual basis to the resulting 1d function. * * @note The Shape Functions are taken from the following paper: * https://arxiv.org/pdf/1504.03025.pdf * * @see ScalarReferenceFiniteElement */ template <typename SCALAR> class FeHierarchicQuad final : public ScalarReferenceFiniteElement<SCALAR> { public: FeHierarchicQuad(const FeHierarchicQuad &) = default; FeHierarchicQuad(FeHierarchicQuad &&) noexcept = default; FeHierarchicQuad &operator=(const FeHierarchicQuad &) = default; FeHierarchicQuad &operator=(FeHierarchicQuad &&) noexcept = default; ~FeHierarchicQuad() override = default; FeHierarchicQuad(unsigned interior_degree, std::array<unsigned, 4> edge_degrees, const quad::QuadRuleCache &qr_cache, nonstd::span<const lf::mesh::Orientation> rel_orient) : ScalarReferenceFiniteElement<SCALAR>(), interior_degree_(interior_degree), edge_degrees_(edge_degrees), qr_dual_edge_({&qr_cache.Get(lf::base::RefEl::kSegment(), 2 * (edge_degrees_[0] - 1)), &qr_cache.Get(lf::base::RefEl::kSegment(), 2 * (edge_degrees_[1] - 1)), &qr_cache.Get(lf::base::RefEl::kSegment(), 2 * (edge_degrees_[2] - 1)), &qr_cache.Get(lf::base::RefEl::kSegment(), 2 * (edge_degrees_[3] - 1))}), rel_orient_(rel_orient), fe1d_(std::max({interior_degree_, edge_degrees_[0], edge_degrees_[1], edge_degrees_[2], edge_degrees_[3]}), qr_cache) { LF_ASSERT_MSG(interior_degree_ >= 0, "illegal interior degree."); LF_ASSERT_MSG(edge_degrees_[0] >= 0, "illegal degree for edge 0"); LF_ASSERT_MSG(edge_degrees_[1] >= 0, "illegal degree for edge 1"); LF_ASSERT_MSG(edge_degrees_[2] >= 0, "illegal degree for edge 2"); LF_ASSERT_MSG(edge_degrees_[3] >= 0, "illegal degree for edge 3"); } [[nodiscard]] lf::base::RefEl RefEl() const override { return lf::base::RefEl::kQuad(); } [[nodiscard]] unsigned Degree() const override { return std::max({interior_degree_, edge_degrees_[0], edge_degrees_[1], edge_degrees_[2], edge_degrees_[3]}); } /** * @brief The local shape functions * @copydoc ScalarReferenceFiniteElement::NumRefShapeFunctions() */ [[nodiscard]] lf::base::size_type NumRefShapeFunctions() const override { return 4 + NumRefShapeFunctions(0) + NumRefShapeFunctions(1, 0) + NumRefShapeFunctions(1, 1) + NumRefShapeFunctions(1, 2) + NumRefShapeFunctions(1, 3); } /** * @brief One shape function for each vertex, p-1 shape functions on the edges * and (p-1)^2 shape functions on the quadrilateral * @copydoc ScalarReferenceFiniteElement::NumRefShapeFunctions(dim_t) const */ [[nodiscard]] lf::base::size_type NumRefShapeFunctions( dim_t codim) const override { switch (codim) { case 0: return (interior_degree_ - 1) * (interior_degree_ - 1); case 1: LF_VERIFY_MSG( edge_degrees_[0] == edge_degrees_[1] && edge_degrees_[0] == edge_degrees_[2] && edge_degrees_[0] == edge_degrees_[3], "You cannot call this method with codim=1 if the edges of the " "quad have a differing number of shape functions."); return edge_degrees_[0] - 1; case 2: return 1; default: LF_ASSERT_MSG(false, "Illegal codim " << codim); // Silence compiler warnings return 0; } } // clang-format off /** * @brief One shape function for each vertex, p-1 shape functions on the edges * and (p-1)^2 shape functions on the quadrilateral * @copydoc ScalarReferenceFiniteElement::NumRefShapeFunctions(dim_t,sub_idx_t) const */ // clang-format on [[nodiscard]] lf::base::size_type NumRefShapeFunctions( dim_t codim, sub_idx_t subidx) const override { switch (codim) { case 0: LF_ASSERT_MSG(subidx == 0, "illegal codim and subidex."); return NumRefShapeFunctions(0); case 1: LF_ASSERT_MSG(subidx >= 0 && subidx < 4, "illegal codim and subidx."); return edge_degrees_[subidx] - 1; case 2: LF_ASSERT_MSG(subidx >= 0 && subidx < 4, "illegal codim and subidx."); return 1; default: LF_VERIFY_MSG(false, "Illegal codim " << codim); // Silence compiler warnings return 0; } } [[nodiscard]] Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> EvalReferenceShapeFunctions(const Eigen::MatrixXd &refcoords) const override { Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> result( NumRefShapeFunctions(), refcoords.cols()); // Compute the 1D shape functions at the x and y coordinates const Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> sf1d_x = fe1d_.EvalReferenceShapeFunctions(refcoords.row(0)); const Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> sf1d_y = fe1d_.EvalReferenceShapeFunctions(refcoords.row(1)); const Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> sf1df_x = fe1d_.EvalReferenceShapeFunctions( Eigen::RowVectorXd::Constant(refcoords.cols(), 1) - refcoords.row(0)); const Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> sf1df_y = fe1d_.EvalReferenceShapeFunctions( Eigen::RowVectorXd::Constant(refcoords.cols(), 1) - refcoords.row(1)); // Get the basis functions associated with the vertices result.row(0) = (sf1d_x.row(0).array() * sf1d_y.row(0).array()).matrix(); result.row(1) = (sf1d_x.row(1).array() * sf1d_y.row(0).array()).matrix(); result.row(2) = (sf1d_x.row(1).array() * sf1d_y.row(1).array()).matrix(); result.row(3) = (sf1d_x.row(0).array() * sf1d_y.row(1).array()).matrix(); int current_dof = 4; // Get the basis functions associated with the first edge // as a tensor product of 1D basis functions for (int i = 0; i < edge_degrees_[0] - 1; ++i) { if (rel_orient_[0] == lf::mesh::Orientation::positive) { result.row(current_dof + i) = (sf1d_x.row(2 + i).array() * sf1d_y.row(0).array()).matrix(); } else { result.row(current_dof - 2 + edge_degrees_[0] - i) = (sf1df_x.row(2 + i).array() * sf1d_y.row(0).array()).matrix(); } } current_dof += edge_degrees_[0] - 1; // Get the basis functions associated with the second edge // as a tensor product of 1D basis functions for (int i = 0; i < edge_degrees_[1] - 1; ++i) { if (rel_orient_[1] == lf::mesh::Orientation::positive) { result.row(current_dof + i) = (sf1d_x.row(1).array() * sf1d_y.row(2 + i).array()).matrix(); } else { result.row(current_dof - 2 + edge_degrees_[1] - i) = (sf1d_x.row(1).array() * sf1df_y.row(2 + i).array()).matrix(); } } current_dof += edge_degrees_[1] - 1; // Get the basis functions associated with the third edge // as a tensor product of 1D basis functions for (int i = 0; i < edge_degrees_[2] - 1; ++i) { if (rel_orient_[2] == lf::mesh::Orientation::positive) { result.row(current_dof + i) = (sf1df_x.row(2 + i).array() * sf1d_y.row(1).array()).matrix(); } else { result.row(current_dof + edge_degrees_[2] - 2 - i) = (sf1d_x.row(2 + i).array() * sf1d_y.row(1).array()).matrix(); } } current_dof += edge_degrees_[2] - 1; // Get the basis functions associated with the fourth edge // as a tensor product of 1D basis functions for (int i = 0; i < edge_degrees_[3] - 1; ++i) { if (rel_orient_[3] == lf::mesh::Orientation::positive) { result.row(current_dof + i) = (sf1d_x.row(0).array() * sf1df_y.row(2 + i).array()).matrix(); } else { result.row(current_dof + edge_degrees_[3] - 2 - i) = (sf1d_x.row(0).array() * sf1d_y.row(2 + i).array()).matrix(); } } current_dof += edge_degrees_[3] - 1; // Get the basis functions associated with the interior of the quad // as a tensor product of 1D basis functions for (int i = 0; i < interior_degree_ - 1; ++i) { for (int j = 0; j < interior_degree_ - 1; ++j) { result.row(current_dof++) = (sf1d_x.row(j + 2).array() * sf1d_y.row(i + 2).array()).matrix(); } } LF_ASSERT_MSG(current_dof == result.rows(), "Not all rows have been filled."); return result; } [[nodiscard]] Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> GradientsReferenceShapeFunctions( const Eigen::MatrixXd &refcoords) const override { Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> result( NumRefShapeFunctions(), 2 * refcoords.cols()); // Compute the gradient of the 1D shape functions at the x and y coordinates const Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> sf1d_x = fe1d_.EvalReferenceShapeFunctions(refcoords.row(0)); const Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> sf1d_y = fe1d_.EvalReferenceShapeFunctions(refcoords.row(1)); const Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> sf1d_dx = fe1d_.GradientsReferenceShapeFunctions(refcoords.row(0)); const Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> sf1d_dy = fe1d_.GradientsReferenceShapeFunctions(refcoords.row(1)); // Compute the gradient of the flipped 1D shape functions at the x and y // coordinates const Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> sf1df_x = fe1d_.EvalReferenceShapeFunctions( Eigen::RowVectorXd::Constant(refcoords.cols(), 1) - refcoords.row(0)); const Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> sf1df_y = fe1d_.EvalReferenceShapeFunctions( Eigen::RowVectorXd::Constant(refcoords.cols(), 1) - refcoords.row(1)); const Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> sf1df_dx = fe1d_.GradientsReferenceShapeFunctions( Eigen::RowVectorXd::Constant(refcoords.cols(), 1) - refcoords.row(0)); const Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> sf1df_dy = fe1d_.GradientsReferenceShapeFunctions( Eigen::RowVectorXd::Constant(refcoords.cols(), 1) - refcoords.row(1)); for (Eigen::Index i = 0; i < refcoords.cols(); ++i) { // Get the gradient of the basis functions associated with the vertices result(0, 2 * i + 0) = sf1d_dx(0, i) * sf1d_y(0, i); result(0, 2 * i + 1) = sf1d_x(0, i) * sf1d_dy(0, i); result(1, 2 * i + 0) = sf1d_dx(1, i) * sf1d_y(0, i); result(1, 2 * i + 1) = sf1d_x(1, i) * sf1d_dy(0, i); result(2, 2 * i + 0) = sf1d_dx(1, i) * sf1d_y(1, i); result(2, 2 * i + 1) = sf1d_x(1, i) * sf1d_dy(1, i); result(3, 2 * i + 0) = sf1d_dx(0, i) * sf1d_y(1, i); result(3, 2 * i + 1) = sf1d_x(0, i) * sf1d_dy(1, i); int current_dof = 4; // Get the basis functions associated with the first edge for (int j = 0; j < edge_degrees_[0] - 1; ++j) { if (rel_orient_[0] == lf::mesh::Orientation::positive) { result(current_dof + j, 2 * i + 0) = sf1d_dx(2 + j, i) * sf1d_y(0, i); result(current_dof + j, 2 * i + 1) = sf1d_x(2 + j, i) * sf1d_dy(0, i); } else { result(current_dof + edge_degrees_[0] - 2 - j, 2 * i + 0) = -sf1df_dx(2 + j, i) * sf1d_y(0, i); result(current_dof + edge_degrees_[0] - 2 - j, 2 * i + 1) = sf1df_x(2 + j, i) * sf1d_dy(0, i); } } current_dof += edge_degrees_[0] - 1; // Get the basis functions associated with the second edge for (int j = 0; j < edge_degrees_[1] - 1; ++j) { if (rel_orient_[1] == lf::mesh::Orientation::positive) { result(current_dof + j, 2 * i + 0) = sf1d_dx(1, i) * sf1d_y(2 + j, i); result(current_dof + j, 2 * i + 1) = sf1d_x(1, i) * sf1d_dy(2 + j, i); } else { result(current_dof + edge_degrees_[1] - 2 - j, 2 * i + 0) = sf1d_dx(1, i) * sf1df_y(2 + j, i); result(current_dof + edge_degrees_[1] - 2 - j, 2 * i + 1) = sf1d_x(1, i) * -sf1df_dy(2 + j, i); } } current_dof += edge_degrees_[1] - 1; // Get the basis functions associated with the third edge for (int j = 0; j < edge_degrees_[2] - 1; ++j) { if (rel_orient_[2] == lf::mesh::Orientation::positive) { result(current_dof + j, 2 * i + 0) = -sf1df_dx(2 + j, i) * sf1d_y(1, i); result(current_dof + j, 2 * i + 1) = sf1df_x(2 + j, i) * sf1d_dy(1, i); } else { result(current_dof + edge_degrees_[2] - 2 - j, 2 * i + 0) = sf1d_dx(2 + j, i) * sf1d_y(1, i); result(current_dof + edge_degrees_[2] - 2 - j, 2 * i + 1) = sf1d_x(2 + j, i) * sf1d_dy(1, i); } } current_dof += edge_degrees_[2] - 1; // Get the basis functions associated with the fourth edge for (int j = 0; j < edge_degrees_[3] - 1; ++j) { if (rel_orient_[3] == lf::mesh::Orientation::positive) { result(current_dof + j, 2 * i + 0) = sf1d_dx(0, i) * sf1df_y(2 + j, i); result(current_dof + j, 2 * i + 1) = sf1d_x(0, i) * -sf1df_dy(2 + j, i); } else { result(current_dof + edge_degrees_[3] - 2 - j, 2 * i + 0) = sf1d_dx(0, i) * sf1d_y(2 + j, i); result(current_dof + edge_degrees_[3] - 2 - j, 2 * i + 1) = sf1d_x(0, i) * sf1d_dy(2 + j, i); } } current_dof += edge_degrees_[3] - 1; // Get the basis functions associated with the interior of the quad for (int j = 0; j < interior_degree_ - 1; ++j) { for (int k = 0; k < interior_degree_ - 1; ++k) { result(current_dof, 2 * i + 0) = sf1d_dx(k + 2, i) * sf1d_y(j + 2, i); result(current_dof++, 2 * i + 1) = sf1d_x(k + 2, i) * sf1d_dy(j + 2, i); } } } return result; } /** * @brief Evaluation nodes are the vertices, the points of * a quadrature rule on each edge and the points of a quadrature * rule on the interior of the quadrilateral. * @copydoc ScalarReferenceFiniteElement::EvaluationNodes() */ [[nodiscard]] Eigen::MatrixXd EvaluationNodes() const override { const base::size_type Ne0 = edge_degrees_[0] > 1 ? qr_dual_edge_[0]->NumPoints() : 0; const base::size_type Ne1 = edge_degrees_[1] > 1 ? qr_dual_edge_[1]->NumPoints() : 0; const base::size_type Ne2 = edge_degrees_[2] > 1 ? qr_dual_edge_[2]->NumPoints() : 0; const base::size_type Ne3 = edge_degrees_[3] > 1 ? qr_dual_edge_[3]->NumPoints() : 0; auto Nq = interior_degree_ > 1 ? fe1d_.NumEvaluationNodes() : 0; Eigen::MatrixXd nodes(2, 4 + Ne0 + Ne1 + Ne2 + Ne3 + Nq * Nq); // Add the vertices nodes(0, 0) = 0; nodes(1, 0) = 0; nodes(0, 1) = 1; nodes(1, 1) = 0; nodes(0, 2) = 1; nodes(1, 2) = 1; nodes(0, 3) = 0; nodes(1, 3) = 1; if (edge_degrees_[0] > 1) { // Add the quadrature points on the first edge if (rel_orient_[0] == lf::mesh::Orientation::positive) { nodes.block(0, 4, 1, Ne0) = qr_dual_edge_[0]->Points(); } else { nodes.block(0, 4, 1, Ne0) = Eigen::RowVectorXd::Ones(Ne0) - qr_dual_edge_[0]->Points(); } nodes.block(1, 4, 1, Ne0).setZero(); } if (edge_degrees_[1] > 1) { // Add the quadrature points on the second edge nodes.block(0, 4 + Ne0, 1, Ne1).setOnes(); if (rel_orient_[1] == lf::mesh::Orientation::positive) { nodes.block(1, 4 + Ne0, 1, Ne1) = qr_dual_edge_[1]->Points(); } else { nodes.block(1, 4 + Ne0, 1, Ne1) = Eigen::RowVectorXd::Ones(Ne1) - qr_dual_edge_[1]->Points(); } } if (edge_degrees_[2] > 1) { // Add the quadrature points on the third edge if (rel_orient_[2] == lf::mesh::Orientation::positive) { nodes.block(0, 4 + Ne0 + Ne1, 1, Ne2) = Eigen::RowVectorXd::Ones(Ne2) - qr_dual_edge_[2]->Points(); } else { nodes.block(0, 4 + Ne0 + Ne1, 1, Ne2) = qr_dual_edge_[2]->Points(); } nodes.block(1, 4 + Ne0 + Ne1, 1, Ne2).setOnes(); } if (edge_degrees_[3] > 1) { // Add the quadrature points on the fourth edge nodes.block(0, 4 + Ne0 + Ne1 + Ne2, 1, Ne3).setZero(); if (rel_orient_[3] == lf::mesh::Orientation::positive) { nodes.block(1, 4 + Ne0 + Ne1 + Ne2, 1, Ne3) = Eigen::RowVectorXd::Ones(Ne3) - qr_dual_edge_[3]->Points(); } else { nodes.block(1, 4 + Ne0 + Ne1 + Ne2, 1, Ne3) = qr_dual_edge_[3]->Points(); } } if (interior_degree_ > 1) { // Add the quadrature points for the face auto points = fe1d_.EvaluationNodes(); for (lf::base::size_type i = 0; i < Nq; ++i) { nodes.block(0, 4 + Ne0 + Ne1 + Ne2 + Ne3 + i * Nq, 1, Nq) = points; nodes.block(1, 4 + Ne0 + Ne1 + Ne2 + Ne3 + i * Nq, 1, Nq) .setConstant(points(0, i)); } } return nodes; } /** * @copydoc ScalarReferenceFiniteElement::NumEvaluationNodes() */ [[nodiscard]] lf::base::size_type NumEvaluationNodes() const override { const base::size_type Ne0 = edge_degrees_[0] > 1 ? qr_dual_edge_[0]->NumPoints() : 0; const base::size_type Ne1 = edge_degrees_[1] > 1 ? qr_dual_edge_[1]->NumPoints() : 0; const base::size_type Ne2 = edge_degrees_[2] > 1 ? qr_dual_edge_[2]->NumPoints() : 0; const base::size_type Ne3 = edge_degrees_[3] > 1 ? qr_dual_edge_[3]->NumPoints() : 0; const lf::base::size_type Nq = interior_degree_ > 1 ? fe1d_.NumEvaluationNodes() : 0; return 4 + Ne0 + Ne1 + Ne2 + Ne3 + Nq * Nq; } [[nodiscard]] Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> NodalValuesToDofs( const Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> &nodevals) const override { Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> dofs(NumRefShapeFunctions()); const base::size_type Ne0 = edge_degrees_[0] > 1 ? qr_dual_edge_[0]->NumPoints() : 0; const base::size_type Ne1 = edge_degrees_[1] > 1 ? qr_dual_edge_[1]->NumPoints() : 0; const base::size_type Ne2 = edge_degrees_[2] > 1 ? qr_dual_edge_[2]->NumPoints() : 0; const base::size_type Ne3 = edge_degrees_[3] > 1 ? qr_dual_edge_[3]->NumPoints() : 0; // Compute the basis function coefficients of the vertex basis functions dofs[0] = nodevals[0]; dofs[1] = nodevals[1]; dofs[2] = nodevals[2]; dofs[3] = nodevals[3]; // Compute the basis function coefficients on the edges // by applying the dual basis of the segment for (lf::base::size_type i = 2; i < Degree() + 1; ++i) { const SCALAR P0 = ilegendre_dx(i, 0); const SCALAR P1 = ilegendre_dx(i, 1); // Compute the basis function coefficients for the first edge if (i <= edge_degrees_[0]) { Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> psidd = qr_dual_edge_[0]->Points().unaryExpr( [&](double x) -> SCALAR { return legendre_dx(i - 1, x); }); const SCALAR integ1 = (qr_dual_edge_[0]->Weights().transpose().array() * psidd.array() * nodevals.segment(4, Ne0).array()) .sum(); if (rel_orient_[0] == lf::mesh::Orientation::positive) { dofs[2 + i] = (P1 * nodevals[1] - P0 * nodevals[0] - integ1) * (2 * i - 1); } else { dofs[5 - i + (edge_degrees_[0] - 1)] = (P1 * nodevals[0] - P0 * nodevals[1] - integ1) * (2 * i - 1); } } if (i <= edge_degrees_[1]) { // Compute the basis function coefficients for the second edge Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> psidd = qr_dual_edge_[1]->Points().unaryExpr( [&](double x) -> SCALAR { return legendre_dx(i - 1, x); }); const SCALAR integ2 = (qr_dual_edge_[1]->Weights().transpose().array() * psidd.array() * nodevals.segment(4 + Ne0, Ne1).array()) .sum(); if (rel_orient_[1] == lf::mesh::Orientation::positive) { dofs[2 + i + (edge_degrees_[0] - 1)] = (P1 * nodevals[2] - P0 * nodevals[1] - integ2) * (2 * i - 1); } else { dofs[5 - i + (edge_degrees_[0] + edge_degrees_[1] - 2)] = (P1 * nodevals[1] - P0 * nodevals[2] - integ2) * (2 * i - 1); } } if (i <= edge_degrees_[2]) { // Compute the basis function coefficients for the third edge Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> psidd = qr_dual_edge_[2]->Points().unaryExpr( [&](double x) -> SCALAR { return legendre_dx(i - 1, x); }); const SCALAR integ3 = (qr_dual_edge_[2]->Weights().transpose().array() * psidd.array() * nodevals.segment(4 + Ne0 + Ne1, Ne2).array()) .sum(); if (rel_orient_[2] == lf::mesh::Orientation::positive) { dofs[2 + i + (edge_degrees_[0] + edge_degrees_[1] - 2)] = (P1 * nodevals[3] - P0 * nodevals[2] - integ3) * (2 * i - 1); } else { dofs[5 - i + (edge_degrees_[0] + edge_degrees_[1] + edge_degrees_[2] - 3)] = (P1 * nodevals[2] - P0 * nodevals[3] - integ3) * (2 * i - 1); } } if (i <= edge_degrees_[3]) { // Compute the basis function coefficients for the fourth edge Eigen::Matrix<SCALAR, 1, Eigen::Dynamic> psidd = qr_dual_edge_[3]->Points().unaryExpr( [&](double x) -> SCALAR { return legendre_dx(i - 1, x); }); const SCALAR integ4 = (qr_dual_edge_[3]->Weights().transpose().array() * psidd.array() * nodevals.segment(4 + Ne0 + Ne1 + Ne2, Ne3).array()) .sum(); if (rel_orient_[3] == lf::mesh::Orientation::positive) { dofs[2 + i + (edge_degrees_[0] + edge_degrees_[1] + edge_degrees_[2] - 3)] = (P1 * nodevals[0] - P0 * nodevals[3] - integ4) * (2 * i - 1); } else { dofs[5 - i + (edge_degrees_[0] + edge_degrees_[1] + edge_degrees_[2] + edge_degrees_[3] - 4)] = (P1 * nodevals[3] - P0 * nodevals[0] - integ4) * (2 * i - 1); } } } if (interior_degree_ > 1) { // Compute the basis function coefficients for the face bubbles auto Nq = fe1d_.NumEvaluationNodes(); Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> dof_temp( Nq, interior_degree_ - 1); for (unsigned i = 0; i < Nq; ++i) { dof_temp.row(i) = fe1d_ .NodalValuesToDofs(nodevals.segment( 4 + Ne0 + Ne1 + Ne2 + Ne3 + Nq * i, Nq)) .segment(2, interior_degree_ - 1); } Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> dof_temp2( interior_degree_ - 1, interior_degree_ - 1); for (unsigned i = 0; i < interior_degree_ - 1; ++i) { dofs.segment(edge_degrees_[0] + edge_degrees_[1] + edge_degrees_[2] + edge_degrees_[3] + i * (interior_degree_ - 1), interior_degree_ - 1) = dof_temp2.row(i) = fe1d_.NodalValuesToDofs(dof_temp.col(i)) .segment(2, interior_degree_ - 1); } dofs.segment(edge_degrees_[0] + edge_degrees_[1] + edge_degrees_[2] + edge_degrees_[3], (interior_degree_ - 1) * (interior_degree_ - 1)) = Eigen::Map<Eigen::Matrix<SCALAR, 1, Eigen::Dynamic>>( dof_temp2.data(), 1, (interior_degree_ - 1) * (interior_degree_ - 1)); } return dofs; } private: unsigned interior_degree_; std::array<unsigned, 4> edge_degrees_; std::array<const quad::QuadRule *, 4> qr_dual_edge_; FeHierarchicSegment<SCALAR> fe1d_; // degree = max(interior_degree_, edge_degrees_) nonstd::span<const lf::mesh::Orientation> rel_orient_; }; } // end namespace lf::fe #endif // LF_USCALFE_HP_FE_H_
43.165848
88
0.58501
[ "mesh", "shape", "vector" ]
00248ac8056d1f0a1c412f9564fc6e24bd7b7ee8
1,126
h
C
ospray/common/Group.h
TOMiii9/ospray
c902dca37f165e01365e51b6bba107dcc53a6842
[ "Apache-2.0" ]
2
2022-01-20T19:28:39.000Z
2022-01-21T00:14:07.000Z
ospray/common/Group.h
TOMiii9/ospray
c902dca37f165e01365e51b6bba107dcc53a6842
[ "Apache-2.0" ]
1
2020-04-24T22:15:32.000Z
2020-04-24T22:15:32.000Z
ospray/common/Group.h
TOMiii9/ospray
c902dca37f165e01365e51b6bba107dcc53a6842
[ "Apache-2.0" ]
1
2021-05-19T17:45:06.000Z
2021-05-19T17:45:06.000Z
// Copyright 2009-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #pragma once // ospray stuff #include "../geometry/GeometricModel.h" #include "../volume/VolumetricModel.h" #include "./Data.h" #include "./Managed.h" // stl #include <vector> // embree #include "embree3/rtcore.h" namespace ospray { struct OSPRAY_SDK_INTERFACE Group : public ManagedObject { Group(); ~Group() override; std::string toString() const override; void commit() override; box3f getBounds() const override; // Data members // Ref<const DataT<GeometricModel *>> geometricModels; std::vector<void *> geometryIEs; std::vector<void *> geometricModelIEs; Ref<const DataT<VolumetricModel *>> volumetricModels; std::vector<void *> volumeIEs; std::vector<void *> volumetricModelIEs; Ref<const DataT<GeometricModel *>> clipModels; std::vector<void *> clipIEs; std::vector<void *> clipModelIEs; int numInvertedClippers{0}; RTCScene sceneGeometries{nullptr}; RTCScene sceneVolumes{nullptr}; RTCScene sceneClippers{nullptr}; }; OSPTYPEFOR_SPECIALIZATION(Group *, OSP_GROUP); } // namespace ospray
22.078431
56
0.726465
[ "geometry", "vector" ]
0027d22a86a3e107b48643937acf888a872a1866
415
h
C
3DLfC4D/source/CameraHook.h
FilipMalmberg/3Delight-for-Cinema-4D
3394f8cd9e1121b8c35aa4e2b2443450ef82cbff
[ "MIT" ]
null
null
null
3DLfC4D/source/CameraHook.h
FilipMalmberg/3Delight-for-Cinema-4D
3394f8cd9e1121b8c35aa4e2b2443450ef82cbff
[ "MIT" ]
null
null
null
3DLfC4D/source/CameraHook.h
FilipMalmberg/3Delight-for-Cinema-4D
3394f8cd9e1121b8c35aa4e2b2443450ef82cbff
[ "MIT" ]
null
null
null
#ifndef CAMERA_HOOK_H #define CAMERA_HOOK_H #pragma warning(disable : 4265) #include "DL_HookPlugin.h" #include "c4d.h" #include <vector> class CameraHook:public DL_HookPlugin{ public: void CreateNSINodes(BaseDocument* doc, DL_SceneParser* parser); void SampleMotion(DL_SampleInfo* info, BaseDocument* document, DL_SceneParser* parser); private: CameraObject* camera; std::string transform_name; }; #endif
20.75
88
0.785542
[ "vector" ]
00378298d54db0e7ed916333821cea02b6a02847
993
h
C
RpcApiStorage/ApiStorage.h
dshadrin/RpcWrappersGenerator
9a8ac6bebbaf73f26324f4444f6d1d620e3e9a75
[ "Apache-2.0" ]
null
null
null
RpcApiStorage/ApiStorage.h
dshadrin/RpcWrappersGenerator
9a8ac6bebbaf73f26324f4444f6d1d620e3e9a75
[ "Apache-2.0" ]
null
null
null
RpcApiStorage/ApiStorage.h
dshadrin/RpcWrappersGenerator
9a8ac6bebbaf73f26324f4444f6d1d620e3e9a75
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2014-2017 Rhonda Software. * All rights reserved. */ #ifndef __API_STORAGE_H #define __API_STORAGE_H #pragma once ////////////////////////////////////////////////////////////////////////// #include "ApiItems.h" ////////////////////////////////////////////////////////////////////////// class ApiStorage : public ApiStorageInterface { public: ApiStorage(const StorageParameters& params); ~ApiStorage(); // check if node with tag <tag> need to be added bool IsHandleTag(const std::string& tagName) const; // add data from XML node void AddNode(const std::string& tagName, const std::map<std::string, std::string>& attrMap); // parsing and store data void LoadXmlData(); private: EItemTag TagName2TagValue(const std::string& name); private: StorageParameters m_params; static const std::vector<std::string> nodeNames; }; ////////////////////////////////////////////////////////////////////////// #endif // __API_STORAGE_H
24.219512
96
0.548842
[ "vector" ]
003cdf060bbb64cfe01f17f12def2db12eaf2e1d
196
h
C
ionWindow/SFileDroppedEvent.h
iondune/ionEngine
7ce3394dafbabf0e0bb9f5d07dbfae31161800d4
[ "MIT" ]
36
2015-06-28T14:53:06.000Z
2021-10-31T04:26:53.000Z
ionWindow/SFileDroppedEvent.h
iondune/ionEngine
7ce3394dafbabf0e0bb9f5d07dbfae31161800d4
[ "MIT" ]
90
2015-05-01T07:21:43.000Z
2017-08-30T01:16:41.000Z
ionWindow/SFileDroppedEvent.h
iondune/ionEngine
7ce3394dafbabf0e0bb9f5d07dbfae31161800d4
[ "MIT" ]
9
2016-04-08T07:48:02.000Z
2019-07-22T15:13:53.000Z
#pragma once #include <ionCore.h> namespace ion { class CWindow; struct SFileDroppedEvent : public IEvent { vector<string> Paths; CWindow * Window = nullptr; }; }
10.315789
42
0.617347
[ "vector" ]
003cebc495cbff11b555bfc8f21824b7ecb0eb2e
4,601
h
C
src/lepage/input/SourceLocationProvider.h
jaydee-io/lepage
30ec14fa809e4e60de64ac7e5bf1f06ee71c93cf
[ "BSD-3-Clause" ]
null
null
null
src/lepage/input/SourceLocationProvider.h
jaydee-io/lepage
30ec14fa809e4e60de64ac7e5bf1f06ee71c93cf
[ "BSD-3-Clause" ]
null
null
null
src/lepage/input/SourceLocationProvider.h
jaydee-io/lepage
30ec14fa809e4e60de64ac7e5bf1f06ee71c93cf
[ "BSD-3-Clause" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // lepage // // This file is distributed under the 3-clause Berkeley Software Distribution // License. See LICENSE for details. //////////////////////////////////////////////////////////////////////////////// #ifndef LEPAGE_SOURCE_LOCATION_PROVIDER_H #define LEPAGE_SOURCE_LOCATION_PROVIDER_H #include <lepage/input/SourceLocation.h> #include <cstddef> #include <vector> namespace lepage::input { /* * SourceLocationProvider */ template<typename CharT = char> class SourceLocationProvider { public: inline constexpr SourceLocation currentLocation(void) const noexcept; inline constexpr SourceLocation previousLocation(void) const noexcept; inline constexpr void forward(CharT character) noexcept; inline constexpr void backward(void) noexcept; private: inline constexpr bool isStartLocation(void) const noexcept; inline constexpr bool isFirstLine(void) const noexcept; inline constexpr bool isFirstColumn(void) const noexcept; inline constexpr bool isLineFeed(CharT character) const noexcept; inline constexpr bool isCarriageReturn(CharT character) const noexcept; inline constexpr std::uint_least32_t lastColumnOfLine(std::uint_least32_t line) const noexcept; SourceLocation currentLocation_; CharT previousCharacter = '\0'; std::size_t currentOffset_ = 0; std::vector<std::size_t> newLineOffset_ = { currentOffset_ }; //< Offset (number of characters) of each newline from begining }; /* * SourceLocationProvider implementation */ template<typename CharT> inline constexpr SourceLocation SourceLocationProvider<CharT>::currentLocation(void) const noexcept { return currentLocation_; } template<typename CharT> inline constexpr SourceLocation SourceLocationProvider<CharT>::previousLocation(void) const noexcept { // Don't go back from first location if(isStartLocation()) return currentLocation_; // Previous location is at end of previous line (First location needs to be checked first) if(isFirstColumn()) return { currentLocation_.line - 1, lastColumnOfLine(currentLocation_.line - 1) }; // Just go one column back return { currentLocation_.line, currentLocation_.column - 1 }; } template<typename CharT> inline constexpr void SourceLocationProvider<CharT>::forward(CharT character) noexcept { // Handle special case of Windows new line : Carriage Return followed by Line Feed // if(not isFirstLine() and isFirstColumn() and isLineFeed(character)) if(isCarriageReturn(previousCharacter) and isLineFeed(character)) backward(); // Move forward currentLocation_.column++; currentOffset_++; previousCharacter = character; // Newline if(isLineFeed(character) or isCarriageReturn(character)) { currentLocation_.line++; currentLocation_.column = 1; newLineOffset_.push_back(currentOffset_); } } template<typename CharT> inline constexpr void SourceLocationProvider<CharT>::backward(void) noexcept { if(isStartLocation()) return; auto needToRemoveLastNewLine = isFirstColumn(); currentLocation_ = previousLocation(); currentOffset_--; if(needToRemoveLastNewLine) newLineOffset_.pop_back(); } template<typename CharT> inline constexpr bool SourceLocationProvider<CharT>::isStartLocation(void) const noexcept { return isFirstLine() and isFirstColumn(); } template<typename CharT> inline constexpr bool SourceLocationProvider<CharT>::isFirstLine(void) const noexcept { return currentLocation_.line <= 1; } template<typename CharT> inline constexpr bool SourceLocationProvider<CharT>::isFirstColumn(void) const noexcept { return currentLocation_.column <= 1; } template<typename CharT> inline constexpr bool SourceLocationProvider<CharT>::isLineFeed(CharT character) const noexcept { return character == CharT('\n'); } template<typename CharT> inline constexpr bool SourceLocationProvider<CharT>::isCarriageReturn(CharT character) const noexcept { return character == CharT('\r'); } template<typename CharT> inline constexpr std::uint_least32_t SourceLocationProvider<CharT>::lastColumnOfLine(std::uint_least32_t line) const noexcept { if(line > newLineOffset_.size()) return 0; return newLineOffset_[line] - newLineOffset_[line - 1]; } }; // namespace lepage::input #endif /* LEPAGE_SOURCE_LOCATION_PROVIDER_H */
31.513699
129
0.708759
[ "vector" ]
003de195596d629bb13a771067219c925538146d
20,677
h
C
Scripts/Template/Headers/java/util/Hashtable.h
zhouxl/J2ObjC-Framework
ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1
[ "MIT" ]
null
null
null
Scripts/Template/Headers/java/util/Hashtable.h
zhouxl/J2ObjC-Framework
ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1
[ "MIT" ]
null
null
null
Scripts/Template/Headers/java/util/Hashtable.h
zhouxl/J2ObjC-Framework
ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1
[ "MIT" ]
null
null
null
// // Generated by the J2ObjC translator. DO NOT EDIT! // source: android/platform/libcore/ojluni/src/main/java/java/util/Hashtable.java // #include "../../J2ObjC_header.h" #pragma push_macro("INCLUDE_ALL_JavaUtilHashtable") #ifdef RESTRICT_JavaUtilHashtable #define INCLUDE_ALL_JavaUtilHashtable 0 #else #define INCLUDE_ALL_JavaUtilHashtable 1 #endif #undef RESTRICT_JavaUtilHashtable #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #if __has_feature(nullability) #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wnullability" #pragma GCC diagnostic ignored "-Wnullability-completeness" #endif #if !defined (JavaUtilHashtable_) && (INCLUDE_ALL_JavaUtilHashtable || defined(INCLUDE_JavaUtilHashtable)) #define JavaUtilHashtable_ #define RESTRICT_JavaUtilDictionary 1 #define INCLUDE_JavaUtilDictionary 1 #include "../../java/util/Dictionary.h" #define RESTRICT_JavaUtilMap 1 #define INCLUDE_JavaUtilMap 1 #include "../../java/util/Map.h" #define RESTRICT_JavaIoSerializable 1 #define INCLUDE_JavaIoSerializable 1 #include "../../java/io/Serializable.h" @protocol JavaUtilCollection; @protocol JavaUtilEnumeration; @protocol JavaUtilFunctionBiConsumer; @protocol JavaUtilFunctionBiFunction; @protocol JavaUtilFunctionFunction; @protocol JavaUtilSet; /*! @brief This class implements a hash table, which maps keys to values.Any non-<code>null</code> object can be used as a key or as a value. <p> To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the <code>hashCode</code> method and the <code>equals</code> method. <p> An instance of <code>Hashtable</code> has two parameters that affect its performance: <i>initial capacity</i> and <i>load factor</i>. The <i>capacity</i> is the number of <i>buckets</i> in the hash table, and the <i>initial capacity</i> is simply the capacity at the time the hash table is created. Note that the hash table is <i>open</i>: in the case of a "hash collision", a single bucket stores multiple entries, which must be searched sequentially. The <i>load factor</i> is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.<p> Generally, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most <tt>Hashtable</tt> operations, including <tt>get</tt> and <tt>put</tt>).<p> The initial capacity controls a tradeoff between wasted space and the need for <code>rehash</code> operations, which are time-consuming. No <code>rehash</code> operations will <i>ever</i> occur if the initial capacity is greater than the maximum number of entries the <tt>Hashtable</tt> will contain divided by its load factor. However, setting the initial capacity too high can waste space.<p> If many entries are to be made into a <code>Hashtable</code>, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table. <p> This example creates a hashtable of numbers. It uses the names of the numbers as keys: @code Hashtable<String, Integer> numbers = new Hashtable<String, Integer>(); numbers.put("one", 1); numbers.put("two", 2); numbers.put("three", 3); @endcode <p>To retrieve a number, use the following code: @code Integer n = numbers.get("two"); if (n != null) { System.out.println("two = " + n); } @endcode <p>The iterators returned by the <tt>iterator</tt> method of the collections returned by all of this class's "collection view methods" are <em>fail-fast</em>: if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own <tt>remove</tt> method, the iterator will throw a <code>ConcurrentModificationException</code> . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. The Enumerations returned by Hashtable's keys and elements methods are <em>not</em> fail-fast. <p>Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw <tt>ConcurrentModificationException</tt> on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: <i>the fail-fast behavior of iterators should be used only to detect bugs.</i> <p>As of the Java 2 platform v1.2, this class was retrofitted to implement the <code>Map</code> interface, making it a member of the <a href="{@@docRoot}/../technotes/guides/collections/index.html"> Java Collections Framework</a>. Unlike the new collection implementations, <code>Hashtable</code> is synchronized. If a thread-safe implementation is not needed, it is recommended to use <code>HashMap</code> in place of <code>Hashtable</code>. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use <code>java.util.concurrent.ConcurrentHashMap</code> in place of <code>Hashtable</code>. @author Arthur van Hoff @author Josh Bloch @author Neal Gafter - seealso: Object#equals(java.lang.Object) - seealso: Object#hashCode() - seealso: Hashtable#rehash() - seealso: Collection - seealso: Map - seealso: HashMap - seealso: TreeMap @since JDK1.0 */ @interface JavaUtilHashtable : JavaUtilDictionary < JavaUtilMap, NSCopying, JavaIoSerializable > #pragma mark Public /*! @brief Constructs a new, empty hashtable with a default initial capacity (11) and load factor (0.75). */ - (instancetype __nonnull)init; /*! @brief Constructs a new, empty hashtable with the specified initial capacity and default load factor (0.75). @param initialCapacity the initial capacity of the hashtable. @throw IllegalArgumentExceptionif the initial capacity is less than zero. */ - (instancetype __nonnull)initWithInt:(jint)initialCapacity; /*! @brief Constructs a new, empty hashtable with the specified initial capacity and the specified load factor. @param initialCapacity the initial capacity of the hashtable. @param loadFactor the load factor of the hashtable. @throw IllegalArgumentExceptionif the initial capacity is less than zero, or if the load factor is nonpositive. */ - (instancetype __nonnull)initWithInt:(jint)initialCapacity withFloat:(jfloat)loadFactor; /*! @brief Constructs a new hashtable with the same mappings as the given Map.The hashtable is created with an initial capacity sufficient to hold the mappings in the given Map and a default load factor (0.75). @param t the map whose mappings are to be placed in this map. @throw NullPointerExceptionif the specified map is null. @since 1.2 */ - (instancetype __nonnull)initWithJavaUtilMap:(id<JavaUtilMap>)t; /*! @brief Clears this hashtable so that it contains no keys. */ - (void)clear; /*! @brief Creates a shallow copy of this hashtable.All the structure of the hashtable itself is copied, but the keys and values are not cloned. This is a relatively expensive operation. @return a clone of the hashtable */ - (id)java_clone; - (id)computeWithId:(id)key withJavaUtilFunctionBiFunction:(id<JavaUtilFunctionBiFunction>)remappingFunction; - (id)computeIfAbsentWithId:(id)key withJavaUtilFunctionFunction:(id<JavaUtilFunctionFunction>)mappingFunction; - (id)computeIfPresentWithId:(id)key withJavaUtilFunctionBiFunction:(id<JavaUtilFunctionBiFunction>)remappingFunction; /*! @brief Tests if some key maps into the specified value in this hashtable. This operation is more expensive than the <code>containsKey</code> method. <p>Note that this method is identical in functionality to <code>containsValue</code>, (which is part of the <code>Map</code> interface in the collections framework). @param value a value to search for @return <code>true</code> if and only if some key maps to the <code>value</code> argument in this hashtable as determined by the <tt>equals</tt> method; <code>false</code> otherwise. @throw NullPointerExceptionif the value is <code>null</code> */ - (jboolean)containsWithId:(id)value; /*! @brief Tests if the specified object is a key in this hashtable. @param key possible key @return <code>true</code> if and only if the specified object is a key in this hashtable, as determined by the <tt>equals</tt> method; <code>false</code> otherwise. @throw NullPointerExceptionif the key is <code>null</code> - seealso: #contains(Object) */ - (jboolean)containsKeyWithId:(id)key; /*! @brief Returns true if this hashtable maps one or more keys to this value. <p>Note that this method is identical in functionality to <code>contains</code> (which predates the <code>Map</code> interface). @param value value whose presence in this hashtable is to be tested @return <tt>true</tt> if this map maps one or more keys to the specified value @throw NullPointerExceptionif the value is <code>null</code> @since 1.2 */ - (jboolean)containsValueWithId:(id)value; /*! @brief Returns an enumeration of the values in this hashtable. Use the Enumeration methods on the returned object to fetch the elements sequentially. @return an enumeration of the values in this hashtable. - seealso: java.util.Enumeration - seealso: #keys() - seealso: #values() - seealso: Map */ - (id<JavaUtilEnumeration>)elements; /*! @brief Returns a <code>Set</code> view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own <tt>remove</tt> operation, or through the <tt>setValue</tt> operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> operations. It does not support the <tt>add</tt> or <tt>addAll</tt> operations. @since 1.2 */ - (id<JavaUtilSet>)entrySet; /*! @brief Compares the specified Object with this Map for equality, as per the definition in the Map interface. @param o object to be compared for equality with this hashtable @return true if the specified Object is equal to this Map - seealso: Map#equals(Object) @since 1.2 */ - (jboolean)isEqual:(id)o; - (void)forEachWithJavaUtilFunctionBiConsumer:(id<JavaUtilFunctionBiConsumer>)action; /*! @brief Returns the value to which the specified key is mapped, or <code>null</code> if this map contains no mapping for the key. <p>More formally, if this map contains a mapping from a key <code>k</code> to a value <code>v</code> such that <code>(key.equals(k))</code>, then this method returns <code>v</code>; otherwise it returns <code>null</code>. (There can be at most one such mapping.) @param key the key whose associated value is to be returned @return the value to which the specified key is mapped, or <code>null</code> if this map contains no mapping for the key @throw NullPointerExceptionif the specified key is null - seealso: #put(Object, Object) */ - (id)getWithId:(id)key; - (id)getOrDefaultWithId:(id)key withId:(id)defaultValue; /*! @brief Returns the hash code value for this Map as per the definition in the Map interface. - seealso: Map#hashCode() @since 1.2 */ - (NSUInteger)hash; /*! @brief Tests if this hashtable maps no keys to values. @return <code>true</code> if this hashtable maps no keys to values; <code>false</code> otherwise. */ - (jboolean)isEmpty; /*! @brief Returns an enumeration of the keys in this hashtable. @return an enumeration of the keys in this hashtable. - seealso: Enumeration - seealso: #elements() - seealso: #keySet() - seealso: Map */ - (id<JavaUtilEnumeration>)keys; /*! @brief Returns a <code>Set</code> view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own <tt>remove</tt> operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not support the <tt>add</tt> or <tt>addAll</tt> operations. @since 1.2 */ - (id<JavaUtilSet>)keySet; - (id)mergeWithId:(id)key withId:(id)value withJavaUtilFunctionBiFunction:(id<JavaUtilFunctionBiFunction>)remappingFunction; /*! @brief Maps the specified <code>key</code> to the specified <code>value</code> in this hashtable.Neither the key nor the value can be <code>null</code>. <p> The value can be retrieved by calling the <code>get</code> method with a key that is equal to the original key. @param key the hashtable key @param value the value @return the previous value of the specified key in this hashtable, or <code>null</code> if it did not have one @throw NullPointerExceptionif the key or value is <code>null</code> - seealso: Object#equals(Object) - seealso: #get(Object) */ - (id)putWithId:(id)key withId:(id)value; /*! @brief Copies all of the mappings from the specified map to this hashtable. These mappings will replace any mappings that this hashtable had for any of the keys currently in the specified map. @param t mappings to be stored in this map @throw NullPointerExceptionif the specified map is null @since 1.2 */ - (void)putAllWithJavaUtilMap:(id<JavaUtilMap>)t; - (id)putIfAbsentWithId:(id)key withId:(id)value; /*! @brief Removes the key (and its corresponding value) from this hashtable.This method does nothing if the key is not in the hashtable. @param key the key that needs to be removed @return the value to which the key had been mapped in this hashtable, or <code>null</code> if the key did not have a mapping @throw NullPointerExceptionif the key is <code>null</code> */ - (id)removeWithId:(id)key; - (jboolean)removeWithId:(id)key withId:(id)value; - (id)replaceWithId:(id)key withId:(id)value; - (jboolean)replaceWithId:(id)key withId:(id)oldValue withId:(id)newValue; - (void)replaceAllWithJavaUtilFunctionBiFunction:(id<JavaUtilFunctionBiFunction>)function; /*! @brief Returns the number of keys in this hashtable. @return the number of keys in this hashtable. */ - (jint)size; /*! @brief Returns a string representation of this <tt>Hashtable</tt> object in the form of a set of entries, enclosed in braces and separated by the ASCII characters "<tt>,&nbsp;</tt>" (comma and space).Each entry is rendered as the key, an equals sign <tt>=</tt>, and the associated element, where the <tt>toString</tt> method is used to convert the key and element to strings. @return a string representation of this hashtable */ - (NSString *)description; /*! @brief Returns a <code>Collection</code> view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator's own <tt>remove</tt> operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> operations. It does not support the <tt>add</tt> or <tt>addAll</tt> operations. @since 1.2 */ - (id<JavaUtilCollection>)values; #pragma mark Protected /*! @brief Increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently.This method is called automatically when the number of keys in the hashtable exceeds this hashtable's capacity and load factor. */ - (void)rehash; @end J2OBJC_EMPTY_STATIC_INIT(JavaUtilHashtable) FOUNDATION_EXPORT void JavaUtilHashtable_initWithInt_withFloat_(JavaUtilHashtable *self, jint initialCapacity, jfloat loadFactor); FOUNDATION_EXPORT JavaUtilHashtable *new_JavaUtilHashtable_initWithInt_withFloat_(jint initialCapacity, jfloat loadFactor) NS_RETURNS_RETAINED; FOUNDATION_EXPORT JavaUtilHashtable *create_JavaUtilHashtable_initWithInt_withFloat_(jint initialCapacity, jfloat loadFactor); FOUNDATION_EXPORT void JavaUtilHashtable_initWithInt_(JavaUtilHashtable *self, jint initialCapacity); FOUNDATION_EXPORT JavaUtilHashtable *new_JavaUtilHashtable_initWithInt_(jint initialCapacity) NS_RETURNS_RETAINED; FOUNDATION_EXPORT JavaUtilHashtable *create_JavaUtilHashtable_initWithInt_(jint initialCapacity); FOUNDATION_EXPORT void JavaUtilHashtable_init(JavaUtilHashtable *self); FOUNDATION_EXPORT JavaUtilHashtable *new_JavaUtilHashtable_init(void) NS_RETURNS_RETAINED; FOUNDATION_EXPORT JavaUtilHashtable *create_JavaUtilHashtable_init(void); FOUNDATION_EXPORT void JavaUtilHashtable_initWithJavaUtilMap_(JavaUtilHashtable *self, id<JavaUtilMap> t); FOUNDATION_EXPORT JavaUtilHashtable *new_JavaUtilHashtable_initWithJavaUtilMap_(id<JavaUtilMap> t) NS_RETURNS_RETAINED; FOUNDATION_EXPORT JavaUtilHashtable *create_JavaUtilHashtable_initWithJavaUtilMap_(id<JavaUtilMap> t); J2OBJC_TYPE_LITERAL_HEADER(JavaUtilHashtable) #endif #if !defined (JavaUtilHashtable_HashtableEntry_) && (INCLUDE_ALL_JavaUtilHashtable || defined(INCLUDE_JavaUtilHashtable_HashtableEntry)) #define JavaUtilHashtable_HashtableEntry_ #define RESTRICT_JavaUtilMap 1 #define INCLUDE_JavaUtilMap_Entry 1 #include "../../java/util/Map.h" /*! @brief Hashtable bucket collision list entry */ @interface JavaUtilHashtable_HashtableEntry : NSObject < JavaUtilMap_Entry > { @public jint hash__; id key_; id value_; JavaUtilHashtable_HashtableEntry *next_; } #pragma mark Public - (jboolean)isEqual:(id)o; - (id)getKey; - (id)getValue; - (NSUInteger)hash; - (id)setValueWithId:(id)value; - (NSString *)description; #pragma mark Protected - (instancetype __nonnull)initWithInt:(jint)hash_ withId:(id)key withId:(id)value withJavaUtilHashtable_HashtableEntry:(JavaUtilHashtable_HashtableEntry *)next; - (id)java_clone; // Disallowed inherited constructors, do not use. - (instancetype __nonnull)init NS_UNAVAILABLE; @end J2OBJC_EMPTY_STATIC_INIT(JavaUtilHashtable_HashtableEntry) J2OBJC_FIELD_SETTER(JavaUtilHashtable_HashtableEntry, key_, id) J2OBJC_FIELD_SETTER(JavaUtilHashtable_HashtableEntry, value_, id) J2OBJC_FIELD_SETTER(JavaUtilHashtable_HashtableEntry, next_, JavaUtilHashtable_HashtableEntry *) FOUNDATION_EXPORT void JavaUtilHashtable_HashtableEntry_initWithInt_withId_withId_withJavaUtilHashtable_HashtableEntry_(JavaUtilHashtable_HashtableEntry *self, jint hash_, id key, id value, JavaUtilHashtable_HashtableEntry *next); FOUNDATION_EXPORT JavaUtilHashtable_HashtableEntry *new_JavaUtilHashtable_HashtableEntry_initWithInt_withId_withId_withJavaUtilHashtable_HashtableEntry_(jint hash_, id key, id value, JavaUtilHashtable_HashtableEntry *next) NS_RETURNS_RETAINED; FOUNDATION_EXPORT JavaUtilHashtable_HashtableEntry *create_JavaUtilHashtable_HashtableEntry_initWithInt_withId_withId_withJavaUtilHashtable_HashtableEntry_(jint hash_, id key, id value, JavaUtilHashtable_HashtableEntry *next); J2OBJC_TYPE_LITERAL_HEADER(JavaUtilHashtable_HashtableEntry) #endif #if __has_feature(nullability) #pragma clang diagnostic pop #endif #pragma clang diagnostic pop #pragma pop_macro("INCLUDE_ALL_JavaUtilHashtable")
38.009191
243
0.756348
[ "object" ]
003e79767111cb0678b5771d9b392ca8f26ff295
14,627
h
C
core/include/mmcore/utility/log/Log.h
reinago/megamol
0438e26e5134a0050a00c6d8d747175a08f85fd9
[ "BSD-3-Clause" ]
null
null
null
core/include/mmcore/utility/log/Log.h
reinago/megamol
0438e26e5134a0050a00c6d8d747175a08f85fd9
[ "BSD-3-Clause" ]
null
null
null
core/include/mmcore/utility/log/Log.h
reinago/megamol
0438e26e5134a0050a00c6d8d747175a08f85fd9
[ "BSD-3-Clause" ]
null
null
null
/* * Log.h * * Copyright (C) 2006 - 2010 by Universitaet Stuttgart (VIS). * Copyright (C) 2020 by Universitaet Stuttgart (VISUS). * Alle Rechte vorbehalten. */ #pragma once #include "mmcore/api/MegaMolCore.std.h" #include <cstdio> #include <ctime> #include <string> #include <iostream> #include <thread> namespace megamol { namespace core { namespace utility { namespace log { /** * This is a utility class for managing a log file. */ class MEGAMOLCORE_API Log { public: /** Default log message pattern for spdlog */ static const char std_pattern[3]; /** type for time stamps */ using TimeStamp = time_t; /** type for the id of the source object */ using SourceID = size_t; /** unsigned int alias */ using UINT = unsigned int; /** * Set this level to log all messages. If you use this constant for * logging itself, the messages will only be logged, if LEVEL_ALL is * also set as current log level. */ static const UINT LEVEL_ALL; /** * Use this for logging errors. The value of this constant is 1, i. e. * messages with LEVEL_ERROR will always be logged, if any logging is * enabled. */ static const UINT LEVEL_ERROR; /** * Use this for informative messages. The value of this constant * is 200. */ static const UINT LEVEL_INFO; /** * Use this for disabling logging. The value is 0. It cannot be used * for logging itself, but only for the current log level. */ static const UINT LEVEL_NONE; /** * Use this for warning messages. The value of this constant * is 100. */ static const UINT LEVEL_WARN; /** The default log object. */ static Log& DefaultLog; /** * Answer the current source id * * @return A source id representing THIS */ static SourceID CurrentSourceID(void); /** * Answer the current time. * * @return A time stamp representing NOW. */ static TimeStamp CurrentTimeStamp(void); /** * Abstract base class for log targets */ class MEGAMOLCORE_API Target { public: /** Dtor */ virtual ~Target(void); /** Flushes any buffer */ virtual void Flush(void); /** * Answer the log level of this target * * @return The log level of this target */ inline UINT Level(void) const { return this->level; } /** * Writes a message to the log target * * @param level The level of the message * @param time The time stamp of the message * @param sid The object id of the source of the message * @param msg The message text itself */ virtual void Msg(UINT level, TimeStamp time, SourceID sid, const char *msg) = 0; /** * Writes a message to the log target * * @param level The level of the message * @param time The time stamp of the message * @param sid The object id of the source of the message * @param msg The message text itself */ virtual void Msg(UINT level, TimeStamp time, SourceID sid, std::string const& msg) = 0; /** * Sets the log level for this target * * @param level The new log level */ inline void SetLevel(UINT level) { this->level = level; } protected: /** * Ctor * * @param level The log level for this target */ Target(UINT level = Log::LEVEL_ERROR); private: /** The log level for this target */ UINT level; }; /** * Ctor. Constructs a new log file without a physical file. * * @param level Sets the current log level. * @param msgbufsize The number of messages that will be stored in * memory if no physical log file is available. */ Log(UINT level = LEVEL_ERROR, unsigned int msgbufsize = 10); /** * Ctor. Constructs a new log file with the specified physical file. * * @param level Sets the current log level. * @param filename The name of the physical log file. * @param addSuffix If true a automatically generated suffix is added * to the name of the physical log file, consisting of * the name of the computer name, the current date and * time. */ Log(UINT level, const char *filename, bool addSuffix); /** * Copy ctor. * * @param source The object which will be copied from. */ Log(const Log& source); /** Dtor. */ ~Log(void); /** * Access the echo log target * * @return The echo log target */ inline const std::shared_ptr<Target> AccessEchoTarget(void) const { return this->echoTarget; } /** * Access the main log target * * @return The main log target */ inline const std::shared_ptr<Target> AccessMainTarget(void) const { return this->mainTarget; } /** Disable the autoflush flag. */ inline void DisableAutoFlush(void) { this->SetAutoFlush(false); } /** * Writes all offline messages to the echo target. * * @param remove If 'true' the offline messages will be removed after * the operation returns. If 'false' the offline messages * remain in the offline buffer. */ void EchoOfflineMessages(bool remove = false); /** Enables the autoflush flag. */ inline void EnableAutoFlush(void) { this->SetAutoFlush(true); } /** Flushes the physical log file. */ void FlushLog(void); /** * Answer the current echo level. Messages above this level will be * ignored, while the other messages will be echoed to the echo output * stream. * * @return The current echo level. */ UINT GetEchoLevel(void) const; /** * Answer the current log level. Messages above this level will be * ignored. * * @return The current log level. */ UINT GetLevel(void) const; /** * Answer the file name of the log file as ANSI string. * * @return The name of the current physical log file as ANSI string. */ std::string GetLogFileNameA(void) const; /** * Answer the number of messages that will be stored in memory if no * physical log file is available. * * @return The number of messages that will be stored in memory if no * physical log file is available. */ unsigned int GetOfflineMessageBufferSize(void) const; /** * Answer the state of the autoflush flag. * * @return The state of the autoflush flag. */ inline bool IsAutoFlushEnabled(void) const { return this->autoflush; } /** * Sets or clears the autoflush flag. If the autoflush flag is set * a flush of all data to the physical log file is performed after * each message. Autoflush is enabled by default. * * @param enable New value for the autoflush flag. */ inline void SetAutoFlush(bool enable) { this->autoflush = enable; } /** * Set a new echo level. Messages above this level will be ignored, * while the other messages will be echoed to the echo output stream. * * @param level The new echo level. */ void SetEchoLevel(UINT level); /** * Sets the new echo log target * * @param The new echo log target */ void SetEchoTarget(std::shared_ptr<Target> target); /** * Set a new log level. Messages above this level will be ignored. * * @param level The new log level. */ void SetLevel(UINT level); /** * Specifies the location of the physical log file. Any physical log * file currently in use will be closed. * * @param filename The name of the physical log file. If this parameter * is NULL, the current physical log file is closed, * but no new file will be opened. * @param addSuffix If true a automatically generated suffix is added * to the name of the physical log file, consisting of * the name of the computer name, the current date and * time. * * @return true if the log file name had been successfully changes, * false otherwise. */ bool SetLogFileName(const char *filename, bool addSuffix); /** * Sets the new main log target * * @param The new main log target */ void SetMainTarget(std::shared_ptr<Target> target); /** * Sets the number of messages that will be stored in memory if no * physical log file is available. * * @param msgbufsize The number of messages that will be stored in * memory if no physical log file is available. */ void SetOfflineMessageBufferSize(unsigned int msgbufsize); /** * Connects the internal memory for log targets of this this log with * the memory of the 'master' log. Changes to the targets themself are * not thread-safe. Log messages as input to the targets may be * thead-safe depending on the employed targets. * * @param master The master log providing the memory for stroing the * log targets. */ void ShareTargetStorage(const Log& master); /** * Writes a formatted error message to the log. The level will be * 'LEVEL_ERROR'. * * @param fmt The log message */ void WriteError(const char *fmt, ...); /** * Writes a formatted error message to the log. The level will be * 'LEVEL_ERROR + lvlOff'. Not that a high level offset value might * downgrade the message to warning or even info level. * * @param fmt The log message * @param lvlOff The log level offset */ void WriteError(int lvlOff, const char *fmt, ...); /** * Writes a formatted error message to the log. The level will be * 'LEVEL_INFO'. * * @param fmt The log message */ void WriteInfo(const char *fmt, ...); /** * Writes a formatted error message to the log. The level will be * 'LEVEL_INFO + lvlOff'. * * @param fmt The log message * @param lvlOff The log level offset */ void WriteInfo(int lvlOff, const char *fmt, ...); /** * Writes a pre-formatted message with specified log level, time stamp * and source id to the log. * * @param level The level of the message * @param time The time stamp of the message * @param sid The object id of the source of the message * @param msg The message text itself */ void WriteMessage(UINT level, TimeStamp time, SourceID sid, const std::string& msg); /** * Writes a pre-formatted message with specified log level, time stamp * and source id to the log. * * @param level The level of the message * @param time The time stamp of the message * @param sid The object id of the source of the message * @param msg The message text itself */ void WriteMessageVaA(UINT level, TimeStamp time, SourceID sid, const char *fmt, va_list argptr); /** * Writes a formatted messages with the specified log level to the log * file. The format of the message is similar to the printf functions. * A new line character is automatically appended if the last * character of fmt is no new line character. * * @param level The log level of the message. * @param fmt The log message. */ void WriteMsg(UINT level, const char *fmt, ...); /** * Writes a formatted error message to the log. The level will be * 'LEVEL_WARN'. * * @param fmt The log message */ void WriteWarn(const char *fmt, ...); /** * Writes a formatted error message to the log. The level will be * 'LEVEL_WARN + lvlOff'. Not that a high level offset value might * downgrade the message to info level. * * @param fmt The log message * @param lvlOff The log level offset */ void WriteWarn(int lvlOff, const char *fmt, ...); /** * Assignment operator * * @param rhs The right hand side operand. * * @return Reference to this. */ Log& operator=(const Log& rhs); private: /** * Answer a file name suffix for log files * * @return A file name suffix for log files */ std::string getFileNameSuffix(void); /** The main log target */ std::shared_ptr<Target> mainTarget; /** The log echo target */ std::shared_ptr<Target> echoTarget; /** Flag whether or not to flush any targets after each message */ bool autoflush; }; } // namespace log } // namespace utility } // namespace core } // namespace megamol
31.055202
99
0.539345
[ "object" ]
003e80848461a401bf4605d42588af903f127883
4,667
h
C
tasks/keypoint_match/MatchFinder/src/normals.h
ethz-asl/Matterport
4338d01c81380b1ad78cca83206648c9b5233f47
[ "MIT" ]
708
2017-09-20T15:05:44.000Z
2022-03-29T15:08:01.000Z
tasks/keypoint_match/MatchFinder/src/normals.h
ethz-asl/Matterport
4338d01c81380b1ad78cca83206648c9b5233f47
[ "MIT" ]
51
2017-09-20T17:26:52.000Z
2022-03-20T13:23:11.000Z
tasks/keypoint_match/MatchFinder/src/normals.h
ethz-asl/Matterport
4338d01c81380b1ad78cca83206648c9b5233f47
[ "MIT" ]
155
2017-09-21T06:30:52.000Z
2022-03-21T19:54:59.000Z
#pragma once #include "mLibInclude.h" class NormalExtractor { public: NormalExtractor(unsigned int width, unsigned int height) { m_width = width; m_height = height; m_graphics = new D3D11GraphicsDevice(); m_graphics->initWithoutWindow(); m_cbCamera.init(*m_graphics); m_shaders.init(*m_graphics); m_shaders.registerShader("shaders/normals.hlsl", "normals"); std::vector<DXGI_FORMAT> formats = { DXGI_FORMAT::DXGI_FORMAT_R32G32B32A32_FLOAT }; m_renderTarget.init(*m_graphics, m_width, m_height, formats); } ~NormalExtractor() { SAFE_DELETE(m_graphics); } //normals from bilateral filt depth void computeDepthNormals(const SensorData* sd, float depthSigmaD, float depthSigmaR, std::vector<PointImage>& normals); void computeMeshNormals(const SensorData* sd, const TriMeshf& mesh, float zNear, float zFar, std::vector<PointImage>& normals); static void saveNormalImage(const std::string& filename, const PointImage& normal) { //convert to 3x 16bit BaseImage<vec3us> normalImage(normal.getDimensions()); for (auto& p : normal) { vec3f n = (p.value.x == -std::numeric_limits<float>::infinity()) ? vec3f(0.0f, 0.0f, 0.0f) : p.value; n = 0.5f * (n + 1) * 65535.0f; //[-1,1] -> [0,65535] normalImage(p.x, p.y) = vec3us(n); } FreeImageWrapper::saveImage(filename, normalImage); } static void loadNormalImage(const std::string& filename, PointImage& normal) { //convert to 3x 16bit BaseImage<vec3us> normalImage; FreeImageWrapper::loadImage(filename, normalImage); normal.allocate(normalImage.getWidth(), normalImage.getHeight()); for (auto& p : normal) { vec3f n = vec3f(normalImage(p.x, p.y)) * 2.0f / 65535.0f - 1.0f; if (n.length() < 0.001f) n = vec3f(-std::numeric_limits<float>::infinity()); p.value = n; } } private: static mat4f projFromVision(const mat4f& intrinsic, const mat4f& cameraToWorld, unsigned int width, unsigned int height, float zNear, float zFar); void render(const mat4f& perspective, const mat4f& worldToCam, const vec3f& eye, ColorImageR32G32B32A32& image, const SensorData* sd) { m_renderTarget.bind(); m_renderTarget.clear(ml::vec4f(0.0f, 0.0f, 0.0f, 0.0f)); ConstantBufferCamera cbCamera; cbCamera.worldViewProj = perspective * worldToCam; cbCamera.world = worldToCam; m_cbCamera.updateAndBind(cbCamera, 0); m_shaders.bindShaders("normals"); m_mesh.render(); m_renderTarget.unbind(); m_renderTarget.captureColorBuffer(image); //mat4f intrinsic = sd->m_calibrationDepth.m_intrinsic; //if (m_width != sd->m_depthWidth || m_height != sd->m_depthHeight) { // // adapt depth intrinsics // intrinsic._m00 *= (float)m_width / (float)sd->m_depthWidth; //focal length // intrinsic._m11 *= (float)m_height / (float)sd->m_depthHeight; //focal length // intrinsic._m02 *= (float)(m_width - 1) / (float)(sd->m_depthWidth - 1); //principal point // intrinsic._m12 *= (float)(m_height - 1) / (float)(sd->m_depthHeight - 1); //principal point //} //DepthImage32 depth; //m_renderTarget.captureDepthBuffer(depth); //mat4f projToCamera = perspective.getInverse(); //for (auto &p : depth) { // vec3f posWorld = vec3f(-std::numeric_limits<float>::infinity()); // if (p.value != 0.0f && p.value != 1.0f) { // vec3f posProj = vec3f(m_graphics->pixelToNDC(vec2i((int)p.x, (int)p.y), depth.getWidth(), depth.getHeight()), p.value); // vec3f posCamera = projToCamera * posProj; // if (posCamera.z >= 0.4f && posCamera.z <= 7.0f) { // p.value = posCamera.z; // posWorld = worldToCam.getInverse() * posCamera; // } // else { // p.value = -std::numeric_limits<float>::infinity(); // } // } // else { // p.value = -std::numeric_limits<float>::infinity(); // } //} //depth pixels //PointImage normal = sd->computeNormals(intrinsic.getInverse(), depth); //PointImage campos = sd->computeCameraSpacePositions(0); //campos.resize(m_width, m_height); //{ // PointCloudf pc; // for (const auto& p : campos) { // vec3f n = normal(p.x, p.y); // if (p.value.x != -std::numeric_limits<float>::infinity() && (!(n.x == 0 && n.y == 0 && n.z == 0))) { // pc.m_points.push_back(p.value); // pc.m_normals.push_back(n); // } // } // PointCloudIOf::saveToFile("test-d.ply", pc); //} //saveNormalImage("test-d.png", normal); //int a = 5; } struct ConstantBufferCamera { mat4f worldViewProj; mat4f world; //vec4f eye; }; unsigned int m_width; unsigned int m_height; D3D11GraphicsDevice* m_graphics; D3D11ShaderManager m_shaders; D3D11ConstantBuffer<ConstantBufferCamera> m_cbCamera; D3D11TriMesh m_mesh; D3D11RenderTarget m_renderTarget; };
33.099291
147
0.68138
[ "mesh", "render", "vector" ]
0040eca55c840e36fa07c4b1b2d5d793b6e43f2a
1,952
h
C
ext/phalcon/mvc/collection/behavior.zep.h
stokes-php/phalcon
b152cacdacedaa5c67798c800bb6eb99068c377b
[ "PHP-3.01", "Zend-2.0", "BSD-3-Clause" ]
3
2016-07-25T09:17:38.000Z
2020-11-24T09:52:24.000Z
ext/phalcon/mvc/collection/behavior.zep.h
stokes-php/phalcon
b152cacdacedaa5c67798c800bb6eb99068c377b
[ "PHP-3.01", "Zend-2.0", "BSD-3-Clause" ]
null
null
null
ext/phalcon/mvc/collection/behavior.zep.h
stokes-php/phalcon
b152cacdacedaa5c67798c800bb6eb99068c377b
[ "PHP-3.01", "Zend-2.0", "BSD-3-Clause" ]
1
2018-01-19T10:37:17.000Z
2018-01-19T10:37:17.000Z
extern zend_class_entry *phalcon_mvc_collection_behavior_ce; ZEPHIR_INIT_CLASS(Phalcon_Mvc_Collection_Behavior); PHP_METHOD(Phalcon_Mvc_Collection_Behavior, __construct); PHP_METHOD(Phalcon_Mvc_Collection_Behavior, mustTakeAction); PHP_METHOD(Phalcon_Mvc_Collection_Behavior, getOptions); PHP_METHOD(Phalcon_Mvc_Collection_Behavior, notify); PHP_METHOD(Phalcon_Mvc_Collection_Behavior, missingMethod); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_collection_behavior___construct, 0, 0, 0) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_collection_behavior_musttakeaction, 0, 0, 1) ZEND_ARG_INFO(0, eventName) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_collection_behavior_getoptions, 0, 0, 0) ZEND_ARG_INFO(0, eventName) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_collection_behavior_notify, 0, 0, 2) ZEND_ARG_INFO(0, type) ZEND_ARG_OBJ_INFO(0, model, Phalcon\\Mvc\\CollectionInterface, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_collection_behavior_missingmethod, 0, 0, 2) ZEND_ARG_OBJ_INFO(0, model, Phalcon\\Mvc\\CollectionInterface, 0) ZEND_ARG_INFO(0, method) ZEND_ARG_INFO(0, arguments) ZEND_END_ARG_INFO() ZEPHIR_INIT_FUNCS(phalcon_mvc_collection_behavior_method_entry) { PHP_ME(Phalcon_Mvc_Collection_Behavior, __construct, arginfo_phalcon_mvc_collection_behavior___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(Phalcon_Mvc_Collection_Behavior, mustTakeAction, arginfo_phalcon_mvc_collection_behavior_musttakeaction, ZEND_ACC_PROTECTED) PHP_ME(Phalcon_Mvc_Collection_Behavior, getOptions, arginfo_phalcon_mvc_collection_behavior_getoptions, ZEND_ACC_PROTECTED) PHP_ME(Phalcon_Mvc_Collection_Behavior, notify, arginfo_phalcon_mvc_collection_behavior_notify, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Collection_Behavior, missingMethod, arginfo_phalcon_mvc_collection_behavior_missingmethod, ZEND_ACC_PUBLIC) PHP_FE_END };
45.395349
137
0.880635
[ "model" ]
0046be6e25667b7317de0b8bdf3eadb32e219bba
2,270
h
C
include/platform/TimedExpiryBuffer.h
SonnyRajagopalan/TimerAndCallback
c36a0f7144631ea77848a0fb88857c8c15e07e29
[ "BSD-3-Clause" ]
4
2020-04-07T03:03:00.000Z
2022-02-07T03:58:21.000Z
include/platform/TimedExpiryBuffer.h
SonnyRajagopalan/TimerAndCallback
c36a0f7144631ea77848a0fb88857c8c15e07e29
[ "BSD-3-Clause" ]
null
null
null
include/platform/TimedExpiryBuffer.h
SonnyRajagopalan/TimerAndCallback
c36a0f7144631ea77848a0fb88857c8c15e07e29
[ "BSD-3-Clause" ]
5
2015-06-15T12:12:53.000Z
2022-02-06T14:32:50.000Z
#ifndef TIMED_EXPIRY_BUFFER #define TIMED_EXPIRY_BUFFER /** A timed expiry buffer is a buffer that is required to be maintained for a fixed time, after which the buffer is to be purged. There may be other constraints such as making sure that the buffer contains only unique entries. The class is not designed to be thread/process/fork safe. This is because this class is only for buffers that will maintain per-process-/fork-/thread- unique buffers. */ #include <vector> #include "platform/Timer.h" #include "platform/TEBCb.h" template <class T> class TimedExpiryBuffer { public: enum TEBType { DuplicateNotOk, DuplicatesOk }; TimedExpiryBuffer (Timer* _pTimer, TEBType _type); ~TimedExpiryBuffer (); virtual Result insertIntoBuffer (T) = 0; virtual Result insertUniqueIntoBuffer (T) = 0; virtual bool isInBuffer (T) = 0; private: /** (1) Set timer time period to be time period of buffer maintenance per requirement. (2) When the timer fires (actions in the TEBCb::triggered ()): if (type == TEBType::DuplicateNotOk) { tickTime = ! tickTime; if (tickTime) { purge the tickBuffer; } else { purge the tockBuffer; } } else { // Do nothing: buffer insertion not dependent on tick-tock } (3) For buffer insertion: if (type == TEBType::DuplicateNotOk) { if (tickTime) insertIntoTickBuffer (T); else insertIntoTockBuffer (T); } else { insertIntoTickBuffer (T); // Note: neither buffer is purged u } */ TEBType type; Timer* pTimer; // Periodic timer TEBCb* pTEBCb; bool tickTime; // If false, it is tockTime, else it is tickTime. Initialized to false. std::vector <T> tickBuffer; std::vector <UINT32> tickBufferInsertionTime; std::vector <T> tockBuffer; std::vector <UINT32> tockBufferInsertionTime; // Empty explicit copy contructor here; illegal operation TimedExpiryBuffer (const TimedExpiryBuffer& anotherTimedExpiryBuffer); // Emply explicit copy assignment operator here; illegal operation TimedExpiryBuffer& operator= (const TimedExpiryBuffer& anotherTimedExpiryBuffer); }; #endif
23.163265
90
0.672247
[ "vector" ]
0047a08d97a582c652c8e45c3d8908b5b9f7040a
5,007
c
C
tests/C-tests/diagonalize_matrix_typed.c
jeanlucf22/bml
8bb98b81f80e57d8a88eb898e1dc0f7668b332f7
[ "BSD-3-Clause", "Unlicense" ]
null
null
null
tests/C-tests/diagonalize_matrix_typed.c
jeanlucf22/bml
8bb98b81f80e57d8a88eb898e1dc0f7668b332f7
[ "BSD-3-Clause", "Unlicense" ]
null
null
null
tests/C-tests/diagonalize_matrix_typed.c
jeanlucf22/bml
8bb98b81f80e57d8a88eb898e1dc0f7668b332f7
[ "BSD-3-Clause", "Unlicense" ]
null
null
null
#include "bml.h" #include "../typed.h" #include "../C-interface/dense/bml_getters_dense.h" #include <complex.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #if defined(SINGLE_REAL) || defined(SINGLE_COMPLEX) #define REL_TOL 1.2e-5 #else #define REL_TOL 1e-11 #endif int TYPED_FUNC( test_diagonalize) ( const int N, const bml_matrix_type_t matrix_type, const bml_matrix_precision_t matrix_precision, const int M) { bml_matrix_t *A = NULL; bml_matrix_t *A_t = NULL; REAL_T *eigenvalues = NULL; bml_matrix_t *eigenvectors = NULL; bml_matrix_t *aux = NULL; bml_matrix_t *aux1 = NULL; bml_matrix_t *aux2 = NULL; bml_matrix_t *id = NULL; float fnorm; LOG_DEBUG("rel. tolerance = %e\n", REL_TOL); A = bml_random_matrix(matrix_type, matrix_precision, N, M, sequential); A_t = bml_transpose_new(A); bml_add(A, A_t, 0.5, 0.5, 0.0); LOG_INFO("A + A_t = \n"); bml_print_bml_matrix(A, 0, N, 0, N); switch (matrix_precision) { case single_real: #ifdef INTEL_OPT eigenvalues = bml_allocate_memory(N * sizeof(float)); #pragma omp parallel for simd #pragma vector aligned for (int i = 0; i < N; i++) { __assume_aligned(eigenvalues, 64); eigenvalues[i] = 0.0; } #else eigenvalues = calloc(N, sizeof(float)); #endif break; case double_real: #ifdef INTEL_OPT eigenvalues = bml_allocate_memory(N * sizeof(double)); #pragma omp parallel for simd #pragma vector aligned for (int i = 0; i < N; i++) { __assume_aligned(eigenvalues, 64); eigenvalues[i] = 0.0; } #else eigenvalues = calloc(N, sizeof(double)); #endif break; case single_complex: #ifdef INTEL_OPT eigenvalues = bml_allocate_memory(N * sizeof(float complex)); #pragma omp parallel for simd #pragma vector aligned for (int i = 0; i < N; i++) { __assume_aligned(eigenvalues, 64); eigenvalues[i] = 0.0; } #else eigenvalues = calloc(N, sizeof(float complex)); #endif break; case double_complex: #ifdef INTEL_OPT eigenvalues = bml_allocate_memory(N * sizeof(double complex)); #pragma omp parallel for simd #pragma vector aligned for (int i = 0; i < N; i++) { __assume_aligned(eigenvalues, 64); eigenvalues[i] = 0.0; } #else eigenvalues = calloc(N, sizeof(double complex)); #endif break; default: LOG_DEBUG("matrix_precision is not set"); break; } eigenvectors = bml_zero_matrix(matrix_type, matrix_precision, N, M, sequential); aux1 = bml_zero_matrix(matrix_type, matrix_precision, N, M, sequential); aux2 = bml_zero_matrix(matrix_type, matrix_precision, N, M, sequential); //bml_print_bml_matrix(eigenvectors, 0, N, 0, N); bml_diagonalize(A, eigenvalues, eigenvectors); printf("%s\n", "eigenvectors"); bml_print_bml_matrix(eigenvectors, 0, N, 0, N); printf("%s\n", "eigenvalues"); for (int i = 0; i < N; i++) printf("val = %e i%e\n", REAL_PART(eigenvalues[i]), IMAGINARY_PART(eigenvalues[i])); aux = bml_transpose_new(eigenvectors); bml_multiply(aux, eigenvectors, aux2, 1.0, 0.0, 0.0); // C^t*C printf("%s\n", "check eigenvectors norms"); for (int i = 0; i < N; i++) { REAL_T *val = bml_get_element(aux2, i, i); if (ABS(*val - (REAL_T) 1.0) > REL_TOL) { printf("i = %d, val = %e i%e\n", i, REAL_PART(*val), IMAGINARY_PART(*val)); LOG_ERROR ("Error in matrix diagonalization; eigenvector not normalized\n"); } } id = bml_identity_matrix(matrix_type, matrix_precision, N, M, sequential); bml_add(aux2, id, 1.0, -1.0, 0.0); fnorm = bml_fnorm(aux2); if (fabsf(fnorm) > N * REL_TOL) { LOG_ERROR ("Error in matrix diagonalization; fnorm(C^txC^t-Id) = %e\n", fnorm); return -1; } bml_set_diagonal(aux1, eigenvalues, 0.0); bml_multiply(aux1, aux, aux2, 1.0, 0.0, 0.0); // D*C^t bml_multiply(eigenvectors, aux2, aux, 1.0, 0.0, 0.0); // C*(D*C^t) bml_add(aux, A, 1.0, -1.0, 0.0); fnorm = bml_fnorm(aux); if (fabsf(fnorm) > N * REL_TOL) { LOG_ERROR ("Error in matrix diagonalization; fnorm(CDC^t-A) = %e\n", fnorm); return -1; } bml_deallocate(&A); bml_deallocate(&aux); bml_deallocate(&aux1); bml_deallocate(&aux2); bml_deallocate(&A_t); bml_deallocate(&eigenvectors); bml_deallocate(&id); bml_free_memory(eigenvalues); LOG_INFO("diagonalize matrix test passed\n"); return 0; }
27.662983
82
0.575594
[ "vector" ]
004aaefa49d0e6fbea8a4953f37afc006c7398be
15,748
h
C
inetsrv/iis/staxinc/fdlhash.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/staxinc/fdlhash.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/staxinc/fdlhash.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ FDLHash.h This file contains a template class for a hash table. The templates used in here build off the templates in tfdlist.h for doubly linked lists. The bucket chains implemented in this version of the hash table are doubly linked lists. The Data type must support the following : class Data { DLSIT_ENTRY m_list; KEYREF GetKey( ) ; } ; int MatchKey( KEYREF otherkey, KEYREF otherkey) ; /* NOTE : MatchKey returns non-zero on equality DWORD (* m_pfnReHash)(Data* p ) ; DWORD (* m_pfnHash)( KEYREF k ) ; --*/ #ifndef _FDLHASH_H_ #define _FDLHASH_H_ #include "tfdlist.h" class CHashStats { public : enum COUNTER { HASHITEMS = 0, // Number of items in the hash table INSERTS, // Number of times Insert has been called SPLITINSERTS, // Number of inserts until the next split ! DELETES, // Number of times Delete has been called SEARCHES, // Number of times Search has been called SEARCHHITS, // Number of times we Search and find something ! SPLITS, // Number of times we've split the table on an insert ! REALLOCS, // Number of times we've reallocated memory for a split DEEPBUCKET, // The deepest bucket we have ! AVERAGEBUCKET, // The average depth of the buckets EMPTYBUCKET, // The number of Empty buckets ! ALLOCBUCKETS, // Number of buckets we've allocated ACTIVEBUCKETS, // Number of Active buckets AVERAGESEARCH, // Average number of buckets we examine each search DEEPSEARCH, // Longest walk we do on a search SEARCHCOST, // Sum of the number of items we've visited for all search hits ! SEARCHCOSTMISS, // Sum of the number of items we've visited for search misses ! MAX_HASH_STATS // Number of statistics we report ! } ; long m_cHashCounters[MAX_HASH_STATS] ; CHashStats() { ZeroMemory( m_cHashCounters, sizeof( m_cHashCounters ) ) ; //m_cHashCounters[SMALLSEARCH] = 0x7FFF ; } static inline void IncrementStat( CHashStats* p, CHashStats::COUNTER c ) { _ASSERT( c < CHashStats::MAX_HASH_STATS ) ; if( p != 0 ) { InterlockedIncrement( &p->m_cHashCounters[c] ) ; } } static inline void AddStat( CHashStats*p, CHashStats::COUNTER c, long l ) { _ASSERT( c < CHashStats::MAX_HASH_STATS ) ; if( p != 0 ) { InterlockedExchangeAdd( &p->m_cHashCounters[c], l ) ; } } static inline void DecrementStat( CHashStats* p, CHashStats::COUNTER c ) { _ASSERT( c < CHashStats::MAX_HASH_STATS ) ; if( p != 0 ) { InterlockedDecrement( &p->m_cHashCounters[c] ) ; } } static inline void SetStat( CHashStats* p, CHashStats::COUNTER c, long l ) { _ASSERT( c < CHashStats::MAX_HASH_STATS ) ; if( p != 0 ) { p->m_cHashCounters[c] = l ; } } } ; #ifdef METER #define INCREMENTSTAT( s ) CHashStats::IncrementStat( m_pStat, CHashStats::##s ) #define DECREMENTSTAT( s ) CHashStats::DecrementStat( m_pStat, CHashStats::##s ) #define ADDSTAT( s, a ) CHashStats::AddStat( m_pStat, CHashStats::##s, a ) #define SETSTAT( s, a ) CHashStats::SetStat( m_pStat, CHashStats::##s, a ) //#if 0 #define MAXBUCKET( i ) MaxBucket( i ) #define AVERAGEBUCKET() AverageBucket() //#else //#define MAXBUCKET( i ) //#define AVERAGEBUCKET() //#endif #else // METER #define INCREMENTSTAT( s ) #define DECREMENTSTAT( s ) #define ADDSTAT( s, a ) #define SETSTAT( s, a ) #define MAXBUCKET( i ) #define AVERAGEBUCKET() #endif // METER template< class HASHTABLE > class TFDLHashIterator { private : // // The hash table that the item is in ! // HASHTABLE* m_pTable ; // // The bucket we are walking on ! // int m_iBucket ; // // Keep track of our position in a list ! // typename HASHTABLE::ITER m_Iter ; // // Move between hash table buckets as necessary ! // void PrevBucket() { _ASSERT( m_iBucket >= 0 && m_iBucket < m_pTable->m_cActiveBuckets ) ; _ASSERT( m_Iter.AtEnd() ) ; if( m_iBucket > 0 ) { do { m_Iter.ReBind( &m_pTable->m_pBucket[--m_iBucket] ) ; } while( m_Iter.AtEnd() && m_iBucket > 0 ) ; } _ASSERT( m_iBucket >= 0 && m_iBucket < m_pTable->m_cActiveBuckets ) ; } // // Move between hash table buckets as necessary ! // void NextBucket() { _ASSERT( m_iBucket >= 0 && m_iBucket < m_pTable->m_cActiveBuckets ) ; _ASSERT( m_Iter.AtEnd() ) ; if( m_iBucket < m_pTable->m_cActiveBuckets-1 ) { do { m_Iter.ReBind( &m_pTable->m_pBucket[++m_iBucket] ) ; } while( m_Iter.AtEnd() && m_iBucket < m_pTable->m_cActiveBuckets-1 ) ; } _ASSERT( m_iBucket >= 0 && m_iBucket < m_pTable->m_cActiveBuckets ) ; } public : typedef typename HASHTABLE::DATA DATA ; TFDLHashIterator( HASHTABLE& ref, BOOL fForward = TRUE ) : m_pTable( &ref ), m_iBucket( fForward ? 0 : ref.m_cActiveBuckets-1 ), m_Iter( ref.m_pBucket[m_iBucket] ) { if( m_Iter.AtEnd() ) { if( fForward ) { NextBucket() ; } else { PrevBucket() ; } } } void Prev() { /*++ Routine Description : This function moves the iterator back one slot. Arguments : None. Return Value : None. --*/ m_Iter.Prev() ; if( m_Iter.AtEnd() ) { PrevBucket() ; } } void Next() { /*++ Routine Description : This function moves the iterator forward one slot. Arguments : None. Return Value : None. --*/ m_Iter.Next() ; if( m_Iter.AtEnd() ) { NextBucket() ; } } void Front() { /*++ Routine Description : Reset the iterator to reference the first item of the list ! Arguments : None. Return Value : None. --*/ m_Iter.ReBind( &m_pTable->m_pBucket[0], TRUE ) ; m_iBucket = 0 ; if( m_Iter.AtEnd() ) { NextBucket() ; } } void Back() { /*++ Routine Description : Reset the iterator to reference the last item of the list ! Arguments : None. Return Value : None. --*/ m_Iter.ReBind( &m_pTable->m_pBucket[m_pTable->m_cActiveBuckets-1], FALSE ) ; m_iBucket = m_pTable->m_cActiveBuckets-1 ; if( m_Iter.AtEnd() ) { PrevBucket() ; } } BOOL AtEnd() { /*++ Routine Description : Return TRUE if we are at the end of the list ! This is a little more complicated to compute - depends on which way we are going ! Arguments : None. Return Value : None. --*/ return m_Iter.AtEnd() ; } DATA* CurrentEntry() { return m_Iter.Current() ; } DATA* RemoveItem() { /*++ Routine Description : Remove the item that the iterator currently references from the list. If we are going forward then the iterator will be setting on the previous element, otherwise the iterator is left on the next element. We have to take care that we don't leave the iterator sitting on an invalid element. Arguments : None. Return Value : Pointer to the removed item. --*/ DATA* pData = m_Iter.RemoveItem() ; if( pData ) { m_pTable->NotifyOfRemoval() ; } if( m_Iter.AtEnd() ) { if( m_Iter.m_fForward ) { NextBucket() ; } else { PrevBucket() ; } } return pData ; } inline DATA* Current( ) { return m_Iter.Current() ; } inline void InsertBefore( DATA* p ) { m_Iter.InsertBefore( p ) ; } inline void InsertAfter( DATA* p ) { m_Iter.InsertAfter( p ) ; } } ; //------------------------------------------------------------ template< class Data, /* This is the item that resides in the hashtable */ class KEYREF, /* This is the type used to point or reference items in the cache*/ typename Data::PFNDLIST pfnDlist, BOOL fOrdered = TRUE > class TFDLHash { // // This class defines a Hash table which can grow dynamically to // accomodate insertions into the table. The table only grows, and // does not shrink. // public : // // This is the iterator object that can walk the hash table ! // friend class TFDLHashIterator< TFDLHash< Data, KEYREF, pfnDlist > > ; // // This is the type of the Data item ! // //typedef DATAHELPER Data ; typedef KEYREF (Data::*GETKEY)() ; // // This is the type that we use to maintain doubly linked lists of // hash table items ! // typedef TDListHead< Data, pfnDlist > DLIST ; // // This is the type we use to make iterators over the bucket chains ! // typedef TDListIterator< DLIST > ITER ; // // Define this type for our iterators ! // typedef Data DATA ; // // This is a member function pointer to a function which // will retrieve the key we are to use ! // //typedef KEYREF (Data::*GETKEY)( ) ; //typedef Data::GETKEY GETKEY ; // // This is the type of function that computes the hash value ! // typedef DWORD (*PFNHASH)( KEYREF ) ; // // This is the type of function that can recompute the hash value when // we are splitting up the hash table ! // typedef DWORD (*PFNREHASH)( Data* ) ; // // This is a member function pointer of the type that will // compare keys for us ! // typedef int (*MATCHKEY)( KEYREF key1, KEYREF key2 ) ; private : // // An array of buckets ! // DLIST* m_pBucket ; // // Member Pointer - will get the key out of the object for us ! // GETKEY m_pGetKey ; // // Member Pointer - will compare the key in the item for us ! // MATCHKEY m_pMatchKey ; // // A counter that we use to determine when to grow the // hash table. Each time we grow the table we set this // to a large positive value, and decrement as we insert // elements. When this hits 0 its time to grow the table ! // long m_cInserts ; // // The function we use to compute hash values. // (Provided by the Caller of Init()) // PFNHASH m_pfnHash ; // // The function we call when we are growing the hash table // and splitting bucket chains and we need to rehash an element ! // PFNREHASH m_pfnReHash ; // // Number of Buckets used in index computation // int m_cBuckets ; // // Number of Buckets we are actually using // Assert( m_cBuckets >= m_cActiveBuckets ) always true. // int m_cActiveBuckets ; // // Number of Buckets we have allocated // Assert( m_cNumAlloced >= m_cActiveBuckets ) must // always be true. // int m_cNumAlloced ; // // The amount we should grow the hash table when we // decide to grow it. // int m_cIncrement ; // // The number of CBuckets we should allow in each // collision chain (on average). // int m_load ; #ifdef METER // // The structure for collecting our performance data ! // CHashStats* m_pStat ; // // Compute the depth of a bucket ! // long BucketDepth( DWORD index ) ; // // set the statistics for the deepest bucket ! // void MaxBucket( DWORD index ) ; // // Compute the average Search depth ! // void AverageSearch( BOOL fHit, long lDepth ) ; // // Compute the average Bucket depth ! // void AverageBucket( ) ; #endif // // The function we use to compute the // position of an element in the hash table given its // Hash Value. // DWORD ComputeIndex( DWORD dw ) ; DWORD ReHash( Data* p ) { if( m_pfnReHash ) return m_pfnReHash( p ) ; return m_pfnHash( (p->*m_pGetKey)() ) ; } public : TFDLHash( ) ; ~TFDLHash( ) ; BOOL Init( int cInitial, int cIncrement, int load, PFNHASH pfnHash, GETKEY pGetKey, MATCHKEY pMatchKey, PFNREHASH pfnReHash = 0, CHashStats* pStats = 0 ) ; // // Check that the hash table is in a valid state // if fCheckHash == TRUE we will walk all the buckets and check that // the data hashes to the correct value ! // BOOL IsValid( BOOL fCheckHash = FALSE ) ; // // Check that the Bucket is valid - everything contains // proper hash value and is in order ! // BOOL IsValidBucket( int i ) ; // // This function grows the number of hash buckets as the // total number of items in the table grows ! // BOOL Split() ; // // Insert a piece of Data into the Hash Table // We take a pointer to the Data object. // BOOL InsertDataHash( DWORD dw, KEYREF k, Data* pd ) ; // // Insert a piece of Data into the Hash Table // // We take an iterator that is already position in the // correct location for inserting the item ! // BOOL InsertDataHashIter( ITER& iter, DWORD dw, KEYREF k, Data* pd ) ; // // Insert a piece of Data into the Hash Table // BOOL InsertData( Data* pd ) { KEYREF keyref = (pd->*m_pGetKey)() ; return InsertDataHash( m_pfnHash(keyref), keyref, pd ) ; } // // Insert a piece of Data into the Hash table // given an iterator that should be at the right location ! // BOOL InsertDataIter( ITER& iter, Data* pd ) { KEYREF keyref = (pd->*m_pGetKey)() ; return InsertDataHashIter( iter, m_pfnHash(keyref), keyref, pd ) ; } // // Search for an item in the cache - if we don't find // it we return an ITERATOR that the user can use to insert // the item by calling ITER.InsertBefore() ; // // If the item is found, we'll return the item, as well // as returning an iterator who's current element // points at the data item ! // ITER SearchKeyHashIter( DWORD dw, KEYREF k, Data* &pd ) ; // // Search for a given Key in the Hash Table - return a pointer // to the Data within our Bucket object // void SearchKeyHash( DWORD dw, KEYREF k, Data* &pd ) ; // // Search for a given Key in the Hash Table - return a pointer // to the Data within our Bucket object // Data* SearchKey( KEYREF k ) { Data* p ; SearchKeyHash( m_pfnHash( k ), k, p ) ; return p ; } // // Search for the given item and return a good iterator ! // ITER SearchKeyIter( KEYREF k, Data* &pd ) { pd = 0 ; return SearchKeyHashIter( m_pfnHash( k ), k, pd ) ; } Data* SearchKey( DWORD dw, KEYREF k ) { Data* p = 0 ; _ASSERT( dw == m_pfnHash( k ) ) ; SearchKeyHash( dw, k, p ) ; return p ; } // // Given an item in the hash table - remove it ! // void Delete( Data* pd ) ; // // Find an element in the hash table - and remove it ! // (Confirm that the found item matches the Key!) // void DeleteData( KEYREF k, Data* pd ) ; // // Remove an item from the hash table - and return it ! // Data* DeleteData( KEYREF k ) { Data* p ; // // Find the item // SearchKeyHash( m_pfnHash( k ), k, p ) ; // // Remove from Hash Table // if( p ) Delete( p ) ; return p ; } // // Delete the key and associated data from the table. // BOOL Destroy( KEYREF k ) { Data* p = DeleteData( k ) ; if( p ) { delete p ; return TRUE ; } return FALSE ; } // // Discards any memory we have allocated - after this, you must // call Init() again! // void Clear( ) ; // // Removes all of the items in the hash table. Does not call "delete" // on them. // void Empty( ) ; // // Called by Iterators that want to let us know that items have been // removed from the cache so we can do our splits correctly etc... ! // void NotifyOfRemoval() ; // // Function to compute hash value of a key for callers // who don't keep track of the hash function // DWORD ComputeHash( KEYREF k ) ; } ; #include "fdlhash.inl" #endif // _FDLHASH_H_
20.748353
100
0.611189
[ "object" ]
0053ffa6e2d24cca7217a3d02779f1aaf7998810
44,772
h
C
public/sdk/inc/encdec.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
public/sdk/inc/encdec.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
public/sdk/inc/encdec.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 6.00.0361 */ /* Compiler settings for encdec.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 475 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif // __RPCNDR_H_VERSION__ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __encdec_h__ #define __encdec_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IETFilterConfig_FWD_DEFINED__ #define __IETFilterConfig_FWD_DEFINED__ typedef interface IETFilterConfig IETFilterConfig; #endif /* __IETFilterConfig_FWD_DEFINED__ */ #ifndef __IDTFilterConfig_FWD_DEFINED__ #define __IDTFilterConfig_FWD_DEFINED__ typedef interface IDTFilterConfig IDTFilterConfig; #endif /* __IDTFilterConfig_FWD_DEFINED__ */ #ifndef __IXDSCodecConfig_FWD_DEFINED__ #define __IXDSCodecConfig_FWD_DEFINED__ typedef interface IXDSCodecConfig IXDSCodecConfig; #endif /* __IXDSCodecConfig_FWD_DEFINED__ */ #ifndef __IETFilter_FWD_DEFINED__ #define __IETFilter_FWD_DEFINED__ typedef interface IETFilter IETFilter; #endif /* __IETFilter_FWD_DEFINED__ */ #ifndef __IETFilterEvents_FWD_DEFINED__ #define __IETFilterEvents_FWD_DEFINED__ typedef interface IETFilterEvents IETFilterEvents; #endif /* __IETFilterEvents_FWD_DEFINED__ */ #ifndef __ETFilter_FWD_DEFINED__ #define __ETFilter_FWD_DEFINED__ #ifdef __cplusplus typedef class ETFilter ETFilter; #else typedef struct ETFilter ETFilter; #endif /* __cplusplus */ #endif /* __ETFilter_FWD_DEFINED__ */ #ifndef __IDTFilter_FWD_DEFINED__ #define __IDTFilter_FWD_DEFINED__ typedef interface IDTFilter IDTFilter; #endif /* __IDTFilter_FWD_DEFINED__ */ #ifndef __IDTFilterEvents_FWD_DEFINED__ #define __IDTFilterEvents_FWD_DEFINED__ typedef interface IDTFilterEvents IDTFilterEvents; #endif /* __IDTFilterEvents_FWD_DEFINED__ */ #ifndef __DTFilter_FWD_DEFINED__ #define __DTFilter_FWD_DEFINED__ #ifdef __cplusplus typedef class DTFilter DTFilter; #else typedef struct DTFilter DTFilter; #endif /* __cplusplus */ #endif /* __DTFilter_FWD_DEFINED__ */ #ifndef __IXDSCodec_FWD_DEFINED__ #define __IXDSCodec_FWD_DEFINED__ typedef interface IXDSCodec IXDSCodec; #endif /* __IXDSCodec_FWD_DEFINED__ */ #ifndef __IXDSCodecEvents_FWD_DEFINED__ #define __IXDSCodecEvents_FWD_DEFINED__ typedef interface IXDSCodecEvents IXDSCodecEvents; #endif /* __IXDSCodecEvents_FWD_DEFINED__ */ #ifndef __XDSCodec_FWD_DEFINED__ #define __XDSCodec_FWD_DEFINED__ #ifdef __cplusplus typedef class XDSCodec XDSCodec; #else typedef struct XDSCodec XDSCodec; #endif /* __cplusplus */ #endif /* __XDSCodec_FWD_DEFINED__ */ /* header files for imported files */ #include "oaidl.h" #include "ocidl.h" #include "TvRatings.h" #ifdef __cplusplus extern "C"{ #endif void * __RPC_USER MIDL_user_allocate(size_t); void __RPC_USER MIDL_user_free( void * ); /* interface __MIDL_itf_encdec_0000 */ /* [local] */ //+------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 2002. // //-------------------------------------------------------------------------- #pragma once // {C4C4C481-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_ETFilterEncProperties, 0xC4C4C481, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C491-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_ETFilterTagProperties, 0xC4C4C491, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C482-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_DTFilterEncProperties, 0xC4C4C482, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C492-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_DTFilterTagProperties, 0xC4C4C492, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C482-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_XDSCodecProperties, 0xC4C4C483, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C492-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_XDSCodecTagProperties, 0xC4C4C493, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4FC-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_CPCAFiltersCategory, 0xC4C4C4FC, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E0-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_XDSCodecNewXDSRating, 0xC4C4C4E0, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4DF-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_XDSCodecDuplicateXDSRating, 0xC4C4C4DF, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E1-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_XDSCodecNewXDSPacket, 0xC4C4C4E1, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E2-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterRatingChange, 0xC4C4C4E2, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E3-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterRatingsBlock, 0xC4C4C4E3, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E4-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterRatingsUnblock, 0xC4C4C4E4, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E5-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterXDSPacket, 0xC4C4C4E5, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4EC-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterDataFormatOK, 0xC4C4C4ED, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4ED-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterDataFormatFailure, 0xC4C4C4EF, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4EE-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_ETDTFilterLicenseOK, 0xC4C4C4EE, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4EF-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_ETDTFilterLicenseFailure, 0xC4C4C4EF, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4D0-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(MEDIASUBTYPE_ETDTFilter_Tagged, 0xC4C4C4D0, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4D1-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(FORMATTYPE_ETDTFilter_Tagged, 0xC4C4C4D1, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); typedef LONGLONG REFERENCE_TIME; typedef LONG PackedTvRating; typedef enum EnTag_Mode { EnTag_Remove = 0, EnTag_Once = 0x1, EnTag_Repeat = 0x2 } EnTag_Mode; extern RPC_IF_HANDLE __MIDL_itf_encdec_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_encdec_0000_v0_0_s_ifspec; #ifndef __IETFilterConfig_INTERFACE_DEFINED__ #define __IETFilterConfig_INTERFACE_DEFINED__ /* interface IETFilterConfig */ /* [unique][helpstring][uuid][object][restricted] */ EXTERN_C const IID IID_IETFilterConfig; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4D1-0049-4E2B-98FB-9537F6CE516D") IETFilterConfig : public IUnknown { public: virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE InitLicense( /* [in] */ int LicenseId) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetSecureChannelObject( /* [out] */ IUnknown **ppUnkDRMSecureChannel) = 0; }; #else /* C style interface */ typedef struct IETFilterConfigVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IETFilterConfig * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IETFilterConfig * This); ULONG ( STDMETHODCALLTYPE *Release )( IETFilterConfig * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *InitLicense )( IETFilterConfig * This, /* [in] */ int LicenseId); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetSecureChannelObject )( IETFilterConfig * This, /* [out] */ IUnknown **ppUnkDRMSecureChannel); END_INTERFACE } IETFilterConfigVtbl; interface IETFilterConfig { CONST_VTBL struct IETFilterConfigVtbl *lpVtbl; }; #ifdef COBJMACROS #define IETFilterConfig_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IETFilterConfig_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IETFilterConfig_Release(This) \ (This)->lpVtbl -> Release(This) #define IETFilterConfig_InitLicense(This,LicenseId) \ (This)->lpVtbl -> InitLicense(This,LicenseId) #define IETFilterConfig_GetSecureChannelObject(This,ppUnkDRMSecureChannel) \ (This)->lpVtbl -> GetSecureChannelObject(This,ppUnkDRMSecureChannel) #endif /* COBJMACROS */ #endif /* C style interface */ /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IETFilterConfig_InitLicense_Proxy( IETFilterConfig * This, /* [in] */ int LicenseId); void __RPC_STUB IETFilterConfig_InitLicense_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IETFilterConfig_GetSecureChannelObject_Proxy( IETFilterConfig * This, /* [out] */ IUnknown **ppUnkDRMSecureChannel); void __RPC_STUB IETFilterConfig_GetSecureChannelObject_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IETFilterConfig_INTERFACE_DEFINED__ */ #ifndef __IDTFilterConfig_INTERFACE_DEFINED__ #define __IDTFilterConfig_INTERFACE_DEFINED__ /* interface IDTFilterConfig */ /* [unique][helpstring][uuid][object][restricted] */ EXTERN_C const IID IID_IDTFilterConfig; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4D2-0049-4E2B-98FB-9537F6CE516D") IDTFilterConfig : public IUnknown { public: virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetSecureChannelObject( /* [out] */ IUnknown **ppUnkDRMSecureChannel) = 0; }; #else /* C style interface */ typedef struct IDTFilterConfigVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IDTFilterConfig * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IDTFilterConfig * This); ULONG ( STDMETHODCALLTYPE *Release )( IDTFilterConfig * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetSecureChannelObject )( IDTFilterConfig * This, /* [out] */ IUnknown **ppUnkDRMSecureChannel); END_INTERFACE } IDTFilterConfigVtbl; interface IDTFilterConfig { CONST_VTBL struct IDTFilterConfigVtbl *lpVtbl; }; #ifdef COBJMACROS #define IDTFilterConfig_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IDTFilterConfig_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IDTFilterConfig_Release(This) \ (This)->lpVtbl -> Release(This) #define IDTFilterConfig_GetSecureChannelObject(This,ppUnkDRMSecureChannel) \ (This)->lpVtbl -> GetSecureChannelObject(This,ppUnkDRMSecureChannel) #endif /* COBJMACROS */ #endif /* C style interface */ /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IDTFilterConfig_GetSecureChannelObject_Proxy( IDTFilterConfig * This, /* [out] */ IUnknown **ppUnkDRMSecureChannel); void __RPC_STUB IDTFilterConfig_GetSecureChannelObject_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IDTFilterConfig_INTERFACE_DEFINED__ */ #ifndef __IXDSCodecConfig_INTERFACE_DEFINED__ #define __IXDSCodecConfig_INTERFACE_DEFINED__ /* interface IXDSCodecConfig */ /* [unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IXDSCodecConfig; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4D3-0049-4E2B-98FB-9537F6CE516D") IXDSCodecConfig : public IUnknown { public: }; #else /* C style interface */ typedef struct IXDSCodecConfigVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IXDSCodecConfig * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IXDSCodecConfig * This); ULONG ( STDMETHODCALLTYPE *Release )( IXDSCodecConfig * This); END_INTERFACE } IXDSCodecConfigVtbl; interface IXDSCodecConfig { CONST_VTBL struct IXDSCodecConfigVtbl *lpVtbl; }; #ifdef COBJMACROS #define IXDSCodecConfig_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IXDSCodecConfig_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IXDSCodecConfig_Release(This) \ (This)->lpVtbl -> Release(This) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IXDSCodecConfig_INTERFACE_DEFINED__ */ #ifndef __EncDec_LIBRARY_DEFINED__ #define __EncDec_LIBRARY_DEFINED__ /* library EncDec */ /* [helpstring][version][uuid] */ EXTERN_C const IID LIBID_EncDec; #ifndef __IETFilter_INTERFACE_DEFINED__ #define __IETFilter_INTERFACE_DEFINED__ /* interface IETFilter */ /* [unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IETFilter; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4B1-0049-4E2B-98FB-9537F6CE516D") IETFilter : public IUnknown { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_EvalRatObjOK( /* [retval][out] */ HRESULT *pHrCoCreateRetVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetCurrRating( /* [out] */ EnTvRat_System *pEnSystem, /* [out] */ EnTvRat_GenericLevel *pEnRating, /* [out] */ LONG *plbfEnAttr) = 0; }; #else /* C style interface */ typedef struct IETFilterVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IETFilter * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IETFilter * This); ULONG ( STDMETHODCALLTYPE *Release )( IETFilter * This); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EvalRatObjOK )( IETFilter * This, /* [retval][out] */ HRESULT *pHrCoCreateRetVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetCurrRating )( IETFilter * This, /* [out] */ EnTvRat_System *pEnSystem, /* [out] */ EnTvRat_GenericLevel *pEnRating, /* [out] */ LONG *plbfEnAttr); END_INTERFACE } IETFilterVtbl; interface IETFilter { CONST_VTBL struct IETFilterVtbl *lpVtbl; }; #ifdef COBJMACROS #define IETFilter_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IETFilter_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IETFilter_Release(This) \ (This)->lpVtbl -> Release(This) #define IETFilter_get_EvalRatObjOK(This,pHrCoCreateRetVal) \ (This)->lpVtbl -> get_EvalRatObjOK(This,pHrCoCreateRetVal) #define IETFilter_GetCurrRating(This,pEnSystem,pEnRating,plbfEnAttr) \ (This)->lpVtbl -> GetCurrRating(This,pEnSystem,pEnRating,plbfEnAttr) #endif /* COBJMACROS */ #endif /* C style interface */ /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IETFilter_get_EvalRatObjOK_Proxy( IETFilter * This, /* [retval][out] */ HRESULT *pHrCoCreateRetVal); void __RPC_STUB IETFilter_get_EvalRatObjOK_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IETFilter_GetCurrRating_Proxy( IETFilter * This, /* [out] */ EnTvRat_System *pEnSystem, /* [out] */ EnTvRat_GenericLevel *pEnRating, /* [out] */ LONG *plbfEnAttr); void __RPC_STUB IETFilter_GetCurrRating_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IETFilter_INTERFACE_DEFINED__ */ #ifndef __IETFilterEvents_DISPINTERFACE_DEFINED__ #define __IETFilterEvents_DISPINTERFACE_DEFINED__ /* dispinterface IETFilterEvents */ /* [helpstring][uuid] */ EXTERN_C const IID DIID_IETFilterEvents; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4C1-0049-4E2B-98FB-9537F6CE516D") IETFilterEvents : public IDispatch { }; #else /* C style interface */ typedef struct IETFilterEventsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IETFilterEvents * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IETFilterEvents * This); ULONG ( STDMETHODCALLTYPE *Release )( IETFilterEvents * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( IETFilterEvents * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( IETFilterEvents * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( IETFilterEvents * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( IETFilterEvents * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr); END_INTERFACE } IETFilterEventsVtbl; interface IETFilterEvents { CONST_VTBL struct IETFilterEventsVtbl *lpVtbl; }; #ifdef COBJMACROS #define IETFilterEvents_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IETFilterEvents_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IETFilterEvents_Release(This) \ (This)->lpVtbl -> Release(This) #define IETFilterEvents_GetTypeInfoCount(This,pctinfo) \ (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) #define IETFilterEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define IETFilterEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define IETFilterEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IETFilterEvents_DISPINTERFACE_DEFINED__ */ EXTERN_C const CLSID CLSID_ETFilter; #ifdef __cplusplus class DECLSPEC_UUID("C4C4C4F1-0049-4E2B-98FB-9537F6CE516D") ETFilter; #endif #ifndef __IDTFilter_INTERFACE_DEFINED__ #define __IDTFilter_INTERFACE_DEFINED__ /* interface IDTFilter */ /* [unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IDTFilter; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4B2-0049-4E2B-98FB-9537F6CE516D") IDTFilter : public IUnknown { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_EvalRatObjOK( /* [retval][out] */ HRESULT *pHrCoCreateRetVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetCurrRating( /* [out] */ EnTvRat_System *pEnSystem, /* [out] */ EnTvRat_GenericLevel *pEnRating, /* [out] */ LONG *plbfEnAttr) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_BlockedRatingAttributes( /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [retval][out] */ LONG *plbfEnAttr) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_BlockedRatingAttributes( /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [in] */ LONG lbfAttrs) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_BlockUnRated( /* [retval][out] */ BOOL *pfBlockUnRatedShows) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_BlockUnRated( /* [in] */ BOOL fBlockUnRatedShows) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_BlockUnRatedDelay( /* [retval][out] */ LONG *pmsecsDelayBeforeBlock) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_BlockUnRatedDelay( /* [in] */ LONG msecsDelayBeforeBlock) = 0; }; #else /* C style interface */ typedef struct IDTFilterVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IDTFilter * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IDTFilter * This); ULONG ( STDMETHODCALLTYPE *Release )( IDTFilter * This); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EvalRatObjOK )( IDTFilter * This, /* [retval][out] */ HRESULT *pHrCoCreateRetVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetCurrRating )( IDTFilter * This, /* [out] */ EnTvRat_System *pEnSystem, /* [out] */ EnTvRat_GenericLevel *pEnRating, /* [out] */ LONG *plbfEnAttr); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockedRatingAttributes )( IDTFilter * This, /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [retval][out] */ LONG *plbfEnAttr); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BlockedRatingAttributes )( IDTFilter * This, /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [in] */ LONG lbfAttrs); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockUnRated )( IDTFilter * This, /* [retval][out] */ BOOL *pfBlockUnRatedShows); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BlockUnRated )( IDTFilter * This, /* [in] */ BOOL fBlockUnRatedShows); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockUnRatedDelay )( IDTFilter * This, /* [retval][out] */ LONG *pmsecsDelayBeforeBlock); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BlockUnRatedDelay )( IDTFilter * This, /* [in] */ LONG msecsDelayBeforeBlock); END_INTERFACE } IDTFilterVtbl; interface IDTFilter { CONST_VTBL struct IDTFilterVtbl *lpVtbl; }; #ifdef COBJMACROS #define IDTFilter_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IDTFilter_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IDTFilter_Release(This) \ (This)->lpVtbl -> Release(This) #define IDTFilter_get_EvalRatObjOK(This,pHrCoCreateRetVal) \ (This)->lpVtbl -> get_EvalRatObjOK(This,pHrCoCreateRetVal) #define IDTFilter_GetCurrRating(This,pEnSystem,pEnRating,plbfEnAttr) \ (This)->lpVtbl -> GetCurrRating(This,pEnSystem,pEnRating,plbfEnAttr) #define IDTFilter_get_BlockedRatingAttributes(This,enSystem,enLevel,plbfEnAttr) \ (This)->lpVtbl -> get_BlockedRatingAttributes(This,enSystem,enLevel,plbfEnAttr) #define IDTFilter_put_BlockedRatingAttributes(This,enSystem,enLevel,lbfAttrs) \ (This)->lpVtbl -> put_BlockedRatingAttributes(This,enSystem,enLevel,lbfAttrs) #define IDTFilter_get_BlockUnRated(This,pfBlockUnRatedShows) \ (This)->lpVtbl -> get_BlockUnRated(This,pfBlockUnRatedShows) #define IDTFilter_put_BlockUnRated(This,fBlockUnRatedShows) \ (This)->lpVtbl -> put_BlockUnRated(This,fBlockUnRatedShows) #define IDTFilter_get_BlockUnRatedDelay(This,pmsecsDelayBeforeBlock) \ (This)->lpVtbl -> get_BlockUnRatedDelay(This,pmsecsDelayBeforeBlock) #define IDTFilter_put_BlockUnRatedDelay(This,msecsDelayBeforeBlock) \ (This)->lpVtbl -> put_BlockUnRatedDelay(This,msecsDelayBeforeBlock) #endif /* COBJMACROS */ #endif /* C style interface */ /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IDTFilter_get_EvalRatObjOK_Proxy( IDTFilter * This, /* [retval][out] */ HRESULT *pHrCoCreateRetVal); void __RPC_STUB IDTFilter_get_EvalRatObjOK_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IDTFilter_GetCurrRating_Proxy( IDTFilter * This, /* [out] */ EnTvRat_System *pEnSystem, /* [out] */ EnTvRat_GenericLevel *pEnRating, /* [out] */ LONG *plbfEnAttr); void __RPC_STUB IDTFilter_GetCurrRating_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IDTFilter_get_BlockedRatingAttributes_Proxy( IDTFilter * This, /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [retval][out] */ LONG *plbfEnAttr); void __RPC_STUB IDTFilter_get_BlockedRatingAttributes_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE IDTFilter_put_BlockedRatingAttributes_Proxy( IDTFilter * This, /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [in] */ LONG lbfAttrs); void __RPC_STUB IDTFilter_put_BlockedRatingAttributes_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IDTFilter_get_BlockUnRated_Proxy( IDTFilter * This, /* [retval][out] */ BOOL *pfBlockUnRatedShows); void __RPC_STUB IDTFilter_get_BlockUnRated_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE IDTFilter_put_BlockUnRated_Proxy( IDTFilter * This, /* [in] */ BOOL fBlockUnRatedShows); void __RPC_STUB IDTFilter_put_BlockUnRated_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IDTFilter_get_BlockUnRatedDelay_Proxy( IDTFilter * This, /* [retval][out] */ LONG *pmsecsDelayBeforeBlock); void __RPC_STUB IDTFilter_get_BlockUnRatedDelay_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE IDTFilter_put_BlockUnRatedDelay_Proxy( IDTFilter * This, /* [in] */ LONG msecsDelayBeforeBlock); void __RPC_STUB IDTFilter_put_BlockUnRatedDelay_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IDTFilter_INTERFACE_DEFINED__ */ #ifndef __IDTFilterEvents_DISPINTERFACE_DEFINED__ #define __IDTFilterEvents_DISPINTERFACE_DEFINED__ /* dispinterface IDTFilterEvents */ /* [helpstring][uuid] */ EXTERN_C const IID DIID_IDTFilterEvents; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4C2-0049-4E2B-98FB-9537F6CE516D") IDTFilterEvents : public IDispatch { }; #else /* C style interface */ typedef struct IDTFilterEventsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IDTFilterEvents * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IDTFilterEvents * This); ULONG ( STDMETHODCALLTYPE *Release )( IDTFilterEvents * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( IDTFilterEvents * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( IDTFilterEvents * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( IDTFilterEvents * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( IDTFilterEvents * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr); END_INTERFACE } IDTFilterEventsVtbl; interface IDTFilterEvents { CONST_VTBL struct IDTFilterEventsVtbl *lpVtbl; }; #ifdef COBJMACROS #define IDTFilterEvents_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IDTFilterEvents_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IDTFilterEvents_Release(This) \ (This)->lpVtbl -> Release(This) #define IDTFilterEvents_GetTypeInfoCount(This,pctinfo) \ (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) #define IDTFilterEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define IDTFilterEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define IDTFilterEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDTFilterEvents_DISPINTERFACE_DEFINED__ */ EXTERN_C const CLSID CLSID_DTFilter; #ifdef __cplusplus class DECLSPEC_UUID("C4C4C4F2-0049-4E2B-98FB-9537F6CE516D") DTFilter; #endif #ifndef __IXDSCodec_INTERFACE_DEFINED__ #define __IXDSCodec_INTERFACE_DEFINED__ /* interface IXDSCodec */ /* [unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IXDSCodec; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4B3-0049-4E2B-98FB-9537F6CE516D") IXDSCodec : public IUnknown { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_XDSToRatObjOK( /* [retval][out] */ HRESULT *pHrCoCreateRetVal) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_CCSubstreamService( /* [in] */ long SubstreamMask) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_CCSubstreamService( /* [retval][out] */ long *pSubstreamMask) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetContentAdvisoryRating( /* [out] */ PackedTvRating *pRat, /* [out] */ long *pPktSeqID, /* [out] */ long *pCallSeqID, /* [out] */ REFERENCE_TIME *pTimeStart, /* [out] */ REFERENCE_TIME *pTimeEnd) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetXDSPacket( /* [out] */ long *pXDSClassPkt, /* [out] */ long *pXDSTypePkt, /* [out] */ BSTR *pBstrXDSPkt, /* [out] */ long *pPktSeqID, /* [out] */ long *pCallSeqID, /* [out] */ REFERENCE_TIME *pTimeStart, /* [out] */ REFERENCE_TIME *pTimeEnd) = 0; }; #else /* C style interface */ typedef struct IXDSCodecVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IXDSCodec * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IXDSCodec * This); ULONG ( STDMETHODCALLTYPE *Release )( IXDSCodec * This); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_XDSToRatObjOK )( IXDSCodec * This, /* [retval][out] */ HRESULT *pHrCoCreateRetVal); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_CCSubstreamService )( IXDSCodec * This, /* [in] */ long SubstreamMask); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CCSubstreamService )( IXDSCodec * This, /* [retval][out] */ long *pSubstreamMask); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetContentAdvisoryRating )( IXDSCodec * This, /* [out] */ PackedTvRating *pRat, /* [out] */ long *pPktSeqID, /* [out] */ long *pCallSeqID, /* [out] */ REFERENCE_TIME *pTimeStart, /* [out] */ REFERENCE_TIME *pTimeEnd); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetXDSPacket )( IXDSCodec * This, /* [out] */ long *pXDSClassPkt, /* [out] */ long *pXDSTypePkt, /* [out] */ BSTR *pBstrXDSPkt, /* [out] */ long *pPktSeqID, /* [out] */ long *pCallSeqID, /* [out] */ REFERENCE_TIME *pTimeStart, /* [out] */ REFERENCE_TIME *pTimeEnd); END_INTERFACE } IXDSCodecVtbl; interface IXDSCodec { CONST_VTBL struct IXDSCodecVtbl *lpVtbl; }; #ifdef COBJMACROS #define IXDSCodec_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IXDSCodec_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IXDSCodec_Release(This) \ (This)->lpVtbl -> Release(This) #define IXDSCodec_get_XDSToRatObjOK(This,pHrCoCreateRetVal) \ (This)->lpVtbl -> get_XDSToRatObjOK(This,pHrCoCreateRetVal) #define IXDSCodec_put_CCSubstreamService(This,SubstreamMask) \ (This)->lpVtbl -> put_CCSubstreamService(This,SubstreamMask) #define IXDSCodec_get_CCSubstreamService(This,pSubstreamMask) \ (This)->lpVtbl -> get_CCSubstreamService(This,pSubstreamMask) #define IXDSCodec_GetContentAdvisoryRating(This,pRat,pPktSeqID,pCallSeqID,pTimeStart,pTimeEnd) \ (This)->lpVtbl -> GetContentAdvisoryRating(This,pRat,pPktSeqID,pCallSeqID,pTimeStart,pTimeEnd) #define IXDSCodec_GetXDSPacket(This,pXDSClassPkt,pXDSTypePkt,pBstrXDSPkt,pPktSeqID,pCallSeqID,pTimeStart,pTimeEnd) \ (This)->lpVtbl -> GetXDSPacket(This,pXDSClassPkt,pXDSTypePkt,pBstrXDSPkt,pPktSeqID,pCallSeqID,pTimeStart,pTimeEnd) #endif /* COBJMACROS */ #endif /* C style interface */ /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IXDSCodec_get_XDSToRatObjOK_Proxy( IXDSCodec * This, /* [retval][out] */ HRESULT *pHrCoCreateRetVal); void __RPC_STUB IXDSCodec_get_XDSToRatObjOK_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE IXDSCodec_put_CCSubstreamService_Proxy( IXDSCodec * This, /* [in] */ long SubstreamMask); void __RPC_STUB IXDSCodec_put_CCSubstreamService_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IXDSCodec_get_CCSubstreamService_Proxy( IXDSCodec * This, /* [retval][out] */ long *pSubstreamMask); void __RPC_STUB IXDSCodec_get_CCSubstreamService_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IXDSCodec_GetContentAdvisoryRating_Proxy( IXDSCodec * This, /* [out] */ PackedTvRating *pRat, /* [out] */ long *pPktSeqID, /* [out] */ long *pCallSeqID, /* [out] */ REFERENCE_TIME *pTimeStart, /* [out] */ REFERENCE_TIME *pTimeEnd); void __RPC_STUB IXDSCodec_GetContentAdvisoryRating_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IXDSCodec_GetXDSPacket_Proxy( IXDSCodec * This, /* [out] */ long *pXDSClassPkt, /* [out] */ long *pXDSTypePkt, /* [out] */ BSTR *pBstrXDSPkt, /* [out] */ long *pPktSeqID, /* [out] */ long *pCallSeqID, /* [out] */ REFERENCE_TIME *pTimeStart, /* [out] */ REFERENCE_TIME *pTimeEnd); void __RPC_STUB IXDSCodec_GetXDSPacket_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IXDSCodec_INTERFACE_DEFINED__ */ #ifndef __IXDSCodecEvents_DISPINTERFACE_DEFINED__ #define __IXDSCodecEvents_DISPINTERFACE_DEFINED__ /* dispinterface IXDSCodecEvents */ /* [helpstring][uuid] */ EXTERN_C const IID DIID_IXDSCodecEvents; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4C3-0049-4E2B-98FB-9537F6CE516D") IXDSCodecEvents : public IDispatch { }; #else /* C style interface */ typedef struct IXDSCodecEventsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IXDSCodecEvents * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IXDSCodecEvents * This); ULONG ( STDMETHODCALLTYPE *Release )( IXDSCodecEvents * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( IXDSCodecEvents * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( IXDSCodecEvents * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( IXDSCodecEvents * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( IXDSCodecEvents * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr); END_INTERFACE } IXDSCodecEventsVtbl; interface IXDSCodecEvents { CONST_VTBL struct IXDSCodecEventsVtbl *lpVtbl; }; #ifdef COBJMACROS #define IXDSCodecEvents_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IXDSCodecEvents_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IXDSCodecEvents_Release(This) \ (This)->lpVtbl -> Release(This) #define IXDSCodecEvents_GetTypeInfoCount(This,pctinfo) \ (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) #define IXDSCodecEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define IXDSCodecEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define IXDSCodecEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IXDSCodecEvents_DISPINTERFACE_DEFINED__ */ EXTERN_C const CLSID CLSID_XDSCodec; #ifdef __cplusplus class DECLSPEC_UUID("C4C4C4F3-0049-4E2B-98FB-9537F6CE516D") XDSCodec; #endif #endif /* __EncDec_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
30.75
119
0.644666
[ "object" ]
00547f7ca0ffacfa825201e5e0036eb224e95f18
26,242
c
C
src/map/lapack2flamec/f2c/c/zlaqz0.c
greck2908/libflame
51d901f5fa1729c018c19110d100d117b91a0e65
[ "BSD-3-Clause" ]
27
2017-10-01T08:26:08.000Z
2022-01-03T20:26:42.000Z
src/map/lapack2flamec/f2c/c/zlaqz0.c
greck2908/libflame
51d901f5fa1729c018c19110d100d117b91a0e65
[ "BSD-3-Clause" ]
null
null
null
src/map/lapack2flamec/f2c/c/zlaqz0.c
greck2908/libflame
51d901f5fa1729c018c19110d100d117b91a0e65
[ "BSD-3-Clause" ]
11
2017-07-30T19:15:00.000Z
2020-02-21T13:18:13.000Z
/* zlaqz0.f -- translated by f2c (version 20160102). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "FLA_f2c.h" /* Table of constant values */ static doublecomplex c_b1 = { 0.,0.} ; static doublecomplex c_b2 = { 1.,0.} ; static integer c__12 = 12; static integer c__13 = 13; static integer c__14 = 14; static integer c__15 = 15; static integer c__17 = 17; static integer c_n1 = -1; static integer c__1 = 1; /* > \brief \b ZLAQZ0 */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download ZLAQZ0 + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zlaqz0. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zlaqz0. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zlaqz0. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE ZLAQZ0( WANTS, WANTQ, WANTZ, N, ILO, IHI, A, LDA, B, */ /* $ LDB, ALPHA, BETA, Q, LDQ, Z, LDZ, WORK, LWORK, RWORK, REC, */ /* $ INFO ) */ /* IMPLICIT NONE */ /* Arguments */ /* CHARACTER, INTENT( IN ) :: WANTS, WANTQ, WANTZ */ /* INTEGER, INTENT( IN ) :: N, ILO, IHI, LDA, LDB, LDQ, LDZ, LWORK, */ /* $ REC */ /* INTEGER, INTENT( OUT ) :: INFO */ /* COMPLEX*16, INTENT( INOUT ) :: A( LDA, * ), B( LDB, * ), Q( LDQ, */ /* $ * ), Z( LDZ, * ), ALPHA( * ), BETA( * ), WORK( * ) */ /* DOUBLE PRECISION, INTENT( OUT ) :: RWORK( * ) */ /* .. */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > ZLAQZ0 computes the eigenvalues of a real matrix pair (H,T), */ /* > where H is an upper Hessenberg matrix and T is upper triangular, */ /* > using the double-shift QZ method. */ /* > Matrix pairs of this type are produced by the reduction to */ /* > generalized upper Hessenberg form of a real matrix pair (A,B): */ /* > */ /* > A = Q1*H*Z1**H, B = Q1*T*Z1**H, */ /* > */ /* > as computed by ZGGHRD. */ /* > */ /* > If JOB='S', then the Hessenberg-triangular pair (H,T) is */ /* > also reduced to generalized Schur form, */ /* > */ /* > H = Q*S*Z**H, T = Q*P*Z**H, */ /* > */ /* > where Q and Z are unitary matrices, P and S are an upper triangular */ /* > matrices. */ /* > */ /* > Optionally, the unitary matrix Q from the generalized Schur */ /* > factorization may be postmultiplied into an input matrix Q1, and the */ /* > unitary matrix Z may be postmultiplied into an input matrix Z1. */ /* > If Q1 and Z1 are the unitary matrices from ZGGHRD that reduced */ /* > the matrix pair (A,B) to generalized upper Hessenberg form, then the */ /* > output matrices Q1*Q and Z1*Z are the unitary factors from the */ /* > generalized Schur factorization of (A,B): */ /* > */ /* > A = (Q1*Q)*S*(Z1*Z)**H, B = (Q1*Q)*P*(Z1*Z)**H. */ /* > */ /* > To avoid overflow, eigenvalues of the matrix pair (H,T) (equivalently, */ /* > of (A,B)) are computed as a pair of values (alpha,beta), where alpha is */ /* > complex and beta real. */ /* > If beta is nonzero, lambda = alpha / beta is an eigenvalue of the */ /* > generalized nonsymmetric eigenvalue problem (GNEP) */ /* > A*x = lambda*B*x */ /* > and if alpha is nonzero, mu = beta / alpha is an eigenvalue of the */ /* > alternate form of the GNEP */ /* > mu*A*y = B*y. */ /* > Eigenvalues can be read directly from the generalized Schur */ /* > form: */ /* > alpha = S(i,i), beta = P(i,i). */ /* > */ /* > Ref: C.B. Moler & G.W. Stewart, "An Algorithm for Generalized Matrix */ /* > Eigenvalue Problems", SIAM J. Numer. Anal., 10(1973), */ /* > pp. 241--256. */ /* > */ /* > Ref: B. Kagstrom, D. Kressner, "Multishift Variants of the QZ */ /* > Algorithm with Aggressive Early Deflation", SIAM J. Numer. */ /* > Anal., 29(2006), pp. 199--227. */ /* > */ /* > Ref: T. Steel, D. Camps, K. Meerbergen, R. Vandebril "A multishift, */ /* > multipole rational QZ method with agressive early deflation" */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] WANTS */ /* > \verbatim */ /* > WANTS is CHARACTER*1 */ /* > = 'E': Compute eigenvalues only; */ /* > = 'S': Compute eigenvalues and the Schur form. */ /* > \endverbatim */ /* > */ /* > \param[in] WANTQ */ /* > \verbatim */ /* > WANTQ is CHARACTER*1 */ /* > = 'N': Left Schur vectors (Q) are not computed; */ /* > = 'I': Q is initialized to the unit matrix and the matrix Q */ /* > of left Schur vectors of (A,B) is returned; */ /* > = 'V': Q must contain an unitary matrix Q1 on entry and */ /* > the product Q1*Q is returned. */ /* > \endverbatim */ /* > */ /* > \param[in] WANTZ */ /* > \verbatim */ /* > WANTZ is CHARACTER*1 */ /* > = 'N': Right Schur vectors (Z) are not computed; */ /* > = 'I': Z is initialized to the unit matrix and the matrix Z */ /* > of right Schur vectors of (A,B) is returned; */ /* > = 'V': Z must contain an unitary matrix Z1 on entry and */ /* > the product Z1*Z is returned. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The order of the matrices A, B, Q, and Z. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] ILO */ /* > \verbatim */ /* > ILO is INTEGER */ /* > \endverbatim */ /* > */ /* > \param[in] IHI */ /* > \verbatim */ /* > IHI is INTEGER */ /* > ILO and IHI mark the rows and columns of A which are in */ /* > Hessenberg form. It is assumed that A is already upper */ /* > triangular in rows and columns 1:ILO-1 and IHI+1:N. */ /* > If N > 0, 1 <= ILO <= IHI <= N; if N = 0, ILO=1 and IHI=0. */ /* > \endverbatim */ /* > */ /* > \param[in,out] A */ /* > \verbatim */ /* > A is COMPLEX*16 array, dimension (LDA, N) */ /* > On entry, the N-by-N upper Hessenberg matrix A. */ /* > On exit, if JOB = 'S', A contains the upper triangular */ /* > matrix S from the generalized Schur factorization. */ /* > If JOB = 'E', the diagonal blocks of A match those of S, but */ /* > the rest of A is unspecified. */ /* > \endverbatim */ /* > */ /* > \param[in] LDA */ /* > \verbatim */ /* > LDA is INTEGER */ /* > The leading dimension of the array A. LDA >= max( 1, N ). */ /* > \endverbatim */ /* > */ /* > \param[in,out] B */ /* > \verbatim */ /* > B is COMPLEX*16 array, dimension (LDB, N) */ /* > On entry, the N-by-N upper triangular matrix B. */ /* > On exit, if JOB = 'S', B contains the upper triangular */ /* > matrix P from the generalized Schur factorization; */ /* > If JOB = 'E', the diagonal blocks of B match those of P, but */ /* > the rest of B is unspecified. */ /* > \endverbatim */ /* > */ /* > \param[in] LDB */ /* > \verbatim */ /* > LDB is INTEGER */ /* > The leading dimension of the array B. LDB >= max( 1, N ). */ /* > \endverbatim */ /* > */ /* > \param[out] ALPHA */ /* > \verbatim */ /* > ALPHA is COMPLEX*16 array, dimension (N) */ /* > Each scalar alpha defining an eigenvalue */ /* > of GNEP. */ /* > \endverbatim */ /* > */ /* > \param[out] BETA */ /* > \verbatim */ /* > BETA is COMPLEX*16 array, dimension (N) */ /* > The scalars beta that define the eigenvalues of GNEP. */ /* > Together, the quantities alpha = ALPHA(j) and */ /* > beta = BETA(j) represent the j-th eigenvalue of the matrix */ /* > pair (A,B), in one of the forms lambda = alpha/beta or */ /* > mu = beta/alpha. Since either lambda or mu may overflow, */ /* > they should not, in general, be computed. */ /* > \endverbatim */ /* > */ /* > \param[in,out] Q */ /* > \verbatim */ /* > Q is COMPLEX*16 array, dimension (LDQ, N) */ /* > On entry, if COMPQ = 'V', the unitary matrix Q1 used in */ /* > the reduction of (A,B) to generalized Hessenberg form. */ /* > On exit, if COMPQ = 'I', the unitary matrix of left Schur */ /* > vectors of (A,B), and if COMPQ = 'V', the unitary matrix */ /* > of left Schur vectors of (A,B). */ /* > Not referenced if COMPQ = 'N'. */ /* > \endverbatim */ /* > */ /* > \param[in] LDQ */ /* > \verbatim */ /* > LDQ is INTEGER */ /* > The leading dimension of the array Q. LDQ >= 1. */ /* > If COMPQ='V' or 'I', then LDQ >= N. */ /* > \endverbatim */ /* > */ /* > \param[in,out] Z */ /* > \verbatim */ /* > Z is COMPLEX*16 array, dimension (LDZ, N) */ /* > On entry, if COMPZ = 'V', the unitary matrix Z1 used in */ /* > the reduction of (A,B) to generalized Hessenberg form. */ /* > On exit, if COMPZ = 'I', the unitary matrix of */ /* > right Schur vectors of (H,T), and if COMPZ = 'V', the */ /* > unitary matrix of right Schur vectors of (A,B). */ /* > Not referenced if COMPZ = 'N'. */ /* > \endverbatim */ /* > */ /* > \param[in] LDZ */ /* > \verbatim */ /* > LDZ is INTEGER */ /* > The leading dimension of the array Z. LDZ >= 1. */ /* > If COMPZ='V' or 'I', then LDZ >= N. */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is COMPLEX*16 array, dimension (MAX(1,LWORK)) */ /* > On exit, if INFO >= 0, WORK(1) returns the optimal LWORK. */ /* > \endverbatim */ /* > */ /* > \param[out] RWORK */ /* > \verbatim */ /* > RWORK is DOUBLE PRECISION array, dimension (N) */ /* > \endverbatim */ /* > */ /* > \param[in] LWORK */ /* > \verbatim */ /* > LWORK is INTEGER */ /* > The dimension of the array WORK. LWORK >= max(1,N). */ /* > */ /* > If LWORK = -1, then a workspace query is assumed; the routine */ /* > only calculates the optimal size of the WORK array, returns */ /* > this value as the first entry of the WORK array, and no error */ /* > message related to LWORK is issued by XERBLA. */ /* > \endverbatim */ /* > */ /* > \param[in] REC */ /* > \verbatim */ /* > REC is INTEGER */ /* > REC indicates the current recursion level. Should be set */ /* > to 0 on first call. */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > = 1,...,N: the QZ iteration did not converge. (A,B) is not */ /* > in Schur form, but ALPHA(i) and */ /* > BETA(i), i=INFO+1,...,N should be correct. */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Thijs Steel, KU Leuven */ /* > \date May 2020 */ /* > \ingroup complex16GEcomputational */ /* > */ /* ===================================================================== */ /* Subroutine */ int zlaqz0_(char *wants, char *wantq, char *wantz, integer * n, integer *ilo, integer *ihi, doublecomplex *a, integer *lda, doublecomplex *b, integer *ldb, doublecomplex *alpha, doublecomplex * beta, doublecomplex *q, integer *ldq, doublecomplex *z__, integer * ldz, doublecomplex *work, integer *lwork, doublereal *rwork, integer * rec, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, q_dim1, q_offset, z_dim1, z_offset, i__1, i__2, i__3, i__4, i__5; doublereal d__1, d__2; doublecomplex z__1, z__2; /* Builtin functions */ double sqrt(doublereal), z_abs(doublecomplex *); void d_cnjg(doublecomplex *, doublecomplex *), z_div(doublecomplex *, doublecomplex *, doublecomplex *); /* Local variables */ integer aed_info__; extern /* Subroutine */ int f90_cycle_(void); integer shiftpos, lworkreq, k; doublereal c1; integer k2; doublecomplex s1; integer norm_info__, ld, ns, n_deflated__, nw, sweep_info__, nbr; logical ilq, ilz; doublereal ulp; integer nsr, nwr, nmin; doublecomplex temp; integer n_undeflated__; extern /* Subroutine */ int zrot_(integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublereal *, doublecomplex *); extern logical lsame_(char *, char *); integer iiter, maxit; doublereal tempr; integer rcost, istop, itemp1, itemp2; extern /* Subroutine */ int dlabad_(doublereal *, doublereal *), zlaqz2_( logical *, logical *, logical *, integer *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, integer * , integer *, doublecomplex *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublereal *, integer *, integer *), zlaqz3_(logical *, logical * , logical *, integer *, integer *, integer *, integer *, integer * , doublecomplex *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, integer *) ; extern doublereal dlamch_(char *); integer nibble, nblock; doublereal safmin; extern /* Subroutine */ int xerbla_(char *, integer *); doublereal safmax; extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *); doublecomplex eshift; char jbcmpz[3]; extern /* Subroutine */ int zlaset_(char *, integer *, integer *, doublecomplex *, doublecomplex *, doublecomplex *, integer *); integer iwantq; extern /* Subroutine */ int zlartg_(doublecomplex *, doublecomplex *, doublereal *, doublecomplex *, doublecomplex *); integer iwants, istart; extern /* Subroutine */ int zhgeqz_(char *, char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublereal *, integer *); doublereal smlnum; integer istopm, iwantz, istart2; extern /* Subroutine */ int f90_exit_(void); logical ilschur; integer nshifts, istartm; /* Arguments */ /* const */ /* const */ /* Parameters */ /* Local scalars */ /* External Functions */ /* extern dlamch */ /* Decode wantS,wantQ,wantZ */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; --alpha; --beta; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; --work; --rwork; /* Function Body */ if (lsame_(wants, "E")) { ilschur = FALSE_; iwants = 1; } else if (lsame_(wants, "S")) { ilschur = TRUE_; iwants = 2; } else { iwants = 0; } if (lsame_(wantq, "N")) { ilq = FALSE_; iwantq = 1; } else if (lsame_(wantq, "V")) { ilq = TRUE_; iwantq = 2; } else if (lsame_(wantq, "I")) { ilq = TRUE_; iwantq = 3; } else { iwantq = 0; } if (lsame_(wantz, "N")) { ilz = FALSE_; iwantz = 1; } else if (lsame_(wantz, "V")) { ilz = TRUE_; iwantz = 2; } else if (lsame_(wantz, "I")) { ilz = TRUE_; iwantz = 3; } else { iwantz = 0; } /* Check Argument Values */ *info = 0; if (iwants == 0) { *info = -1; } else if (iwantq == 0) { *info = -2; } else if (iwantz == 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if (*ilo < 1) { *info = -5; } else if (*ihi > *n || *ihi < *ilo - 1) { *info = -6; } else if (*lda < *n) { *info = -8; } else if (*ldb < *n) { *info = -10; } else if (*ldq < 1 || ilq && *ldq < *n) { *info = -15; } else if (*ldz < 1 || ilz && *ldz < *n) { *info = -17; } if (*info != 0) { i__1 = -(*info); xerbla_("ZLAQZ0", &i__1); return 0; } /* Quick return if possible */ if (*n <= 0) { work[1].r = 1.; work[1].i = 0.; // , expr subst return 0; } /* Get the parameters */ *(unsigned char *)jbcmpz = *(unsigned char *)wants; *(unsigned char *)&jbcmpz[1] = *(unsigned char *)wantq; *(unsigned char *)&jbcmpz[2] = *(unsigned char *)wantz; nmin = ilaenv_(&c__12, "ZLAQZ0", jbcmpz, n, ilo, ihi, lwork); nwr = ilaenv_(&c__13, "ZLAQZ0", jbcmpz, n, ilo, ihi, lwork); nwr = max(2,nwr); /* Computing MIN */ i__1 = *ihi - *ilo + 1; i__2 = (*n - 1) / 3; i__1 = min(i__1,i__2); // ; expr subst nwr = min(i__1,nwr); nibble = ilaenv_(&c__14, "ZLAQZ0", jbcmpz, n, ilo, ihi, lwork); nsr = ilaenv_(&c__15, "ZLAQZ0", jbcmpz, n, ilo, ihi, lwork); /* Computing MIN */ i__1 = nsr, i__2 = (*n + 6) / 9; i__1 = min(i__1,i__2); i__2 = *ihi - * ilo; // ; expr subst nsr = min(i__1,i__2); /* Computing MAX */ i__1 = 2; i__2 = nsr - nsr % 2; // , expr subst nsr = max(i__1,i__2); rcost = ilaenv_(&c__17, "ZLAQZ0", jbcmpz, n, ilo, ihi, lwork); itemp1 = (integer) (nsr / sqrt((nsr << 1) / ((doublereal) rcost / 100 * * n) + 1)); itemp1 = ((itemp1 - 1) / 4 << 2) + 4; nbr = nsr + itemp1; if (*n < nmin || *rec >= 2) { zhgeqz_(wants, wantq, wantz, n, ilo, ihi, &a[a_offset], lda, &b[ b_offset], ldb, &alpha[1], &beta[1], &q[q_offset], ldq, &z__[ z_offset], ldz, &work[1], lwork, &rwork[1], info); return 0; } /* Find out required workspace */ /* Workspace query to ZLAQZ2 */ nw = max(nwr,nmin); zlaqz2_(&ilschur, &ilq, &ilz, n, ilo, ihi, &nw, &a[a_offset], lda, &b[ b_offset], ldb, &q[q_offset], ldq, &z__[z_offset], ldz, & n_undeflated__, &n_deflated__, &alpha[1], &beta[1], &work[1], &nw, &work[1], &nw, &work[1], &c_n1, &rwork[1], rec, &aed_info__); itemp1 = (integer) work[1].r; /* Workspace query to ZLAQZ3 */ zlaqz3_(&ilschur, &ilq, &ilz, n, ilo, ihi, &nsr, &nbr, &alpha[1], &beta[1] , &a[a_offset], lda, &b[b_offset], ldb, &q[q_offset], ldq, &z__[ z_offset], ldz, &work[1], &nbr, &work[1], &nbr, &work[1], &c_n1, & sweep_info__); itemp2 = (integer) work[1].r; /* Computing MAX */ /* Computing 2nd power */ i__3 = nw; /* Computing 2nd power */ i__4 = nbr; i__1 = itemp1 + (i__3 * i__3 << 1); i__2 = itemp2 + (i__4 * i__4 << 1); // , expr subst lworkreq = max(i__1,i__2); if (*lwork == -1) { d__1 = (doublereal) lworkreq; work[1].r = d__1; work[1].i = 0.; // , expr subst return 0; } else if (*lwork < lworkreq) { *info = -19; } if (*info != 0) { xerbla_("ZLAQZ0", info); return 0; } /* Initialize Q and Z */ if (iwantq == 3) { zlaset_("FULL", n, n, &c_b1, &c_b2, &q[q_offset], ldq); } if (iwantz == 3) { zlaset_("FULL", n, n, &c_b1, &c_b2, &z__[z_offset], ldz); } /* Get machine constants */ safmin = dlamch_("SAFE MINIMUM"); safmax = 1. / safmin; dlabad_(&safmin, &safmax); ulp = dlamch_("PRECISION"); smlnum = safmin * ((doublereal) (*n) / ulp); istart = *ilo; istop = *ihi; maxit = (*ihi - *ilo + 1) * 30; ld = 0; i__1 = maxit; for (iiter = 1; iiter <= i__1; ++iiter) { if (iiter >= maxit) { *info = istop + 1; goto L80; } if (istart + 1 >= istop) { istop = istart; break; } /* Check deflations at the end */ /* Computing MAX */ d__1 = smlnum; d__2 = ulp * (z_abs(&a[istop + istop * a_dim1]) + z_abs(&a[istop - 1 + (istop - 1) * a_dim1])); // , expr subst if (z_abs(&a[istop + (istop - 1) * a_dim1]) <= max(d__1,d__2)) { i__2 = istop + (istop - 1) * a_dim1; a[i__2].r = 0.; a[i__2].i = 0.; // , expr subst --istop; ld = 0; eshift.r = 0.; eshift.i = 0.; // , expr subst } /* Check deflations at the start */ /* Computing MAX */ d__1 = smlnum; d__2 = ulp * (z_abs(&a[istart + istart * a_dim1]) + z_abs(&a[istart + 1 + (istart + 1) * a_dim1])); // , expr subst if (z_abs(&a[istart + 1 + istart * a_dim1]) <= max(d__1,d__2)) { i__2 = istart + 1 + istart * a_dim1; a[i__2].r = 0.; a[i__2].i = 0.; // , expr subst ++istart; ld = 0; eshift.r = 0.; eshift.i = 0.; // , expr subst } if (istart + 1 >= istop) { break; } /* Check interior deflations */ istart2 = istart; i__2 = istart + 1; for (k = istop; k >= i__2; --k) { /* Computing MAX */ d__1 = smlnum; d__2 = ulp * (z_abs(&a[k + k * a_dim1]) + z_abs(&a[ k - 1 + (k - 1) * a_dim1])); // , expr subst if (z_abs(&a[k + (k - 1) * a_dim1]) <= max(d__1,d__2)) { i__3 = k + (k - 1) * a_dim1; a[i__3].r = 0.; a[i__3].i = 0.; // , expr subst istart2 = k; break; } } /* Get range to apply rotations to */ if (ilschur) { istartm = 1; istopm = *n; } else { istartm = istart2; istopm = istop; } /* Check infinite eigenvalues, this is done without blocking so might */ /* slow down the method when many infinite eigenvalues are present */ k = istop; while(k >= istart2) { tempr = 0.; if (k < istop) { tempr += z_abs(&b[k + (k + 1) * b_dim1]); } if (k > istart2) { tempr += z_abs(&b[k - 1 + k * b_dim1]); } /* Computing MAX */ d__1 = smlnum; d__2 = ulp * tempr; // , expr subst if (z_abs(&b[k + k * b_dim1]) < max(d__1,d__2)) { /* A diagonal element of B is negligable, move it */ /* to the top and deflate it */ i__2 = istart2 + 1; for (k2 = k; k2 >= i__2; --k2) { zlartg_(&b[k2 - 1 + k2 * b_dim1], &b[k2 - 1 + (k2 - 1) * b_dim1], &c1, &s1, &temp); i__3 = k2 - 1 + k2 * b_dim1; b[i__3].r = temp.r; b[i__3].i = temp.i; // , expr subst i__3 = k2 - 1 + (k2 - 1) * b_dim1; b[i__3].r = 0.; b[i__3].i = 0.; // , expr subst i__3 = k2 - 2 - istartm + 1; zrot_(&i__3, &b[istartm + k2 * b_dim1], &c__1, &b[istartm + (k2 - 1) * b_dim1], &c__1, &c1, &s1); /* Computing MIN */ i__4 = k2 + 1; i__3 = min(i__4,istop) - istartm + 1; zrot_(&i__3, &a[istartm + k2 * a_dim1], &c__1, &a[istartm + (k2 - 1) * a_dim1], &c__1, &c1, &s1); if (ilz) { zrot_(n, &z__[k2 * z_dim1 + 1], &c__1, &z__[(k2 - 1) * z_dim1 + 1], &c__1, &c1, &s1); } if (k2 < istop) { zlartg_(&a[k2 + (k2 - 1) * a_dim1], &a[k2 + 1 + (k2 - 1) * a_dim1], &c1, &s1, &temp); i__3 = k2 + (k2 - 1) * a_dim1; a[i__3].r = temp.r; a[i__3].i = temp.i; // , expr subst i__3 = k2 + 1 + (k2 - 1) * a_dim1; a[i__3].r = 0.; a[i__3].i = 0.; // , expr subst i__3 = istopm - k2 + 1; zrot_(&i__3, &a[k2 + k2 * a_dim1], lda, &a[k2 + 1 + k2 * a_dim1], lda, &c1, &s1); i__3 = istopm - k2 + 1; zrot_(&i__3, &b[k2 + k2 * b_dim1], ldb, &b[k2 + 1 + k2 * b_dim1], ldb, &c1, &s1); if (ilq) { d_cnjg(&z__1, &s1); zrot_(n, &q[k2 * q_dim1 + 1], &c__1, &q[(k2 + 1) * q_dim1 + 1], &c__1, &c1, &z__1); } } } if (istart2 < istop) { zlartg_(&a[istart2 + istart2 * a_dim1], &a[istart2 + 1 + istart2 * a_dim1], &c1, &s1, &temp); i__2 = istart2 + istart2 * a_dim1; a[i__2].r = temp.r; a[i__2].i = temp.i; // , expr subst i__2 = istart2 + 1 + istart2 * a_dim1; a[i__2].r = 0.; a[i__2].i = 0.; // , expr subst i__2 = istopm - (istart2 + 1) + 1; zrot_(&i__2, &a[istart2 + (istart2 + 1) * a_dim1], lda, & a[istart2 + 1 + (istart2 + 1) * a_dim1], lda, &c1, &s1); i__2 = istopm - (istart2 + 1) + 1; zrot_(&i__2, &b[istart2 + (istart2 + 1) * b_dim1], ldb, & b[istart2 + 1 + (istart2 + 1) * b_dim1], ldb, &c1, &s1); if (ilq) { d_cnjg(&z__1, &s1); zrot_(n, &q[istart2 * q_dim1 + 1], &c__1, &q[(istart2 + 1) * q_dim1 + 1], &c__1, &c1, &z__1); } } ++istart2; } --k; } /* istart2 now points to the top of the bottom right */ /* unreduced Hessenberg block */ if (istart2 >= istop) { istop = istart2 - 1; ld = 0; eshift.r = 0.; eshift.i = 0.; // , expr subst continue; } nw = nwr; nshifts = nsr; nblock = nbr; if (istop - istart2 + 1 < nmin) { /* Setting nw to the size of the subblock will make AED deflate */ /* all the eigenvalues. This is slightly more efficient than just */ /* using qz_small because the off diagonal part gets updated via BLAS. */ if (istop - istart + 1 < nmin) { nw = istop - istart + 1; istart2 = istart; } else { nw = istop - istart2 + 1; } } /* Time for AED */ /* Computing 2nd power */ i__2 = nw; /* Computing 2nd power */ i__3 = nw; /* Computing 2nd power */ i__5 = nw; i__4 = *lwork - (i__5 * i__5 << 1); zlaqz2_(&ilschur, &ilq, &ilz, n, &istart2, &istop, &nw, &a[a_offset], lda, &b[b_offset], ldb, &q[q_offset], ldq, &z__[z_offset], ldz, &n_undeflated__, &n_deflated__, &alpha[1], &beta[1], & work[1], &nw, &work[i__2 * i__2 + 1], &nw, &work[(i__3 * i__3 << 1) + 1], &i__4, &rwork[1], rec, &aed_info__); if (n_deflated__ > 0) { istop -= n_deflated__; ld = 0; eshift.r = 0.; eshift.i = 0.; // , expr subst } if (n_deflated__ * 100 > nibble * (n_deflated__ + n_undeflated__) || istop - istart2 + 1 < nmin) { /* AED has uncovered many eigenvalues. Skip a QZ sweep and run */ /* AED again. */ continue; } ++ld; /* Computing MIN */ i__2 = nshifts; i__3 = istop - istart2; // , expr subst ns = min(i__2,i__3); ns = min(ns,n_undeflated__); shiftpos = istop - n_deflated__ - n_undeflated__ + 1; if (ld % 6 == 0) { /* Exceptional shift. Chosen for no particularly good reason. */ if ((doublereal) maxit * safmin * z_abs(&a[istop + (istop - 1) * a_dim1]) < z_abs(&a[istop - 1 + (istop - 1) * a_dim1])) { z_div(&z__1, &a[istop + (istop - 1) * a_dim1], &b[istop - 1 + (istop - 1) * b_dim1]); eshift.r = z__1.r; eshift.i = z__1.i; // , expr subst } else { d__1 = safmin * (doublereal) maxit; z__2.r = 1. / d__1; z__2.i = 0. / d__1; // , expr subst z__1.r = eshift.r + z__2.r; z__1.i = eshift.i + z__2.i; // , expr subst eshift.r = z__1.r; eshift.i = z__1.i; // , expr subst } i__2 = shiftpos; alpha[i__2].r = 1.; alpha[i__2].i = 0.; // , expr subst i__2 = shiftpos; beta[i__2].r = eshift.r; beta[i__2].i = eshift.i; // , expr subst ns = 1; } /* Time for a QZ sweep */ /* Computing 2nd power */ i__2 = nblock; /* Computing 2nd power */ i__3 = nblock; /* Computing 2nd power */ i__5 = nblock; i__4 = *lwork - (i__5 * i__5 << 1); zlaqz3_(&ilschur, &ilq, &ilz, n, &istart2, &istop, &ns, &nblock, & alpha[shiftpos], &beta[shiftpos], &a[a_offset], lda, &b[ b_offset], ldb, &q[q_offset], ldq, &z__[z_offset], ldz, &work[ 1], &nblock, &work[i__2 * i__2 + 1], &nblock, &work[(i__3 * i__3 << 1) + 1], &i__4, &sweep_info__); } /* Call ZHGEQZ to normalize the eigenvalue blocks and set the eigenvalues */ /* If all the eigenvalues have been found, ZHGEQZ will not do any iterations */ /* and only normalize the blocks. In case of a rare convergence failure, */ /* the single shift might perform better. */ L80: zhgeqz_(wants, wantq, wantz, n, ilo, ihi, &a[a_offset], lda, &b[b_offset], ldb, &alpha[1], &beta[1], &q[q_offset], ldq, &z__[z_offset], ldz, &work[1], lwork, &rwork[1], &norm_info__); *info = norm_info__; return 0; } /* zlaqz0_ */
35.654891
758
0.579415
[ "object" ]
5320d398c324c91979683a00e8c18bf6705a1a93
3,152
h
C
cc/layers/nine_patch_layer_impl.h
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
5
2019-05-24T01:25:34.000Z
2020-04-06T05:07:01.000Z
cc/layers/nine_patch_layer_impl.h
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
null
null
null
cc/layers/nine_patch_layer_impl.h
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
5
2016-12-23T04:21:10.000Z
2020-06-18T13:52:33.000Z
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CC_LAYERS_NINE_PATCH_LAYER_IMPL_H_ #define CC_LAYERS_NINE_PATCH_LAYER_IMPL_H_ #include <string> #include "cc/base/cc_export.h" #include "cc/layers/layer_impl.h" #include "cc/layers/ui_resource_layer_impl.h" #include "cc/resources/resource_provider.h" #include "cc/resources/ui_resource_client.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" namespace base { class DictionaryValue; } namespace cc { class CC_EXPORT NinePatchLayerImpl : public UIResourceLayerImpl { public: static scoped_ptr<NinePatchLayerImpl> Create(LayerTreeImpl* tree_impl, int id) { return make_scoped_ptr(new NinePatchLayerImpl(tree_impl, id)); } ~NinePatchLayerImpl() override; // The bitmap stretches out the bounds of the layer. The following picture // illustrates the parameters associated with the dimensions. // // Layer space layout Bitmap space layout // // ------------------------ ~~~~~~~~~~ W ~~~~~~~~~~ // | : | : : | // | C | : Y | // | : | : : | // | ------------ | :~~X~~------------ | // | | | | : | : | // | | | | : | : | // |~~A~~| |~~B~~| H | Q | // | | | | : | : | // | ------------ | : ~~~~~P~~~~~ | // | : | : | // | D | : | // | : | : | // ------------------------ ------------------------ // // |image_bounds| = (W, H) // |image_aperture| = (X, Y, P, Q) // |border| = (A, C, A + B, C + D) // |fill_center| indicates whether to draw the center quad or not. void SetLayout(const gfx::Rect& image_aperture, const gfx::Rect& border, bool fill_center); scoped_ptr<LayerImpl> CreateLayerImpl(LayerTreeImpl* tree_impl) override; void PushPropertiesTo(LayerImpl* layer) override; void AppendQuads(RenderPass* render_pass, const Occlusion& occlusion_in_content_space, AppendQuadsData* append_quads_data) override; base::DictionaryValue* LayerTreeAsJson() const override; protected: NinePatchLayerImpl(LayerTreeImpl* tree_impl, int id); private: const char* LayerTypeAsString() const override; void CheckGeometryLimitations(); // The transparent center region that shows the parent layer's contents in // image space. gfx::Rect image_aperture_; // An inset border that the patches will be mapped to. gfx::Rect border_; bool fill_center_; DISALLOW_COPY_AND_ASSIGN(NinePatchLayerImpl); }; } // namespace cc #endif // CC_LAYERS_NINE_PATCH_LAYER_IMPL_H_
34.26087
77
0.524429
[ "geometry" ]
53247759ae3d6f175bab661ba1b2a7cc4c8cbd07
1,844
h
C
Gems/LmbrCentral/Code/Source/Scripting/EditorSpawnerComponent.h
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/LmbrCentral/Code/Source/Scripting/EditorSpawnerComponent.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/LmbrCentral/Code/Source/Scripting/EditorSpawnerComponent.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <AzToolsFramework/ToolsComponents/EditorComponentBase.h> #include <AzCore/Slice/SliceAsset.h> namespace LmbrCentral { /** * Editor spawner component * Spawns the entities from a ".dynamicslice" asset at runtime. */ class EditorSpawnerComponent : public AzToolsFramework::Components::EditorComponentBase { public: AZ_EDITOR_COMPONENT(EditorSpawnerComponent, "{77CDE991-EC1A-B7C1-B112-7456ABAC81A1}", EditorComponentBase); static void Reflect(AZ::ReflectContext* context); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType&); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType&); static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType&); bool ReadInConfig(const AZ::ComponentConfig* baseConfig) override; bool WriteOutConfig(AZ::ComponentConfig* outBaseConfig) const override; void BuildGameEntity(AZ::Entity* gameEntity) override; protected: ////////////////////////////////////////////////////////////////////////// // Data changed validation methods AZ::u32 SliceAssetChanged(); AZ::u32 SpawnOnActivateChanged(); bool HasInfiniteLoop(); ////////////////////////////////////////////////////////////////////////// // Serialized members AZ::Data::Asset<AZ::DynamicSliceAsset> m_sliceAsset{ AZ::Data::AssetLoadBehavior::PreLoad }; bool m_spawnOnActivate = false; bool m_destroyOnDeactivate = false; }; } // namespace LmbrCentral
36.88
115
0.652928
[ "3d" ]
532982278a81e1c174ed817dee182669576c29bb
993
h
C
engine/core/render/metal/mt_renderable.h
Houkime/echo
d115ca55faf3a140bea04feffeb2efdedb0e7f82
[ "MIT" ]
null
null
null
engine/core/render/metal/mt_renderable.h
Houkime/echo
d115ca55faf3a140bea04feffeb2efdedb0e7f82
[ "MIT" ]
null
null
null
engine/core/render/metal/mt_renderable.h
Houkime/echo
d115ca55faf3a140bea04feffeb2efdedb0e7f82
[ "MIT" ]
null
null
null
#pragma once #include "base/Renderable.h" #include "mt_render_base.h" namespace Echo { class MTRenderable : public Renderable { public: MTRenderable(int identifier); virtual ~MTRenderable() {} // get render pipelinestate id<MTLRenderPipelineState> getMetalRenderPipelineState() { return m_metalRenderPipelineState; } // get metal buffer id<MTLBuffer> getMetalIndexBuffer(); id<MTLBuffer> getMetalVertexBuffer(); // bind shader uniforms void bindShaderParams(); private: // link virtual void setMesh(MeshPtr mesh); // build vertex descriptor void buildVertexDescriptor(); // build render pipeline state void buildRenderPipelineState(); private: MTLVertexDescriptor* m_metalVertexDescriptor = nullptr; id<MTLRenderPipelineState> m_metalRenderPipelineState = nullptr; }; }
25.461538
103
0.623364
[ "mesh", "render" ]
532c52c25c5f35f1265298e9cabef83f913e297f
32,527
c
C
src/main.c
lorossi/pomoc
6f63c32ea840b23000b6e0f3be0ae5a855eb9455
[ "CC-BY-4.0" ]
null
null
null
src/main.c
lorossi/pomoc
6f63c32ea840b23000b6e0f3be0ae5a855eb9455
[ "CC-BY-4.0" ]
null
null
null
src/main.c
lorossi/pomoc
6f63c32ea840b23000b6e0f3be0ae5a855eb9455
[ "CC-BY-4.0" ]
null
null
null
#define _DEFAULT_SOURCE // for nanosleep #include <stdio.h> #include <sys/time.h> // for gettimeofday #include <time.h> // for timespec #include <signal.h> // for signal() #include <unistd.h> // for nanosleep() #include <pthread.h> // for multithread #include <string.h> // for strlen() #include <stdlib.h> // for malloc() and free() and rand() #include "terminal.h" #include "constants.h" #include "structures.h" // global variables are bad but there's no other way to pass data from interrupts volatile int sigint_called; // flag for sigint volatile int sigwinch_called; // flag for sigwinch int file_read_line(char *buffer, int max_bytes, FILE *fp); int file_count_lines(FILE *fp); int check_savefile(); int load_savefile(Parameters *p, Phase *phases); int save_savefile(Parameters *p); int check_settings(); int load_settings(int *durations); int save_settings(int *durations); void SIGWINCH_handler(); void SIGINT_handler(); unsigned long long epoch(); void ms_sleep(int ms); void s_sleep(int sec); Phase *init_phases(Phase *phases, int argc, char *argv[]); Windows *init_windows(); Parameters *init_parameters(Phase *current_phase, Windows *windows); void delete_parameters(Parameters *p); Phase *set_initial_phase(Phase *phases); void reset_current_time(Parameters *p); void start_time(Parameters *p); void pause_time(Parameters *p); void next_phase(Parameters *p); int phase_time_remaining(); void format_elapsed_time(char *buffer, int elapsed); void format_date(char *buffer); void format_time_delta(char *buffer, int delta_seconds); int place_random_quote(Window *w); void set_windows_visibility(Parameters *p, int visibility); void *beep_async(void *args); void *show_routine(void *args); void *advance_routine(void *args); void *save_routine(void *args); void *keypress_routine(void *args); int check_routines(Parameters *p); int main(int argc, char *argv[]); /** * @brief Reads a line from file, advance the pointer. * * @param buffer pointer to line buffer * @param max_bytes maximum number of bytes to read * @param fp pointer to file * @return int number of read bytes, -1 in case of error */ int file_read_line(char *buffer, int max_bytes, FILE *fp) { if (fgets(buffer, max_bytes, fp) == NULL) return -1; int len = strlen(buffer); // remove newline from last character buffer[len - 1] = '\0'; return len; } /** * @brief Counts number of lines in a file. * * @param fp pointer to file * @return int number of lines in file */ int file_count_lines(FILE *fp) { fpos_t old_pos; int lines; // save old position fgetpos(fp, &old_pos); // reset to start rewind(fp); lines = 0; while (!feof(fp)) { char ch = fgetc(fp); if (ch == '\n') lines++; } // return to old position fsetpos(fp, &old_pos); return lines; } /** * @brief Checks if a save from today is already present. * * @return int -1 if file is not found, -2 is save is from another day, 1 if save is valid */ int check_savefile() { FILE *fp; char buffer[BUFLEN]; char r_buffer[BUFLEN]; fp = fopen(SAVE_PATH, "r"); if (fp == NULL) return -1; // read date if (file_read_line(r_buffer, BUFLEN, fp) == -1) return -1; // format current date format_date(buffer); if (strcmp(buffer, r_buffer) != 0) return -2; fclose(fp); return 1; } /** * @brief Loads save from file. * * @param p pointer to parameters structs * @param phases pointer to phases * @return int -1 if file is not found, negative values for other errors, 0 if save is correctly loaded */ int load_savefile(Parameters *p, Phase *phases) { FILE *fp; char r_buffer[BUFLEN]; int num_buffer; // if the save is not from today, return if (check_savefile() == -1) return -2; fp = fopen(SAVE_PATH, "r"); if (fp == NULL) return -1; // read date, discarding first line if (file_read_line(r_buffer, BUFLEN, fp) == -1) return -1; // read phase elapsed if (file_read_line(r_buffer, BUFLEN, fp) == -1) return -2; // update the parameters struct p->phase_elapsed = atoi(r_buffer); // read total study elapsed if (file_read_line(r_buffer, BUFLEN, fp) == -1) return -3; // update the parameters struct p->previous_elapsed = atoi(r_buffer); // read total study phases if (file_read_line(r_buffer, BUFLEN, fp) == -1) return -4; // update the parameters struct p->study_phases = atoi(r_buffer); // read current phase id if (file_read_line(r_buffer, BUFLEN, fp) == -1) return -5; // update the parameters struct num_buffer = atoi(r_buffer); // cycle to find the correct phase for (int i = 0; i < 3; i++) { if (phases[i].id == num_buffer) { p->current_phase = phases + i; break; } return -6; } // read current phase completed if (file_read_line(r_buffer, BUFLEN, fp) == -1) return -7; // update the parameters struct p->current_phase->completed = atoi(r_buffer); fclose(fp); return 0; } /** * @brief Saves stats to file. Structure of the save file: - timestamp (year-month-day) - phase elapsed - total study elapsed - total study phases - current phase id - current phase completed - current phase started * * @param p pointer to parameters * @return int -1 in case of error, 0 in case of success */ int save_savefile(Parameters *p) { FILE *fp; char w_buffer[BUFLEN]; fp = fopen(SAVE_PATH, "w"); if (fp == NULL) return -1; // save timestamp format_date(w_buffer); fputs(w_buffer, fp); fputc('\n', fp); // save phase elapsed sprintf(w_buffer, "%i\n", p->phase_elapsed); fputs(w_buffer, fp); // save total study elapsed sprintf(w_buffer, "%i\n", p->study_elapsed); fputs(w_buffer, fp); // save total study phases sprintf(w_buffer, "%i\n", p->study_phases); fputs(w_buffer, fp); // save current phase id sprintf(w_buffer, "%i\n", p->current_phase->id); fputs(w_buffer, fp); // save current completed phases sprintf(w_buffer, "%i\n", p->current_phase->completed); fputs(w_buffer, fp); // save current phase started sprintf(w_buffer, "%li\n", p->current_phase->started); fputs(w_buffer, fp); fclose(fp); return 0; } /** * @brief Checks if settings file exists. * * @return int -1 if file does not exist, -2 if it's not valid, 0 if it's valid */ int check_settings() { FILE *fp; fp = fopen(SETTINGS_PATH, "r"); if (fp == NULL) return -1; // check if there are enough lines if (file_count_lines(fp) < 4) return -2; fclose(fp); return 0; } /** * @brief Loads settings from file. * * @param durations pointer to array to hold the lines * @return int -1 if file does not exist, -2 if it's not valid, 0 if it's valid */ int load_settings(int *durations) { FILE *fp; char r_buffer[BUFLEN]; fp = fopen(SETTINGS_PATH, "r"); if (fp == NULL) return -1; // check if there are enough lines if (file_count_lines(fp) < 4) return -2; // populate array with integers loaded from file for (int i = 0; i < 4; i++) { file_read_line(r_buffer, BUFLEN, fp); int val = atoi(r_buffer); if (val == 0) { // atoi returns 0 if the number is not valid // in that case, return return -3; } *(durations + i) = val; } fclose(fp); return 0; } /** * @brief Save settings to file. * * @param durations pointer to duration * @return int -1 if file is not writeable, 0 otherwise */ int save_settings(int *durations) { FILE *fp; char w_buffer[BUFLEN]; fp = fopen(SETTINGS_PATH, "w"); if (fp == NULL) return -1; // save study duration sprintf(w_buffer, "%i\n", *durations); fputs(w_buffer, fp); // save short break duration sprintf(w_buffer, "%i\n", *(durations + 1)); fputs(w_buffer, fp); // save long break duration sprintf(w_buffer, "%i\n", *(durations + 2)); fputs(w_buffer, fp); // save study sessions sprintf(w_buffer, "%i\n", *(durations + 3)); fputs(w_buffer, fp); fclose(fp); return 0; } /** * @brief Handler for CTRL+C. * */ void SIGINT_handler() { sigint_called = 1; return; } /** * @brief Handler for terminal resize. * */ void SIGWINCH_handler() { sigwinch_called = 1; return; } /** * @brief Returns time (milliseconds) since epoch * * @return unsigned long long */ unsigned long long epoch() { struct timeval tv; gettimeofday(&tv, NULL); unsigned long long ms_since_epoch = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000; return ms_since_epoch; } /** * @brief Sleeps a set amount of time (milliseconds). * * @param ms millisecond */ void ms_sleep(int ms) { // check if number of milli second is valid if (ms < 0) return; // pack a struct struct timespec ts; ts.tv_sec = ms / 1000; ts.tv_nsec = (ms % 1000) * 1000000; // actually sleep nanosleep(&ts, NULL); } /** * @brief Sleeps a set amount of time (seconds). * * @param s seconds */ void s_sleep(int s) { // check if number of second is valid if (s < 0) return; // sleep... ms_sleep(s * 1000); } /** * @brief Assigns all the variables needed to run the timer. * * @param phases pointer to phases array * @param argc * @param argv * @return Phase* current phase */ Phase *init_phases(Phase *phases, int argc, char *argv[]) { // preload durations to default values int durations[] = { STUDYDURATION, SHORTBREAKDURATION, LONGBREAKDURATION, STUDYSESSIONS, }; if (argc > 1) { // if arguments have been passed, load them if (strcmp(argv[1], "reset") != 0) { for (int i = 1; i < argc && i < 5; i++) { int val = atoi(argv[i]); if (val == 0 || val < 0) { // atoi does not check for validity, but returns 0 for invalid numbers // skip negative values aswell continue; } durations[i - 1] = val; } } } else if (check_settings() == 0) { // otherwise, just load from file load_settings(durations); } save_settings(durations); // create array of phases phases[0] = (Phase){ .name = "study", .id = 0, .duration = durations[0], .repetitions = durations[3], .completed = 0, .started = 0, .is_study = 1, .next = phases + 1, .next_after = phases + 2, .fg_color = fg_RED, .bg_color = bg_DEFAULT, }; phases[1] = (Phase){ .name = "short break", .id = 1, .duration = durations[1], .repetitions = 0, .completed = 0, .started = 0, .is_study = 0, .next = phases, .fg_color = fg_GREEN, .bg_color = bg_DEFAULT, }; phases[2] = (Phase){ .name = "long break", .id = 2, .duration = durations[2], .repetitions = 0, .completed = 0, .started = 0, .is_study = 0, .next = phases, .fg_color = fg_GREEN, .bg_color = bg_DEFAULT, }; phases->started = time(NULL); return phases; // returns current phase } /** * @brief Creates the windows container struct and returns its pointer. * * @return Windows* */ Windows *init_windows() { Window *w_phase, *w_total, *w_quote, *w_controls, *w_paused; Windows *w; // first, allocate space for the windows struct w = malloc(sizeof(Windows)); // now create all the windows // w_phase keeping track of current phase w_phase = createWindow(0, Y_BORDER); windowSetAlignment(w_phase, 0); windowSetPadding(w_phase, PADDING); windowSetFGcolor(w_phase, fg_RED); // w_phase keeping track of total time w_total = createWindow(0, 0); windowSetAlignment(w_total, 0); windowSetPadding(w_total, PADDING); windowSetFGcolor(w_total, fg_BRIGHT_YELLOW); // w_quote with... a quote w_quote = createWindow(0, Y_BORDER); windowSetAlignment(w_quote, 0); windowSetPadding(w_quote, PADDING); windowSetAutoWidth(w_quote, 0); windowSetFGcolor(w_quote, fg_BRIGHT_BLUE); windowSetTextStyle(w_quote, text_ITALIC); place_random_quote(w_quote); // window with info w_controls = createWindow(0, 0); windowSetAlignment(w_controls, 0); windowSetPadding(w_controls, PADDING); windowSetAutoWidth(w_controls, 0); windowSetFGcolor(w_controls, fg_BRIGHT_GREEN); windowAddLine(w_controls, "press S to skip, P to pause, Q to get and new quote, I to hide this window, CTRL+C to exit"); // window showing is timer is currently paused w_paused = createWindow(0, 0); windowSetAlignment(w_paused, 0); windowSetPadding(w_paused, PADDING); windowSetAutoWidth(w_paused, 0); windowSetAutoHeight(w_paused, 0); windowSetFGcolor(w_paused, fg_BRIGHT_RED); windowSetTextStyle(w_paused, text_BLINKING); windowSetVisibility(w_paused, 0); windowAddLine(w_paused, "WARNING, TIMER IS CURRENTLY PAUSED"); // assign the windows to the struct w->w_phase = w_phase; w->w_total = w_total; w->w_quote = w_quote; w->w_controls = w_controls; w->w_paused = w_paused; // return pointer to window return w; } /** * @brief Inits parameters. * * @param current_phase * @return Parameters* */ Parameters *init_parameters(Phase *current_phase, Windows *windows) { // allocate space for all parameters Parameters *p = malloc(sizeof(Parameters)); // create mutex p->terminal_lock = malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(p->terminal_lock, NULL); // create windows p->windows = windows; // create tone p->tone = malloc(sizeof(Tone)); p->tone->repetitions = 0; p->tone->speed = 0; // create return values p->return_values = malloc(sizeof(ReturnValues)); p->return_values->show_routine = 1; p->return_values->advance_routine = 1; p->return_values->save_routine = 1; p->return_values->keypress_routine = 1; // init all other parameters p->current_phase = current_phase; p->study_phases = 0; p->study_elapsed = 0; p->windows_force_reload = 1; p->phase_elapsed = 0; p->study_elapsed = 0; p->previous_elapsed = 0; p->time_paused = 1; p->frozen_elapsed = 0; return p; } /** * @brief Deletes parameters struct. * * @param p pointer to parameters struct */ void delete_parameters(Parameters *p) { // free memory and delete mutex pthread_mutex_destroy(p->terminal_lock); free(p->terminal_lock); // free memory and delete windows deleteWindow(p->windows->w_phase); deleteWindow(p->windows->w_total); deleteWindow(p->windows->w_quote); deleteWindow(p->windows->w_controls); deleteWindow(p->windows->w_paused); free(p->windows); // free memory from tone free(p->tone); // free memory from return values free(p->return_values); // free memory from parameters free(p); } /** * @brief Resets current phase time. * * @param p pointer to parameters struct */ void reset_current_time(Parameters *p) { p->current_phase->started = time(NULL); } /** * @brief Starts counting time. * * @param p pointer to parameters struct */ void start_time(Parameters *p) { p->time_paused = 0; } /** * @brief Pauses current phase. * * @param p pointer to parameters struct */ void pause_time(Parameters *p) { p->time_paused = 1; p->frozen_elapsed = (time(NULL) - p->current_phase->started); } /** * @brief Advances to next phase. * * @param p pointer to parameters struct */ void next_phase(Parameters *p) { pthread_t beep_thread; pthread_create(&beep_thread, NULL, beep_async, p); pthread_detach(beep_thread); // one phase has been completed p->current_phase->completed++; // shall the phase count toward the maximum? // yes if (p->current_phase->is_study) { p->study_phases++; // update the total time until now p->previous_elapsed += p->phase_elapsed; } // check if this phase must be repeated if (p->current_phase->completed >= p->current_phase->repetitions && p->current_phase->repetitions) { // repetitions have ended p->current_phase->completed = 0; p->current_phase = p->current_phase->next_after; } else { // no repetitions or repetitions already finished p->current_phase = p->current_phase->next; } reset_current_time(p); } /** * @brief Returns remaining time (seconds) in current phase * * @param p parameters pointer * @return int */ int phase_time_remaining(Parameters *p) { return p->current_phase->duration * 60 - (time(NULL) - p->current_phase->started); } /** * @brief Formats elapsed time. * * @param buffer pointer to buffer string * @param elapsed elapsed time in seconds */ void format_elapsed_time(char *buffer, int elapsed) { int seconds, minutes, hours; // unpack time into hours, minutes, seconds hours = elapsed / 3600; minutes = (elapsed % 3600) / 60; seconds = elapsed % 60; if (hours > 0) { // if hours is bigger than 0, save into final string sprintf(buffer, "%02d:%02d:%02d", hours, minutes, seconds); } else { // otherwise, just neglect it sprintf(buffer, "%02d:%02d", minutes, seconds); } return; } /** * @brief Formats tile difference (in seconds). * * @param pointer to buffer string * @param delta_seconds elapsed time in seconds */ void format_time_delta(char *buffer, int delta_seconds) { time_t now; struct tm tm; now = time(NULL) + (time_t)delta_seconds; tm = *localtime(&now); sprintf(buffer, "%02d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec); return; } /** * @brief Formats date (discarding time). * * @param pointer to buffer string */ void format_date(char *buffer) { time_t now; struct tm tm; now = time(NULL); tm = *localtime(&now); sprintf(buffer, "%d-%02d-%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); } /** * @brief Gets random quote and saves it into window. * * @param w pointer to window * @return int -1 if file is not readable, 0 in case of success */ int place_random_quote(Window *w) { char r_buffer[BUFLEN], l_buffer[BUFLEN]; int rindex, count; FILE *fp; count = 0; fp = fopen(QUOTES_PATH, "r"); if (fp == NULL) { // if the quotes file is somehow not found, // add a gimmick quote to panel windowAddLine(w, "God is dead and we killed him."); windowAddLine(w, "~Harambe"); return -1; } // reset quotes window windowDeleteAllLines(w); // calculate the number of lines const int quotes_num = file_count_lines(fp); rindex = random() % quotes_num; while (fgets(r_buffer, BUFLEN, fp) != NULL) { if (count == rindex) { int line_end; // remove newline and find end for (int i = 0; i < BUFLEN; i++) { if (r_buffer[i] == '\n') { line_end = i; break; } } // find author and remove it from string int author_start; for (int i = line_end; i >= 0; i--) { if (r_buffer[i] == '@') { author_start = i + 1; break; } } // copy quote to buffer for (int i = 0; i < author_start - 1; i++) l_buffer[i] = r_buffer[i]; l_buffer[author_start - 1] = '\0'; // copy quote into destination windowAddLine(w, l_buffer); // copy author to buffer for (int i = author_start; i < line_end; i++) { l_buffer[i - author_start] = r_buffer[i]; } l_buffer[line_end - author_start] = '\0'; // copy author into destination windowAddLine(w, l_buffer); break; } count++; } fclose(fp); return 0; } /* hides/shows all windows on screen */ /** * @brief Sets the windows visibility. * * @param p pointer to parameters * @param visibility 0 for invisible, 1 for visible */ void set_windows_visibility(Parameters *p, int visibility) { clear_terminal(); windowSetVisibility(p->windows->w_phase, visibility); windowSetVisibility(p->windows->w_total, visibility); windowSetVisibility(p->windows->w_quote, visibility); windowSetVisibility(p->windows->w_paused, visibility); } /** * @brief Async beeping. * * @param args * @return void* */ void *beep_async(void *args) { Parameters *p = args; const int delay = (1 - p->tone->speed / 10.0) * 700 + 300; for (int i = 0; i < p->tone->repetitions; i++) { pthread_mutex_lock(p->terminal_lock); terminal_beep(); pthread_mutex_unlock(p->terminal_lock); ms_sleep(delay); } pthread_exit(0); } /** * @brief Routine handling terminal output. * * @param args * @return void* */ void *show_routine(void *args) { Parameters *p = args; unsigned long long last_updated = 0; while (p->loop) { // update 4 times a second if (epoch() - last_updated > 250) { last_updated = epoch(); char buffer[BUFLEN]; char num_buffer[BUFLEN]; // remove old lines windowDeleteAllLines(p->windows->w_phase); windowDeleteAllLines(p->windows->w_total); // update windows color windowSetFGcolor(p->windows->w_phase, p->current_phase->fg_color); // first line of phase window if (p->current_phase->repetitions > 0) sprintf(buffer, "current phase: %s [%i/%i]", p->current_phase->name, p->current_phase->completed + 1, p->current_phase->repetitions); else sprintf(buffer, "current phase: %s", p->current_phase->name); windowAddLine(p->windows->w_phase, buffer); // second line of phase window sprintf(buffer, "phase duration: %i minutes", p->current_phase->duration); windowAddLine(p->windows->w_phase, buffer); // format time format_elapsed_time(num_buffer, p->phase_elapsed); // third line of phase window sprintf(buffer, "elapsed time: %s", num_buffer); windowAddLine(p->windows->w_phase, buffer); // first line of w_total sprintf(buffer, "total study sessions: %i", p->study_phases); windowAddLine(p->windows->w_total, buffer); // second line of w_total format_elapsed_time(num_buffer, p->study_elapsed); sprintf(buffer, "total time studied: %s", num_buffer); windowAddLine(p->windows->w_total, buffer); // third line of w_total int time_remaining = phase_time_remaining(p); format_time_delta(num_buffer, time_remaining); sprintf(buffer, "phase ending: %s", num_buffer); windowAddLine(p->windows->w_total, buffer); // wait for exclusive terminal use pthread_mutex_lock(p->terminal_lock); windowShow(p->windows->w_phase); windowShow(p->windows->w_total); pthread_mutex_unlock(p->terminal_lock); } if (p->windows_force_reload) { // get largest window int largest, terminal_width, dx; largest = windowGetSize(p->windows->w_phase).width + windowGetSize(p->windows->w_total).width + 1; // now get terminal width terminal_width = get_terminal_size().width; // now calculate displacement dx = (terminal_width - largest) / 2; // set position of w_phase windowSetPosition(p->windows->w_phase, dx, Y_BORDER); // set position of w_total windowSetPosition(p->windows->w_total, windowGetBottomRight(p->windows->w_phase).x + 1, Y_BORDER); windowAutoResize(p->windows->w_total); // trigger resize to get the actual width Position total_br_corner = windowGetBottomRight(p->windows->w_total); // set position of w_quote windowSetPosition(p->windows->w_quote, dx, total_br_corner.y); windowSetSize(p->windows->w_quote, total_br_corner.x - dx, 4); windowAutoResize(p->windows->w_quote); // trigger resize to get the actual width Position quotes_br_corner = windowGetBottomRight(p->windows->w_quote); // set position of w_controls windowSetPosition(p->windows->w_controls, dx, quotes_br_corner.y); windowSetWidth(p->windows->w_controls, total_br_corner.x - dx); windowAutoResize(p->windows->w_controls); // trigger resize to get the actual width // now set position of w_paused if (windowGetVisibility(p->windows->w_controls)) { // since info window is visible, get its position Position info_br_corner = windowGetBottomRight(p->windows->w_controls); windowSetPosition(p->windows->w_paused, dx, info_br_corner.y); } else { // otherwise, place below quotes windowSetPosition(p->windows->w_paused, dx, quotes_br_corner.y); } windowSetWidth(p->windows->w_paused, quotes_br_corner.x - dx); windowSetHeight(p->windows->w_paused, 3); windowSetVisibility(p->windows->w_paused, p->time_paused); // wait for exclusive use of terminal pthread_mutex_lock(p->terminal_lock); // clear terminal clear_terminal(); // display all windowShow(p->windows->w_phase); windowShow(p->windows->w_total); windowShow(p->windows->w_quote); windowShow(p->windows->w_controls); windowShow(p->windows->w_paused); // unlock terminal pthread_mutex_unlock(p->terminal_lock); // reset flag p->windows_force_reload = 0; } // idle ms_sleep(SLEEP_INTERVAL); } p->return_values->show_routine = 0; pthread_exit(0); } /** * @brief Routine handling time. * * @param args * @return void* */ void *advance_routine(void *args) { Parameters *p = args; while (p->loop) { if (p->time_paused) { // stall elapsed time p->current_phase->started = time(NULL) - p->frozen_elapsed; } else { int phase_elapsed; // calculate seconds elapsed phase_elapsed = time(NULL) - p->current_phase->started; // second line of w_total, total time spent studying int total_elapsed = 0; // add current session to total time if it's a study session if (p->current_phase->is_study) { total_elapsed = phase_elapsed; // next phase is a study phase, set tone accordingly p->tone->speed = 3; p->tone->repetitions = 3; } else { // the next phase is a pause, set tone accordingly p->tone->speed = 10; p->tone->repetitions = 5; } // update the parameters struct // time in the current phase p->phase_elapsed = phase_elapsed; // total time studied today, until this very moment p->study_elapsed = total_elapsed + p->previous_elapsed; if (phase_elapsed / 60 >= p->current_phase->duration) { // phase has been completed // go to next next_phase(p); // load a new quote place_random_quote(p->windows->w_quote); // force windows reload p->windows_force_reload = 1; } } ms_sleep(SLEEP_INTERVAL); } p->return_values->advance_routine = 0; pthread_exit(0); } /** * @brief Routing handling periodic saves. * * @param args * @return void* */ void *save_routine(void *args) { Parameters *p = args; unsigned long long last_save = 0; while (p->loop) { if (epoch() - last_save > SAVEINTERVAL) { save_savefile(p); last_save = epoch(); } ms_sleep(SLEEP_INTERVAL); } p->return_values->save_routine = 0; pthread_exit(0); } /** * @brief Routine handling keypresses. * * @param args * @return void* */ void *keypress_routine(void *args) { Parameters *p = args; while (p->loop) { if (sigint_called) { sigint_called = 0; // hide all windows // wait for exclusive use of terminal pthread_mutex_lock(p->terminal_lock); set_windows_visibility(p, 0); // unlock terminal pthread_mutex_unlock(p->terminal_lock); Dialog *d; int ret; d = createDialog(0, Y_BORDER); dialogSetPadding(d, 4); dialogSetText(d, "Exit pomodoro?", 1); dialogCenter(d, 1, 0); dialogShow(d); ret = dialogWaitResponse(d); dialogClear(d); deleteDialog(d); if (ret == 1) { p->loop = 0; } else { // show windows again // wait for exclusive use of terminal pthread_mutex_lock(p->terminal_lock); set_windows_visibility(p, 1); // unlock terminal pthread_mutex_unlock(p->terminal_lock); p->windows_force_reload = 1; } } else if (sigwinch_called) { // terminal has been resized sigwinch_called = 0; p->windows_force_reload = 1; } char key; // wait for exclusive use of terminal pthread_mutex_lock(p->terminal_lock); key = poll_keypress(); // unlock terminal pthread_mutex_unlock(p->terminal_lock); // transform to lower case if (key >= 65 && key <= 90) key += 32; if (key == 'p') { if (!p->time_paused) pause_time(p); else start_time(p); // force windows refresh p->windows_force_reload = 1; } else if (key == 's') { // hide all windows // wait for exclusive use of terminal pthread_mutex_lock(p->terminal_lock); set_windows_visibility(p, 0); // unlock terminal pthread_mutex_unlock(p->terminal_lock); // pause time so phases does not elapse // while dialog is shown pause_time(p); Dialog *d; int ret; d = createDialog(0, Y_BORDER); dialogSetPadding(d, 4); dialogSetText(d, "Do you want to skip the current session?", 1); dialogCenter(d, 1, 0); dialogShow(d); ret = dialogWaitResponse(d); dialogClear(d); deleteDialog(d); if (ret) { // load stats from file next_phase(p); } // show windows again // wait for exclusive use of terminal pthread_mutex_lock(p->terminal_lock); clear_terminal(); set_windows_visibility(p, 1); // unlock terminal pthread_mutex_unlock(p->terminal_lock); // restart time start_time(p); // update flags p->windows_force_reload = 1; // reset tone p->tone->repetitions = 1; } else if (key == 'q') { // make a new quote place_random_quote(p->windows->w_quote); p->windows_force_reload = 1; } else if (key == 'i') { // show/hide visibility of commands panel windowToggleVisibility(p->windows->w_controls); p->windows_force_reload = 1; } ms_sleep(SLEEP_INTERVAL); } p->return_values->keypress_routine = 0; pthread_exit(0); } /** * @brief Checks if routine have ended * * @param p pointer to parameters * @return int */ int check_routines(Parameters *p) { //* this is quite ugly return p->return_values->show_routine || p->return_values->advance_routine || p->return_values->save_routine || p->return_values->keypress_routine; } int main(int argc, char *argv[]) { // init random seed srand(time(NULL)); // set raw mode enter_raw_mode(); // declare variables pthread_t show_thread, advance_thread, save_thread, keypress_thread; Phase phases[3], *current_phase; Windows *windows; Parameters *p; // init phases, provide argv and argc to handle command line parsing current_phase = init_phases(phases, argc, argv); // init windows windows = init_windows(); // pack the parameters p = init_parameters(current_phase, windows); // prepare terminal clear_terminal(); hide_cursor(); // check if a previous file session is available if (check_savefile() == 1) { Dialog *d; int ret; d = createDialog(0, Y_BORDER); dialogSetPadding(d, 4); dialogSetText(d, "Previous session found. Continue?", 1); dialogCenter(d, 1, 0); dialogShow(d); ret = dialogWaitResponse(d); dialogClear(d); deleteDialog(d); // load stats from file if (ret) load_savefile(p, phases); } // handle signal interrupt signal(SIGINT, SIGINT_handler); // handle terminal resize signal(SIGWINCH, SIGWINCH_handler); // setup callback flags sigint_called = 0; sigwinch_called = 0; //start the loop p->loop = 1; // spawn threads pthread_create(&show_thread, NULL, show_routine, (void *)p); pthread_create(&advance_thread, NULL, advance_routine, (void *)p); pthread_create(&save_thread, NULL, save_routine, (void *)p); pthread_create(&keypress_thread, NULL, keypress_routine, (void *)p); reset_current_time(p); start_time(p); // Main thread IDLE while (check_routines(p)) { ms_sleep(SLEEP_INTERVAL); } // clean up delete_parameters(p); // reset all terminal exit_raw_mode(); reset_styles(); clear_terminal(); show_cursor(); move_cursor_to(0, 0); return 0; }
23.233571
149
0.640483
[ "transform" ]
532d9fe74b140a1adcbd7719ccfbb7dc59111589
6,929
h
C
src/Weather/nt_clear.h
MHotchin/RLEBitmap
ebea6f7f032c235ff2301e2aced1e6180b71882e
[ "MIT" ]
8
2020-07-05T17:00:15.000Z
2022-02-08T04:34:50.000Z
src/Weather/nt_clear.h
Bodmer/RLEBitmap
ed2bf7ec6497371415878a7a5a07b7938294aad6
[ "MIT" ]
2
2020-07-04T21:11:49.000Z
2020-08-11T20:23:06.000Z
src/Weather/nt_clear.h
Bodmer/RLEBitmap
ed2bf7ec6497371415878a7a5a07b7938294aad6
[ "MIT" ]
3
2020-07-05T17:00:22.000Z
2020-11-03T11:18:34.000Z
// // This file is AUTOMATICALLY GENERATED, and should not be edited unless you are certain // that it will not be re-generated anytime in the future. As generated code, the // copyright owner(s) of the generating program do NOT claim any copyright on the code // generated. // // Run Length Encoded (RLE) bitmaps. Each run is encoded as either one or two bytes, // with NO PADDING. Thus, the data for each line of the bitmap is VARIABLE LENGTH, and // there is no way of determining where any line other than the first starts without // walking though the data. // // Note that one byte encoding ONLY occurs if the total number of colors is 16 or less, // and in that case the 'flags' member of the 'RLEBitmapInfo' will have the first bit // (0x01) set. // // In that case, if the high 4 bits of the first byte are ZERO, then this is a 2 byte // run. The first byte is the index of the color in the color palette, and the second // byte is the length. // // Else, the lower 4 bits are the color index, and the upper 4 bits are the run length. // // If the 'flags' member first bit is zero, then ALL runs are 2 byte runs. The first // byte is the palette index, and the second is the run length. // // In order to save PROGMEM for other uses, the bitmap data is placed in a section that // occurs near the END of the used FLASH. So, this data should only be accessed using // the 'far' versions of the progmem functions - the usual versions are limited to the // first 64K of FLASH. // // Data is from file 'nt_clear.bmp'. // const byte nt_clear_RLEBM_data[] PROGMEM_LATE = { 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x38, 0x81, 0x00, 0x40, 0x00, 0x34, 0xc1, 0x00, 0x40, 0x00, 0x31, 0xf1, 0x00, 0x40, 0x00, 0x2e, 0x01, 0x12, 0x00, 0x40, 0x00, 0x2c, 0x01, 0x13, 0x00, 0x41, 0x00, 0x2b, 0x01, 0x14, 0x00, 0x41, 0x00, 0x29, 0x01, 0x16, 0x00, 0x41, 0x00, 0x27, 0x01, 0x18, 0x00, 0x41, 0x00, 0x26, 0x01, 0x10, 0x10, 0x71, 0x00, 0x42, 0x00, 0x25, 0xe1, 0x40, 0x71, 0x00, 0x42, 0x00, 0x24, 0xd1, 0x60, 0x71, 0x00, 0x42, 0x00, 0x23, 0xc1, 0x80, 0x71, 0x00, 0x42, 0x00, 0x22, 0xc1, 0x90, 0x71, 0x00, 0x42, 0x00, 0x21, 0xb1, 0xb0, 0x71, 0x00, 0x42, 0x00, 0x20, 0xb1, 0xc0, 0x71, 0x00, 0x42, 0x00, 0x1f, 0xb1, 0xd0, 0x71, 0x00, 0x42, 0x00, 0x1e, 0xb1, 0xe0, 0x71, 0x00, 0x42, 0x00, 0x1e, 0xa1, 0xf0, 0x71, 0x00, 0x42, 0x00, 0x1d, 0xa1, 0x00, 0x10, 0x71, 0x00, 0x42, 0x00, 0x1c, 0xa1, 0x00, 0x11, 0x71, 0x00, 0x42, 0x00, 0x1c, 0x91, 0x00, 0x12, 0x71, 0x00, 0x42, 0x00, 0x1b, 0x91, 0x00, 0x13, 0x81, 0x00, 0x41, 0x00, 0x1b, 0x91, 0x00, 0x14, 0x71, 0x00, 0x41, 0x00, 0x1a, 0x91, 0x00, 0x15, 0x71, 0x00, 0x41, 0x00, 0x1a, 0x81, 0x00, 0x16, 0x81, 0x00, 0x40, 0x00, 0x19, 0x91, 0x00, 0x16, 0x81, 0x00, 0x40, 0x00, 0x19, 0x81, 0x00, 0x18, 0x71, 0x00, 0x40, 0x00, 0x18, 0x91, 0x00, 0x18, 0x81, 0x00, 0x3f, 0x00, 0x18, 0x81, 0x00, 0x19, 0x81, 0x00, 0x3f, 0x00, 0x18, 0x81, 0x00, 0x1a, 0x81, 0x00, 0x3e, 0x00, 0x17, 0x91, 0x00, 0x1a, 0x81, 0x00, 0x3e, 0x00, 0x17, 0x81, 0x00, 0x1b, 0x91, 0x00, 0x3d, 0x00, 0x17, 0x81, 0x00, 0x1c, 0x91, 0x00, 0x3c, 0x00, 0x17, 0x81, 0x00, 0x1d, 0x91, 0x00, 0x3b, 0x00, 0x17, 0x71, 0x00, 0x1e, 0xa1, 0x00, 0x3a, 0x00, 0x16, 0x81, 0x00, 0x1f, 0xa1, 0x00, 0x39, 0x00, 0x16, 0x81, 0x00, 0x1f, 0xb1, 0x00, 0x38, 0x00, 0x16, 0x81, 0x00, 0x20, 0xb1, 0x00, 0x37, 0x00, 0x16, 0x81, 0x00, 0x21, 0xb1, 0x00, 0x36, 0x00, 0x16, 0x81, 0x00, 0x22, 0xb1, 0x00, 0x35, 0x00, 0x16, 0x81, 0x00, 0x22, 0xd1, 0x00, 0x33, 0x00, 0x16, 0x81, 0x00, 0x23, 0xd1, 0x00, 0x32, 0x00, 0x16, 0x81, 0x00, 0x24, 0xe1, 0x00, 0x30, 0x00, 0x16, 0x81, 0x00, 0x25, 0xf1, 0x00, 0x2e, 0x00, 0x16, 0x81, 0x00, 0x26, 0x01, 0x11, 0x00, 0x2b, 0x00, 0x16, 0x81, 0x00, 0x27, 0x01, 0x12, 0x00, 0x29, 0x00, 0x16, 0x81, 0x00, 0x28, 0x01, 0x15, 0x00, 0x25, 0x00, 0x16, 0x81, 0x00, 0x2a, 0x01, 0x19, 0x00, 0x1f, 0x00, 0x16, 0x81, 0x00, 0x2b, 0x01, 0x21, 0x00, 0x16, 0x00, 0x17, 0x71, 0x00, 0x2d, 0x01, 0x1f, 0x00, 0x16, 0x00, 0x17, 0x81, 0x00, 0x2e, 0x01, 0x1d, 0x00, 0x16, 0x00, 0x17, 0x81, 0x00, 0x30, 0x01, 0x1b, 0x00, 0x16, 0x00, 0x17, 0x81, 0x00, 0x32, 0x01, 0x18, 0x00, 0x17, 0x00, 0x17, 0x91, 0x00, 0x34, 0x01, 0x15, 0x00, 0x17, 0x00, 0x18, 0x81, 0x00, 0x37, 0x01, 0x12, 0x00, 0x17, 0x00, 0x18, 0x81, 0x00, 0x3b, 0xd1, 0x00, 0x18, 0x00, 0x18, 0x91, 0x00, 0x3f, 0x81, 0x00, 0x18, 0x00, 0x19, 0x81, 0x00, 0x3e, 0x91, 0x00, 0x18, 0x00, 0x19, 0x91, 0x00, 0x3d, 0x81, 0x00, 0x19, 0x00, 0x1a, 0x81, 0x00, 0x3c, 0x91, 0x00, 0x19, 0x00, 0x1a, 0x91, 0x00, 0x3b, 0x81, 0x00, 0x1a, 0x00, 0x1b, 0x91, 0x00, 0x39, 0x91, 0x00, 0x1a, 0x00, 0x1b, 0x91, 0x00, 0x38, 0x91, 0x00, 0x1b, 0x00, 0x1c, 0x91, 0x00, 0x36, 0xa1, 0x00, 0x1b, 0x00, 0x1c, 0xa1, 0x00, 0x35, 0x91, 0x00, 0x1c, 0x00, 0x1d, 0xa1, 0x00, 0x33, 0xa1, 0x00, 0x1c, 0x00, 0x1e, 0xa1, 0x00, 0x31, 0xa1, 0x00, 0x1d, 0x00, 0x1e, 0xb1, 0x00, 0x2f, 0xa1, 0x00, 0x1e, 0x00, 0x1f, 0xb1, 0x00, 0x2d, 0xa1, 0x00, 0x1f, 0x00, 0x20, 0xb1, 0x00, 0x2b, 0xb1, 0x00, 0x1f, 0x00, 0x21, 0xb1, 0x00, 0x29, 0xb1, 0x00, 0x20, 0x00, 0x22, 0xc1, 0x00, 0x25, 0xc1, 0x00, 0x21, 0x00, 0x23, 0xd1, 0x00, 0x22, 0xc1, 0x00, 0x22, 0x00, 0x24, 0xe1, 0x00, 0x1e, 0xd1, 0x00, 0x23, 0x00, 0x25, 0xf1, 0x00, 0x19, 0xf1, 0x00, 0x24, 0x00, 0x26, 0x01, 0x10, 0x00, 0x15, 0xf1, 0x00, 0x26, 0x00, 0x28, 0x01, 0x13, 0xb0, 0x01, 0x13, 0x00, 0x27, 0x00, 0x29, 0x01, 0x2e, 0x00, 0x29, 0x00, 0x2b, 0x01, 0x2b, 0x00, 0x2a, 0x00, 0x2c, 0x01, 0x28, 0x00, 0x2c, 0x00, 0x2f, 0x01, 0x23, 0x00, 0x2e, 0x00, 0x31, 0x01, 0x1f, 0x00, 0x30, 0x00, 0x34, 0x01, 0x19, 0x00, 0x33, 0x00, 0x38, 0x01, 0x11, 0x00, 0x37, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, }; // 128x128 Bitmap (16384 pixels) in 731 bytes const uint16_t nt_clear_RLEBM_palette[] PROGMEM_LATE = { // Palette has 2 entries 0x0000, 0x75ba, }; // Some platforms don't fully implement the pgmspace.h interface. Assume ordinary // addresses will do. #if not defined pgm_get_far_address #define pgm_get_far_address(x) ((uint32_t)(&(x))) #endif // Returns the info needed to render the bitmap. inline void get_nt_clear_RLEBM( RLEBitmapInfo &bmInfo) { bmInfo.pRLEBM_data_far = pgm_get_far_address(nt_clear_RLEBM_data); bmInfo.pRLEBM_palette_far = pgm_get_far_address(nt_clear_RLEBM_palette); bmInfo.width = 128; bmInfo.height = 128; bmInfo.flags = 0x01; }
36.277487
89
0.662722
[ "render" ]
532fe263a1aea5c52a03573e693f52bfd8a0224d
4,966
h
C
defender_base.h
xmil9/towers
06c9c07c1ec6cb5f3493c1de0ffa8930b6add5f6
[ "MIT" ]
null
null
null
defender_base.h
xmil9/towers
06c9c07c1ec6cb5f3493c1de0ffa8930b6add5f6
[ "MIT" ]
null
null
null
defender_base.h
xmil9/towers
06c9c07c1ec6cb5f3493c1de0ffa8930b6add5f6
[ "MIT" ]
null
null
null
// // Dec-2020, Michael Lindner // MIT license // #pragma once #include "attacker.h" #include "defender_look.h" #include "map_coord_sys.h" #include "path.h" #include "target_scan.h" #include "spiel/renderer2.h" #include "essentutils/fputil.h" #include "glm/glm.hpp" #include "glm/gtx/vector_angle.hpp" #include <cstddef> #include <limits> #include <optional> #include <unordered_map> /////////////////// template <typename Derived> class DefenderBase { public: struct Attribs { sp::MapCoord range = 0.f; int damage = 0; int cost = 0; }; public: DefenderBase(EntityId id, DefenderLook look, sp::MapDim size, sp::MapPos center, const MapCoordSys* cs, AttackerMap* attackers); EntityId id() const { return m_id; } int cost() const { return baseAttribs().cost; } sp::MapCoord range() const { return baseAttribs().range; } sp::MapPos center() const { return m_center; } void render(sp::Renderer2& renderer, bool isPaused); void update(); void removeAsTarget(EntityId attackerId); bool isInRange(const Attacker& attacker) const; bool isInRange(sp::MapCoord dist) const; protected: Attacker& target(); const Attacker& target() const; private: void setPosition(sp::MapPos center); void setSize(sp::MapVec size); bool findTarget(); bool canHit(const Attacker& attacker) const; void calcRotation(); std::optional<sp::MapVec> targetDirection() const; Derived& derived() { return static_cast<Derived&>(*this); } const Derived& derived() const { return static_cast<const Derived&>(*this); } const Attribs& baseAttribs() const { return derived().m_attribs; } protected: EntityId m_id = 0; DefenderLook m_look; sp::MapPos m_center; const MapCoordSys* m_coordSys; AttackerMap* m_attackers = nullptr; ClosestTargetScan<Derived> m_targetScan; std::optional<EntityId> m_target; }; template <typename Derived> DefenderBase<Derived>::DefenderBase(EntityId id, DefenderLook look, sp::MapDim size, sp::MapPos center, const MapCoordSys* cs, AttackerMap* attackers) : m_id{id}, m_look{std::move(look)}, m_center{center}, m_coordSys{cs}, m_attackers{attackers}, m_targetScan{attackers} { assert(m_coordSys); assert(m_attackers); setSize(m_coordSys->scaleInto(m_coordSys->toMap(m_look.size()), size)); setPosition(center); } template <typename Derived> void DefenderBase<Derived>::render(sp::Renderer2& renderer, bool isPaused) { const sp::PixPos center = m_coordSys->toPix(m_center); if (m_target && target().isAlive()) { calcRotation(); m_look.renderFiring(renderer, center, isPaused); } else { m_look.render(renderer, center); } } template <typename Derived> Attacker& DefenderBase<Derived>::target() { assert(m_target.has_value()); return (*m_attackers)[*m_target]; } template <typename Derived> const Attacker& DefenderBase<Derived>::target() const { assert(m_target.has_value()); return (*m_attackers)[*m_target]; } template <typename Derived> void DefenderBase<Derived>::update() { if (findTarget()) derived().shoot(); } template <typename Derived> void DefenderBase<Derived>::removeAsTarget(EntityId attackerId) { if (m_target && target().id() == attackerId) m_target = std::nullopt; } template <typename Derived> void DefenderBase<Derived>::setPosition(sp::MapPos center) { m_center = center; } template <typename Derived> void DefenderBase<Derived>::setSize(sp::MapVec size) { m_look.setSize(m_coordSys->toPix(size)); } template <typename Derived> bool DefenderBase<Derived>::findTarget() { // Try to keep existing target. if (m_target && canHit(target())) return true; // Find new target. m_target = m_targetScan.scan(derived()); return m_target.has_value(); } template <typename Derived> bool DefenderBase<Derived>::canHit(const Attacker& attacker) const { return attacker.isAlive() && isInRange(attacker); } template <typename Derived> bool DefenderBase<Derived>::isInRange(const Attacker& attacker) const { const auto pos = attacker.position(); if (pos) return isInRange(glm::length(m_center - *pos)); return false; } template <typename Derived> bool DefenderBase<Derived>::isInRange(sp::MapCoord dist) const { return esl::lessEqual(dist, baseAttribs().range); } template <typename Derived> void DefenderBase<Derived>::calcRotation() { const auto targetDir = targetDirection(); if (!targetDir) return; const sp::Angle rot{-glm::orientedAngle(glm::normalize(*targetDir), sp::Up)}; m_look.setRotation(rot); } template <typename Derived> std::optional<sp::MapVec> DefenderBase<Derived>::targetDirection() const { if (!m_target) return std::nullopt; const auto targetPos = target().position(); if (!targetPos) return std::nullopt; return *targetPos - m_center; }
24.106796
86
0.68828
[ "render" ]
5331f17e7b90aebbb2ba011cb627e7360c7c3f04
205
h
C
Nodo.h
PaulinaEEF/P3Examen2_PaulinaEuceda
6d62285c08606563065748837ba90ba96716c166
[ "MIT" ]
null
null
null
Nodo.h
PaulinaEEF/P3Examen2_PaulinaEuceda
6d62285c08606563065748837ba90ba96716c166
[ "MIT" ]
null
null
null
Nodo.h
PaulinaEEF/P3Examen2_PaulinaEuceda
6d62285c08606563065748837ba90ba96716c166
[ "MIT" ]
null
null
null
#ifndef NODO_H #define NODO_H #include "Object.h" class Nodo { public: Nodo(Object*); Nodo* getNext(); void setNext(Nodo*); ~Nodo(); private: Nodo* nextNode; Object* data; }; #endif
9.761905
22
0.619512
[ "object" ]
533567c3dacb4df17c65b7ad4013a3d344783efc
641
h
C
tests/CompileTests/PythonExample_tests/pythonDir/moduleobject.h
maurizioabba/rose
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
[ "BSD-3-Clause" ]
488
2015-01-09T08:54:48.000Z
2022-03-30T07:15:46.000Z
tests/CompileTests/PythonExample_tests/pythonDir/moduleobject.h
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
174
2015-01-28T18:41:32.000Z
2022-03-31T16:51:05.000Z
tests/CompileTests/PythonExample_tests/pythonDir/moduleobject.h
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
146
2015-04-27T02:48:34.000Z
2022-03-04T07:32:53.000Z
/* Module object interface */ #ifndef Py_MODULEOBJECT_H #define Py_MODULEOBJECT_H #ifdef __cplusplus extern "C" { #endif extern DL_IMPORT(PyTypeObject) PyModule_Type; #define PyModule_Check(op) PyObject_TypeCheck(op, &PyModule_Type) #define PyModule_CheckExact(op) ((op)->ob_type == &PyModule_Type) extern DL_IMPORT(PyObject *) PyModule_New(char *); extern DL_IMPORT(PyObject *) PyModule_GetDict(PyObject *); extern DL_IMPORT(char *) PyModule_GetName(PyObject *); extern DL_IMPORT(char *) PyModule_GetFilename(PyObject *); extern DL_IMPORT(void) _PyModule_Clear(PyObject *); #ifdef __cplusplus } #endif #endif /* !Py_MODULEOBJECT_H */
25.64
65
0.780031
[ "object" ]
533746c0f78a55afa0e9e3a8677b08d37fb05a64
4,218
h
C
code/src/view/NetView.h
yyh-saa/Visualized-Neural-Networks
d7ddf08dacc047f8b9370ad4f948a25455ef7703
[ "MIT" ]
null
null
null
code/src/view/NetView.h
yyh-saa/Visualized-Neural-Networks
d7ddf08dacc047f8b9370ad4f948a25455ef7703
[ "MIT" ]
1
2020-07-10T07:21:22.000Z
2020-07-10T07:21:22.000Z
code/src/view/NetView.h
yyh-saa/Visualized-Neural-Networks
d7ddf08dacc047f8b9370ad4f948a25455ef7703
[ "MIT" ]
null
null
null
#pragma once #ifndef NETVIEW_H #define NETVIEW_H #include <memory> #include <QtWidgets/QMainWindow> #include <QtWidgets/QTextEdit> #include <QVector> #include <QPair> #include <QGraphicsItem> #include "../viewmodel/NetViewModel.h" #include "../common/Common.h" #include "NeuronView.h" #include "WeightView.h" #include "ConfigView.h" enum EditMode { selectNeuron, addNeuron, addWeight }; enum DragMode { noDrag, preDrag, canDrag, isDrag, lineDrag }; QT_BEGIN_NAMESPACE namespace Ui { class NetView; } QT_END_NAMESPACE class NetView : public QMainWindow { Q_OBJECT public: explicit NetView(QWidget* parent = nullptr); ~NetView(); //BIND COMMANDS void set_add_neuron_command(Command&&); void set_connect_command(Command&&); // commit: addweights void set_change_neuron_command(Command&&); // commit: addvalue void set_change_weight_command(Command&&); // commit: addvalue void set_calculate_forward_command(Command&&); // commit: addcalcforward void set_calculate_gradient_command(Command&&); void set_propagate_gradient_command(Command&&); void set_update_weights_command(Command&&); void set_backprop_command(Command&&); void set_delete_weight_command(Command&&); void set_delete_neuron_command(Command&&); void set_change_learning_rate_command(Command&&); void set_change_loss_command(Command&&); void set_demand_config_command(Command&&); //ATTACH DATA AND MODELS void set_FNN(std::shared_ptr<Graph>); void attach_ViewModel(std::shared_ptr<NetViewModel> refModel) noexcept; std::shared_ptr <NetViewModel > detach_ViewModel() noexcept; //retrun NOTIFICATION(IMPLEMENTED BY VIEW) Notification tell_update_view_notification(); Notification tell_property_change_notification(); private slots: void select_button_clicked(); void neuron_button_clicked(); void sigmoid_button_clicked(); void relu_button_clicked(); void tanh_button_clicked(); void target_button_clicked(); void calc_forward_clicked(); // commit: addcalcforward void calc_gradient_clicked(); void prop_gradient_clicked(); void update_weights_clicked(); void backprop_clicked(); void delete_button_clicked(); void change_neuron_value(QPair<int, double>); void change_weight_value(QPair<int, double>); void change_learning_rate(double); void change_loss(QString); void enter_config(); void change_config(QPair<double, QString>); void exit_clicked(); void iterate_clicked(); private: /*Ui::View *ui;*/ //MODELS AND DATA BIND std::shared_ptr<Graph> FNN; std::shared_ptr<NetViewModel> m_NetVM; //COMMANDS Command add_neuron_command; Command connect_command; // commit: addweights Command change_neuron_command; // commit: addvalue Command change_weight_command; // commit: addvalue Command calculate_forward_command; // commit: addcalcforward Command calculate_gradient_command; Command propagate_gradient_command; Command update_weights_command; Command backprop_command; Command delete_weight_command; Command delete_neuron_command; Command change_learning_rate_command; Command change_loss_command; Command demand_config_command; // edit state EditMode edit_mode; DragMode drag_mode; Neuron current_neuron; // QVector<bool> selected_neurons; int selected_neuron; int selected_weight; // shape of the Graph QVector<QRectF> shape_neurons; QVector<int> neuron_ids; QRectF shape_current_neuron; QVector<QPair<int, int> > topology_weights; QVector<QLineF> shape_weights; QVector<int> weight_ids; QLineF shape_current_weight; // display modules Ui::NetView *ui; NeuronView *neuronView; WeightView *weightView; ConfigView *configView; // internal functions; void paintNeurons(QPainter*); void paintWeights(QPainter*); void check_FNN(); void check_FNN_neurons(); void check_FNN_weights(); protected: void mousePressEvent(QMouseEvent*); void mouseReleaseEvent(QMouseEvent*); void mouseDoubleClickEvent(QMouseEvent*); void mouseMoveEvent(QMouseEvent*); void paintEvent(QPaintEvent*); }; #endif // !VIEW_H
26.528302
77
0.74348
[ "shape" ]
5352c37ba38c41d8efbea18e58851c168402687d
117,071
h
C
src/transwarp.h
ulricheck/transwarp
b1dd863d61d63067d2edd82f87cc1b85c7b4c7ea
[ "MIT" ]
4
2020-07-11T09:49:09.000Z
2021-10-14T18:54:53.000Z
src/transwarp.h
ulricheck/transwarp
b1dd863d61d63067d2edd82f87cc1b85c7b4c7ea
[ "MIT" ]
1
2021-10-10T14:21:06.000Z
2021-11-06T13:01:18.000Z
external/transwarp.h
alok123t/HyINDEL
39cb5a32f08c9c3054f9b7237cb39baab7172d82
[ "MIT" ]
null
null
null
/// @mainpage transwarp is a header-only C++ library for task concurrency /// @details https://github.com/bloomen/transwarp /// @version 1.8.0 /// @author Christian Blume, Guan Wang /// @date 2018 /// @copyright MIT http://www.opensource.org/licenses/mit-license.php #pragma once #include <algorithm> #include <atomic> #include <chrono> #include <cstddef> #include <functional> #include <future> #include <memory> #include <mutex> #include <queue> #include <stdexcept> #include <string> #include <thread> #include <tuple> #include <type_traits> #include <unordered_map> #include <vector> /// The transwarp namespace namespace transwarp { /// The possible task types enum class task_type { root, ///< The task has no parents accept, ///< The task's functor accepts all parent futures accept_any, ///< The task's functor accepts the first parent future that becomes ready consume, ///< The task's functor consumes all parent results consume_any, ///< The task's functor consumes the first parent result that becomes ready wait, ///< The task's functor takes no arguments but waits for all parents to finish wait_any, ///< The task's functor takes no arguments but waits for the first parent to finish }; /// Base class for exceptions class transwarp_error : public std::runtime_error { public: explicit transwarp_error(const std::string& message) : std::runtime_error(message) {} }; /// Exception thrown when a task is canceled class task_canceled : public transwarp::transwarp_error { public: explicit task_canceled(const std::string& node_repr) : transwarp::transwarp_error("Task canceled: " + node_repr) {} }; /// Exception thrown when a task was destroyed prematurely class task_destroyed : public transwarp::transwarp_error { public: explicit task_destroyed(const std::string& node_repr) : transwarp::transwarp_error("Task destroyed: " + node_repr) {} }; /// Exception thrown when an invalid parameter was passed to a function class invalid_parameter : public transwarp::transwarp_error { public: explicit invalid_parameter(const std::string& parameter) : transwarp::transwarp_error("Invalid parameter: " + parameter) {} }; /// Exception thrown when a task is used in unintended ways class control_error : public transwarp::transwarp_error { public: explicit control_error(const std::string& message) : transwarp::transwarp_error("Control error: " + message) {} }; /// String conversion for the task_type enumeration inline std::string to_string(const transwarp::task_type& type) { switch (type) { case transwarp::task_type::root: return "root"; case transwarp::task_type::accept: return "accept"; case transwarp::task_type::accept_any: return "accept_any"; case transwarp::task_type::consume: return "consume"; case transwarp::task_type::consume_any: return "consume_any"; case transwarp::task_type::wait: return "wait"; case transwarp::task_type::wait_any: return "wait_any"; default: throw transwarp::invalid_parameter("task type"); } } /// The root type. Used for tag dispatch struct root_type : std::integral_constant<transwarp::task_type, transwarp::task_type::root> {}; constexpr transwarp::root_type root{}; ///< The root task tag /// The accept type. Used for tag dispatch struct accept_type : std::integral_constant<transwarp::task_type, transwarp::task_type::accept> {}; constexpr transwarp::accept_type accept{}; ///< The accept task tag /// The accept_any type. Used for tag dispatch struct accept_any_type : std::integral_constant<transwarp::task_type, transwarp::task_type::accept_any> {}; constexpr transwarp::accept_any_type accept_any{}; ///< The accept_any task tag /// The consume type. Used for tag dispatch struct consume_type : std::integral_constant<transwarp::task_type, transwarp::task_type::consume> {}; constexpr transwarp::consume_type consume{}; ///< The consume task tag /// The consume_any type. Used for tag dispatch struct consume_any_type : std::integral_constant<transwarp::task_type, transwarp::task_type::consume_any> {}; constexpr transwarp::consume_any_type consume_any{}; ///< The consume_any task tag /// The wait type. Used for tag dispatch struct wait_type : std::integral_constant<transwarp::task_type, transwarp::task_type::wait> {}; constexpr transwarp::wait_type wait{}; ///< The wait task tag /// The wait_any type. Used for tag dispatch struct wait_any_type : std::integral_constant<transwarp::task_type, transwarp::task_type::wait_any> {}; constexpr transwarp::wait_any_type wait_any{}; ///< The wait_any task tag /// Detail namespace for internal functionality only namespace detail { struct visit_depth_visitor; struct unvisit_visitor; struct final_visitor; struct schedule_visitor; struct node_manip; template<bool> struct assign_node_if_impl; } // detail /// A node carrying meta-data of a task class node { public: node() = default; // delete copy/move semantics node(const node&) = delete; node& operator=(const node&) = delete; node(node&&) = delete; node& operator=(node&&) = delete; /// The task ID std::size_t get_id() const noexcept { return id_; } /// The task level std::size_t get_level() const noexcept { return level_; } /// The task type transwarp::task_type get_type() const noexcept { return type_; } /// The optional task name (may be null) const std::shared_ptr<std::string>& get_name() const noexcept { return name_; } /// The optional, task-specific executor (may be null) const std::shared_ptr<std::string>& get_executor() const noexcept { return executor_; } /// The task's parents (may be empty) const std::vector<std::shared_ptr<node>>& get_parents() const noexcept { return parents_; } /// The task priority (defaults to 0) std::size_t get_priority() const noexcept { return priority_; } /// The custom task data (may be null) const std::shared_ptr<void>& get_custom_data() const noexcept { return custom_data_; } /// Returns whether the associated task is canceled bool is_canceled() const noexcept { return canceled_.load(); } /// Returns the average waittime in microseconds (-1 if never set) std::int64_t get_avg_waittime_us() const noexcept { return avg_waittime_us_.load(); } /// Returns the average runtime in microseconds (-1 if never set) std::int64_t get_avg_runtime_us() const noexcept { return avg_runtime_us_.load(); } private: friend struct transwarp::detail::node_manip; std::size_t id_ = 0; std::size_t level_ = 0; transwarp::task_type type_ = transwarp::task_type::root; std::shared_ptr<std::string> name_; std::shared_ptr<std::string> executor_; std::vector<std::shared_ptr<node>> parents_; std::size_t priority_ = 0; std::shared_ptr<void> custom_data_; std::atomic<bool> canceled_{false}; std::atomic<std::int64_t> avg_waittime_us_{-1}; std::atomic<std::int64_t> avg_runtime_us_{-1}; }; /// String conversion for the node class inline std::string to_string(const transwarp::node& node, const std::string& separator="\n") { std::string s; s += '"'; const std::shared_ptr<std::string>& name = node.get_name(); if (name) { s += "<" + *name + ">" + separator; } s += transwarp::to_string(node.get_type()); s += " id=" + std::to_string(node.get_id()); s += " lev=" + std::to_string(node.get_level()); const std::shared_ptr<std::string>& exec = node.get_executor(); if (exec) { s += separator + "<" + *exec + ">"; } const std::int64_t avg_waittime_us = node.get_avg_waittime_us(); if (avg_waittime_us >= 0) { s += separator + "avg-waittime-us=" + std::to_string(avg_waittime_us); } const std::int64_t avg_runtime_us = node.get_avg_runtime_us(); if (avg_runtime_us >= 0) { s += separator + "avg-runtime-us=" + std::to_string(avg_runtime_us); } s += '"'; return s; } /// An edge between two nodes class edge { public: edge(std::shared_ptr<transwarp::node> parent, std::shared_ptr<transwarp::node> child) noexcept : parent_(std::move(parent)), child_(std::move(child)) {} // default copy/move semantics edge(const edge&) = default; edge& operator=(const edge&) = default; edge(edge&&) = default; edge& operator=(edge&&) = default; /// Returns the parent node const std::shared_ptr<transwarp::node>& get_parent() const noexcept { return parent_; } /// Returns the child node const std::shared_ptr<transwarp::node>& get_child() const noexcept { return child_; } private: std::shared_ptr<transwarp::node> parent_; std::shared_ptr<transwarp::node> child_; }; /// String conversion for the edge class inline std::string to_string(const transwarp::edge& edge, const std::string& separator="\n") { return transwarp::to_string(*edge.get_parent(), separator) + " -> " + transwarp::to_string(*edge.get_child(), separator); } /// Creates a dot-style string from the given graph inline std::string to_string(const std::vector<transwarp::edge>& graph, const std::string& separator="\n") { std::string dot = "digraph {" + separator; for (const transwarp::edge& edge : graph) { dot += transwarp::to_string(edge, separator) + separator; } dot += "}"; return dot; } /// The executor interface used to perform custom task execution class executor { public: virtual ~executor() = default; /// Returns the name of the executor virtual std::string get_name() const = 0; /// Runs a task which is wrapped by the given functor. The functor only /// captures one shared pointer and can hence be copied at low cost. /// node represents the task that the functor belongs to. /// This function is only ever called on the thread of the caller to schedule(). /// The implementer needs to ensure that this never throws exceptions virtual void execute(const std::function<void()>& functor, const std::shared_ptr<transwarp::node>& node) = 0; }; /// The task events that can be subscribed to using the listener interface enum class event_type { before_scheduled, ///< Just before a task is scheduled (handle_event called on thread of caller to schedule()) before_started, ///< Just before a task starts running (handle_event called on thread that task is run on) before_invoked, ///< Just before a task's functor is invoked (handle_event called on thread that task is run on) after_finished, ///< Just after a task has finished running (handle_event called on thread that task is run on) after_canceled, ///< Just after a task was canceled (handle_event called on thread that task is run on) count, }; /// The listener interface to listen to events raised by tasks class listener { public: virtual ~listener() = default; /// This may be called from arbitrary threads depending on the event type (see transwarp::event_type). /// The implementer needs to ensure that this never throws exceptions virtual void handle_event(transwarp::event_type event, const std::shared_ptr<transwarp::node>& node) = 0; }; /// Determines in which order tasks are scheduled in the graph enum class schedule_type { breadth, ///< Scheduling according to a breadth-first search (default) depth, ///< Scheduling according to a depth-first search }; /// An interface for the task class class itask { public: virtual ~itask() = default; virtual void set_executor(std::shared_ptr<transwarp::executor> executor) = 0; virtual void set_executor_all(std::shared_ptr<transwarp::executor> executor) = 0; virtual void remove_executor() = 0; virtual void remove_executor_all() = 0; virtual void set_priority(std::size_t priority) = 0; virtual void set_priority_all(std::size_t priority) = 0; virtual void reset_priority() = 0; virtual void reset_priority_all() = 0; virtual void set_custom_data(std::shared_ptr<void> custom_data) = 0; virtual void set_custom_data_all(std::shared_ptr<void> custom_data) = 0; virtual void remove_custom_data() = 0; virtual void remove_custom_data_all() = 0; virtual const std::shared_ptr<transwarp::node>& get_node() const noexcept = 0; virtual void add_listener(std::shared_ptr<transwarp::listener> listener) = 0; virtual void add_listener(transwarp::event_type event, std::shared_ptr<transwarp::listener> listener) = 0; virtual void add_listener_all(std::shared_ptr<transwarp::listener> listener) = 0; virtual void add_listener_all(transwarp::event_type event, std::shared_ptr<transwarp::listener> listener) = 0; virtual void remove_listener(const std::shared_ptr<transwarp::listener>& listener) = 0; virtual void remove_listener(transwarp::event_type event, const std::shared_ptr<transwarp::listener>& listener) = 0; virtual void remove_listener_all(const std::shared_ptr<transwarp::listener>& listener) = 0; virtual void remove_listener_all(transwarp::event_type event, const std::shared_ptr<transwarp::listener>& listener) = 0; virtual void remove_listeners() = 0; virtual void remove_listeners(transwarp::event_type event) = 0; virtual void remove_listeners_all() = 0; virtual void remove_listeners_all(transwarp::event_type event) = 0; virtual void schedule() = 0; virtual void schedule(transwarp::executor& executor) = 0; virtual void schedule(bool reset) = 0; virtual void schedule(transwarp::executor& executor, bool reset) = 0; virtual void schedule_all() = 0; virtual void schedule_all(transwarp::executor& executor) = 0; virtual void schedule_all(bool reset_all) = 0; virtual void schedule_all(transwarp::executor& executor, bool reset_all) = 0; virtual void schedule_all(transwarp::schedule_type type) = 0; virtual void schedule_all(transwarp::executor& executor, transwarp::schedule_type type) = 0; virtual void schedule_all(transwarp::schedule_type type, bool reset_all) = 0; virtual void schedule_all(transwarp::executor& executor, transwarp::schedule_type type, bool reset_all) = 0; virtual void set_exception(std::exception_ptr exception) = 0; virtual bool was_scheduled() const noexcept = 0; virtual void wait() const = 0; virtual bool is_ready() const = 0; virtual bool has_result() const = 0; virtual void reset() = 0; virtual void reset_all() = 0; virtual void cancel(bool enabled) noexcept = 0; virtual void cancel_all(bool enabled) noexcept = 0; virtual std::vector<transwarp::edge> get_graph() const = 0; protected: virtual void schedule_impl(bool reset, transwarp::executor* executor=nullptr) = 0; private: friend struct transwarp::detail::visit_depth_visitor; friend struct transwarp::detail::unvisit_visitor; friend struct transwarp::detail::final_visitor; friend struct transwarp::detail::schedule_visitor; virtual void visit_depth(const std::function<void(itask&)>& visitor) = 0; virtual void unvisit() noexcept = 0; virtual void set_node_id(std::size_t id) noexcept = 0; }; /// Removes reference and const from a type template<typename T> struct decay { using type = typename std::remove_const<typename std::remove_reference<T>::type>::type; }; /// Returns the result type of a std::shared_future<T> template<typename T> struct result { using type = typename std::result_of<decltype(&std::shared_future<T>::get)(std::shared_future<T>)>::type; }; /// The task class template<typename ResultType> class task : public transwarp::itask { public: using result_type = ResultType; virtual ~task() = default; virtual void set_value(const typename transwarp::decay<result_type>::type& value) = 0; virtual void set_value(typename transwarp::decay<result_type>::type&& value) = 0; virtual const std::shared_future<result_type>& get_future() const noexcept = 0; virtual typename transwarp::result<result_type>::type get() const = 0; }; /// The task class (reference result type) template<typename ResultType> class task<ResultType&> : public transwarp::itask { public: using result_type = ResultType&; virtual ~task() = default; virtual void set_value(typename transwarp::decay<result_type>::type& value) = 0; virtual const std::shared_future<result_type>& get_future() const noexcept = 0; virtual typename transwarp::result<result_type>::type get() const = 0; }; /// The task class (void result type) template<> class task<void> : public transwarp::itask { public: using result_type = void; virtual ~task() = default; virtual void set_value() = 0; virtual const std::shared_future<result_type>& get_future() const noexcept = 0; virtual result_type get() const = 0; }; /// A base class for a user-defined functor that needs access to the node associated /// to the task or a cancel point to stop a task while it's running class functor { public: virtual ~functor() = default; protected: /// The node associated to the task const std::shared_ptr<transwarp::node>& transwarp_node() const noexcept { return transwarp_node_; } /// If the associated task is canceled then this will throw transwarp::task_canceled /// which will stop the task while it's running void transwarp_cancel_point() const { if (transwarp_node_->is_canceled()) { throw transwarp::task_canceled(std::to_string(transwarp_node_->get_id())); } } private: template<bool> friend struct transwarp::detail::assign_node_if_impl; std::shared_ptr<transwarp::node> transwarp_node_; }; /// Detail namespace for internal functionality only namespace detail { /// Node manipulation struct node_manip { static void set_id(transwarp::node& node, std::size_t id) noexcept { node.id_ = id; } static void set_level(transwarp::node& node, std::size_t level) noexcept { node.level_ = level; } static void set_type(transwarp::node& node, transwarp::task_type type) noexcept { node.type_ = type; } static void set_name(transwarp::node& node, std::shared_ptr<std::string> name) noexcept { node.name_ = std::move(name); } static void set_executor(transwarp::node& node, std::shared_ptr<std::string> executor) noexcept { if (executor) { node.executor_ = std::move(executor); } else { node.executor_.reset(); } } static void add_parent(transwarp::node& node, std::shared_ptr<transwarp::node> parent) { node.parents_.push_back(std::move(parent)); } static void set_priority(transwarp::node& node, std::size_t priority) noexcept { node.priority_ = priority; } static void set_custom_data(transwarp::node& node, std::shared_ptr<void> custom_data) { if (custom_data) { node.custom_data_ = std::move(custom_data); } else { node.custom_data_.reset(); } } static void set_canceled(transwarp::node& node, bool enabled) noexcept { node.canceled_ = enabled; } static void set_avg_waittime_us(transwarp::node& node, std::int64_t waittime) noexcept { node.avg_waittime_us_ = waittime; } static void set_avg_runtime_us(transwarp::node& node, std::int64_t runtime) noexcept { node.avg_runtime_us_ = runtime; } }; /// A simple thread pool used to execute tasks in parallel class thread_pool { public: explicit thread_pool(std::size_t n_threads) : done_(false) { if (n_threads == 0) { throw transwarp::invalid_parameter("number of threads"); } const std::size_t n_target = threads_.size() + n_threads; while (threads_.size() < n_target) { std::thread thread; try { thread = std::thread(&thread_pool::worker, this); } catch (...) { shutdown(); throw; } try { threads_.push_back(std::move(thread)); } catch (...) { shutdown(); thread.join(); throw; } } } // delete copy/move semantics thread_pool(const thread_pool&) = delete; thread_pool& operator=(const thread_pool&) = delete; thread_pool(thread_pool&&) = delete; thread_pool& operator=(thread_pool&&) = delete; ~thread_pool() { shutdown(); } void push(const std::function<void()>& functor) { { std::lock_guard<std::mutex> lock(mutex_); functors_.push(functor); } cond_var_.notify_one(); } private: void worker() { for (;;) { std::function<void()> functor; { std::unique_lock<std::mutex> lock(mutex_); cond_var_.wait(lock, [this]{ return done_ || !functors_.empty(); }); if (done_ && functors_.empty()) { break; } functor = functors_.front(); functors_.pop(); } functor(); } } void shutdown() { { std::lock_guard<std::mutex> lock(mutex_); done_ = true; } cond_var_.notify_all(); for (std::thread& thread : threads_) { thread.join(); } threads_.clear(); } bool done_; std::vector<std::thread> threads_; std::queue<std::function<void()>> functors_; std::condition_variable cond_var_; std::mutex mutex_; }; template<int offset, typename... ParentResults> struct assign_futures_impl { static void work(const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>& source, std::tuple<std::shared_future<ParentResults>...>& target) { std::get<offset>(target) = std::get<offset>(source)->get_future(); assign_futures_impl<offset - 1, ParentResults...>::work(source, target); } }; template<typename... ParentResults> struct assign_futures_impl<-1, ParentResults...> { static void work(const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>&, std::tuple<std::shared_future<ParentResults>...>&) {} }; /// Returns the futures from the given tuple of tasks template<typename... ParentResults> std::tuple<std::shared_future<ParentResults>...> get_futures(const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>& input) { std::tuple<std::shared_future<ParentResults>...> result; assign_futures_impl<static_cast<int>(sizeof...(ParentResults)) - 1, ParentResults...>::work(input, result); return result; } /// Returns the futures from the given vector of tasks template<typename ParentResultType> std::vector<std::shared_future<ParentResultType>> get_futures(const std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>& input) { std::vector<std::shared_future<ParentResultType>> result; result.reserve(input.size()); for (const std::shared_ptr<transwarp::task<ParentResultType>>& task : input) { result.emplace_back(task->get_future()); } return result; } /// Runs the task with the given arguments, hence, invoking the task's functor template<typename Result, typename Task, typename... Args> Result run_task(std::size_t node_id, const std::weak_ptr<Task>& task, Args&&... args) { const std::shared_ptr<Task> t = task.lock(); if (!t) { throw transwarp::task_destroyed(std::to_string(node_id)); } if (t->node_->is_canceled()) { throw transwarp::task_canceled(std::to_string(node_id)); } t->raise_event(transwarp::event_type::before_invoked); return t->functor_(std::forward<Args>(args)...); } inline void wait_for_all() {} /// Waits for all parents to finish template<typename ParentResult, typename... ParentResults> void wait_for_all(const std::shared_ptr<transwarp::task<ParentResult>>& parent, const std::shared_ptr<transwarp::task<ParentResults>>& ...parents) { parent->get_future().wait(); transwarp::detail::wait_for_all(parents...); } /// Waits for all parents to finish template<typename ParentResultType> void wait_for_all(const std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>& parents) { for (const std::shared_ptr<transwarp::task<ParentResultType>>& parent : parents) { parent->get_future().wait(); } } template<typename Parent> Parent wait_for_any_impl() { return {}; } template<typename Parent, typename ParentResult, typename... ParentResults> Parent wait_for_any_impl(const std::shared_ptr<transwarp::task<ParentResult>>& parent, const std::shared_ptr<transwarp::task<ParentResults>>& ...parents) { const std::future_status status = parent->get_future().wait_for(std::chrono::microseconds(1)); if (status == std::future_status::ready) { return parent; } return transwarp::detail::wait_for_any_impl<Parent>(parents...); } /// Waits for the first parent to finish template<typename Parent, typename... ParentResults> Parent wait_for_any(const std::shared_ptr<transwarp::task<ParentResults>>& ...parents) { for (;;) { Parent parent = transwarp::detail::wait_for_any_impl<Parent>(parents...); if (parent) { return parent; } } } /// Waits for the first parent to finish template<typename ParentResultType> std::shared_ptr<transwarp::task<ParentResultType>> wait_for_any(const std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>& parents) { for (;;) { for (const std::shared_ptr<transwarp::task<ParentResultType>>& parent : parents) { const std::future_status status = parent->get_future().wait_for(std::chrono::microseconds(1)); if (status == std::future_status::ready) { return parent; } } } } template<typename OneResult> void cancel_all_but_one(const std::shared_ptr<transwarp::task<OneResult>>&) {} /// Cancels all tasks but one template<typename OneResult, typename ParentResult, typename... ParentResults> void cancel_all_but_one(const std::shared_ptr<transwarp::task<OneResult>>& one, const std::shared_ptr<transwarp::task<ParentResult>>& parent, const std::shared_ptr<transwarp::task<ParentResults>>& ...parents) { if (one != parent) { parent->cancel(true); } transwarp::detail::cancel_all_but_one(one, parents...); } /// Cancels all tasks but one template<typename OneResult, typename ParentResultType> void cancel_all_but_one(const std::shared_ptr<transwarp::task<OneResult>>& one, const std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>& parents) { for (const std::shared_ptr<transwarp::task<ParentResultType>>& parent : parents) { if (one != parent) { parent->cancel(true); } } } template<typename TaskType, bool done, int total, int... n> struct call_impl { template<typename Result, typename Task, typename... ParentResults> static Result work(std::size_t node_id, const Task& task, const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>& parents) { return call_impl<TaskType, total == 1 + static_cast<int>(sizeof...(n)), total, n..., static_cast<int>(sizeof...(n))>::template work<Result>(node_id, task, parents); } }; template<typename TaskType> struct call_impl_vector; template<int total, int... n> struct call_impl<transwarp::root_type, true, total, n...> { template<typename Result, typename Task, typename... ParentResults> static Result work(std::size_t node_id, const Task& task, const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>&) { return transwarp::detail::run_task<Result>(node_id, task); } }; template<> struct call_impl_vector<transwarp::root_type> { template<typename Result, typename Task, typename ParentResultType> static Result work(std::size_t node_id, const Task& task, const std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>&) { return transwarp::detail::run_task<Result>(node_id, task); } }; template<int total, int... n> struct call_impl<transwarp::accept_type, true, total, n...> { template<typename Result, typename Task, typename... ParentResults> static Result work(std::size_t node_id, const Task& task, const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>& parents) { transwarp::detail::wait_for_all(std::get<n>(parents)...); const std::tuple<std::shared_future<ParentResults>...> futures = transwarp::detail::get_futures(parents); return transwarp::detail::run_task<Result>(node_id, task, std::get<n>(futures)...); } }; template<> struct call_impl_vector<transwarp::accept_type> { template<typename Result, typename Task, typename ParentResultType> static Result work(std::size_t node_id, const Task& task, const std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>& parents) { transwarp::detail::wait_for_all(parents); return transwarp::detail::run_task<Result>(node_id, task, transwarp::detail::get_futures(parents)); } }; template<int total, int... n> struct call_impl<transwarp::accept_any_type, true, total, n...> { template<typename Result, typename Task, typename... ParentResults> static Result work(std::size_t node_id, const Task& task, const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>& parents) { using parent_t = typename std::remove_reference<decltype(std::get<0>(parents))>::type; // Use first type as reference parent_t parent = transwarp::detail::wait_for_any<parent_t>(std::get<n>(parents)...); transwarp::detail::cancel_all_but_one(parent, std::get<n>(parents)...); return transwarp::detail::run_task<Result>(node_id, task, parent->get_future()); } }; template<> struct call_impl_vector<transwarp::accept_any_type> { template<typename Result, typename Task, typename ParentResultType> static Result work(std::size_t node_id, const Task& task, const std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>& parents) { std::shared_ptr<transwarp::task<ParentResultType>> parent = transwarp::detail::wait_for_any(parents); transwarp::detail::cancel_all_but_one(parent, parents); return transwarp::detail::run_task<Result>(node_id, task, parent->get_future()); } }; template<int total, int... n> struct call_impl<transwarp::consume_type, true, total, n...> { template<typename Result, typename Task, typename... ParentResults> static Result work(std::size_t node_id, const Task& task, const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>& parents) { transwarp::detail::wait_for_all(std::get<n>(parents)...); return transwarp::detail::run_task<Result>(node_id, task, std::get<n>(parents)->get_future().get()...); } }; template<> struct call_impl_vector<transwarp::consume_type> { template<typename Result, typename Task, typename ParentResultType> static Result work(std::size_t node_id, const Task& task, const std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>& parents) { transwarp::detail::wait_for_all(parents); std::vector<ParentResultType> results; results.reserve(parents.size()); for (const std::shared_ptr<transwarp::task<ParentResultType>>& parent : parents) { results.emplace_back(parent->get_future().get()); } return transwarp::detail::run_task<Result>(node_id, task, std::move(results)); } }; template<int total, int... n> struct call_impl<transwarp::consume_any_type, true, total, n...> { template<typename Result, typename Task, typename... ParentResults> static Result work(std::size_t node_id, const Task& task, const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>& parents) { using parent_t = typename std::remove_reference<decltype(std::get<0>(parents))>::type; /// Use first type as reference parent_t parent = transwarp::detail::wait_for_any<parent_t>(std::get<n>(parents)...); transwarp::detail::cancel_all_but_one(parent, std::get<n>(parents)...); return transwarp::detail::run_task<Result>(node_id, task, parent->get_future().get()); } }; template<> struct call_impl_vector<transwarp::consume_any_type> { template<typename Result, typename Task, typename ParentResultType> static Result work(std::size_t node_id, const Task& task, const std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>& parents) { std::shared_ptr<transwarp::task<ParentResultType>> parent = transwarp::detail::wait_for_any(parents); transwarp::detail::cancel_all_but_one(parent, parents); return transwarp::detail::run_task<Result>(node_id, task, parent->get_future().get()); } }; template<int total, int... n> struct call_impl<transwarp::wait_type, true, total, n...> { template<typename Result, typename Task, typename... ParentResults> static Result work(std::size_t node_id, const Task& task, const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>& parents) { transwarp::detail::wait_for_all(std::get<n>(parents)...); get_all(std::get<n>(parents)...); // Ensures that exceptions are propagated return transwarp::detail::run_task<Result>(node_id, task); } template<typename T, typename... Args> static void get_all(const T& arg, const Args& ...args) { arg->get_future().get(); get_all(args...); } static void get_all() {} }; template<> struct call_impl_vector<transwarp::wait_type> { template<typename Result, typename Task, typename ParentResultType> static Result work(std::size_t node_id, const Task& task, const std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>& parents) { transwarp::detail::wait_for_all(parents); for (const std::shared_ptr<transwarp::task<ParentResultType>>& parent : parents) { parent->get_future().get(); // Ensures that exceptions are propagated } return transwarp::detail::run_task<Result>(node_id, task); } }; template<int total, int... n> struct call_impl<transwarp::wait_any_type, true, total, n...> { template<typename Result, typename Task, typename... ParentResults> static Result work(std::size_t node_id, const Task& task, const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>& parents) { using parent_t = typename std::remove_reference<decltype(std::get<0>(parents))>::type; // Use first type as reference parent_t parent = transwarp::detail::wait_for_any<parent_t>(std::get<n>(parents)...); transwarp::detail::cancel_all_but_one(parent, std::get<n>(parents)...); parent->get_future().get(); // Ensures that exceptions are propagated return transwarp::detail::run_task<Result>(node_id, task); } }; template<> struct call_impl_vector<transwarp::wait_any_type> { template<typename Result, typename Task, typename ParentResultType> static Result work(std::size_t node_id, const Task& task, const std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>& parents) { std::shared_ptr<transwarp::task<ParentResultType>> parent = transwarp::detail::wait_for_any(parents); transwarp::detail::cancel_all_but_one(parent, parents); parent->get_future().get(); // Ensures that exceptions are propagated return transwarp::detail::run_task<Result>(node_id, task); } }; /// Calls the functor of the given task with the results from the tuple of parents. /// Throws transwarp::task_canceled if the task is canceled. /// Throws transwarp::task_destroyed in case the task was destroyed prematurely. template<typename TaskType, typename Result, typename Task, typename... ParentResults> Result call(std::size_t node_id, const Task& task, const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>& parents) { constexpr std::size_t n = std::tuple_size<std::tuple<std::shared_future<ParentResults>...>>::value; return transwarp::detail::call_impl<TaskType, 0 == n, static_cast<int>(n)>::template work<Result>(node_id, task, parents); } /// Calls the functor of the given task with the results from the vector of parents. /// Throws transwarp::task_canceled if the task is canceled. /// Throws transwarp::task_destroyed in case the task was destroyed prematurely. template<typename TaskType, typename Result, typename Task, typename ParentResultType> Result call(std::size_t node_id, const Task& task, const std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>& parents) { return transwarp::detail::call_impl_vector<TaskType>::template work<Result>(node_id, task, parents); } template<std::size_t...> struct indices {}; template<std::size_t...> struct construct_range; template<std::size_t end, std::size_t idx, std::size_t... i> struct construct_range<end, idx, i...> : construct_range<end, idx + 1, i..., idx> {}; template<std::size_t end, std::size_t... i> struct construct_range<end, end, i...> { using type = transwarp::detail::indices<i...>; }; template<std::size_t b, std::size_t e> struct index_range { using type = typename transwarp::detail::construct_range<e, b>::type; }; template<typename Functor, typename... ParentResults> void call_with_each_index(transwarp::detail::indices<>, const Functor&, const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>&) {} template<std::size_t i, std::size_t... j, typename Functor, typename... ParentResults> void call_with_each_index(transwarp::detail::indices<i, j...>, const Functor& f, const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>& t) { auto ptr = std::get<i>(t); if (!ptr) { throw transwarp::invalid_parameter("task pointer"); } f(*ptr); transwarp::detail::call_with_each_index(transwarp::detail::indices<j...>(), f, t); } /// Calls the functor with every element in the tuple template<typename Functor, typename... ParentResults> void call_with_each(const Functor& f, const std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>& t) { constexpr std::size_t n = std::tuple_size<std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>>::value; using index_t = typename transwarp::detail::index_range<0, n>::type; transwarp::detail::call_with_each_index(index_t(), f, t); } /// Calls the functor with every element in the vector template<typename Functor, typename ParentResultType> void call_with_each(const Functor& f, const std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>& v) { for (const std::shared_ptr<transwarp::task<ParentResultType>>& ptr : v) { if (!ptr) { throw transwarp::invalid_parameter("task pointer"); } f(*ptr); } } /// Sets parents and level of the node struct parent_visitor { explicit parent_visitor(transwarp::node& node) noexcept : node_(node) {} void operator()(const transwarp::itask& task) const { transwarp::detail::node_manip::add_parent(node_, task.get_node()); if (node_.get_level() <= task.get_node()->get_level()) { /// A child's level is always larger than any of its parents' levels transwarp::detail::node_manip::set_level(node_, task.get_node()->get_level() + 1); } } transwarp::node& node_; }; /// Applies final bookkeeping to the task struct final_visitor { final_visitor() noexcept : id_(0) {} void operator()(transwarp::itask& task) noexcept { task.set_node_id(id_++); } std::size_t id_; }; /// Generates a graph struct graph_visitor { explicit graph_visitor(std::vector<transwarp::edge>& graph) noexcept : graph_(graph) {} void operator()(const transwarp::itask& task) { const std::shared_ptr<transwarp::node>& node = task.get_node(); for (const std::shared_ptr<transwarp::node>& parent : node->get_parents()) { graph_.emplace_back(parent, node); } } std::vector<transwarp::edge>& graph_; }; /// Schedules using the given executor struct schedule_visitor { schedule_visitor(bool reset, transwarp::executor* executor) noexcept : reset_(reset), executor_(executor) {} void operator()(transwarp::itask& task) { task.schedule_impl(reset_, executor_); } bool reset_; transwarp::executor* executor_; }; /// Resets the given task struct reset_visitor { void operator()(transwarp::itask& task) const { task.reset(); } }; /// Cancels or resumes the given task struct cancel_visitor { explicit cancel_visitor(bool enabled) noexcept : enabled_(enabled) {} void operator()(transwarp::itask& task) const noexcept { task.cancel(enabled_); } bool enabled_; }; /// Assigns an executor to the given task struct set_executor_visitor { explicit set_executor_visitor(std::shared_ptr<transwarp::executor> executor) noexcept : executor_(std::move(executor)) {} void operator()(transwarp::itask& task) const noexcept { task.set_executor(executor_); } std::shared_ptr<transwarp::executor> executor_; }; /// Removes the executor from the given task struct remove_executor_visitor { void operator()(transwarp::itask& task) const noexcept { task.remove_executor(); } }; /// Assigns a priority to the given task struct set_priority_visitor { explicit set_priority_visitor(std::size_t priority) noexcept : priority_(priority) {} void operator()(transwarp::itask& task) const noexcept { task.set_priority(priority_); } std::size_t priority_; }; /// Resets the priority of the given task struct reset_priority_visitor { void operator()(transwarp::itask& task) const noexcept { task.reset_priority(); } }; /// Assigns custom data to the given task struct set_custom_data_visitor { explicit set_custom_data_visitor(std::shared_ptr<void> custom_data) noexcept : custom_data_(std::move(custom_data)) {} void operator()(transwarp::itask& task) const noexcept { task.set_custom_data(custom_data_); } std::shared_ptr<void> custom_data_; }; /// Removes custom data from the given task struct remove_custom_data_visitor { void operator()(transwarp::itask& task) const noexcept { task.remove_custom_data(); } }; /// Pushes the given task into the vector of tasks struct push_task_visitor { explicit push_task_visitor(std::vector<transwarp::itask*>& tasks) : tasks_(tasks) {} void operator()(transwarp::itask& task) { tasks_.push_back(&task); } std::vector<transwarp::itask*>& tasks_; }; /// Adds a new listener to the given task struct add_listener_visitor { explicit add_listener_visitor(std::shared_ptr<transwarp::listener> listener) : listener_(std::move(listener)) {} void operator()(transwarp::itask& task) { task.add_listener(listener_); } std::shared_ptr<transwarp::listener> listener_; }; /// Adds a new listener per event type to the given task struct add_listener_per_event_visitor { add_listener_per_event_visitor(transwarp::event_type event, std::shared_ptr<transwarp::listener> listener) : event_(event), listener_(std::move(listener)) {} void operator()(transwarp::itask& task) { task.add_listener(event_, listener_); } transwarp::event_type event_; std::shared_ptr<transwarp::listener> listener_; }; /// Removes a listener from the given task struct remove_listener_visitor { explicit remove_listener_visitor(std::shared_ptr<transwarp::listener> listener) : listener_(std::move(listener)) {} void operator()(transwarp::itask& task) { task.remove_listener(listener_); } std::shared_ptr<transwarp::listener> listener_; }; /// Removes a listener per event type from the given task struct remove_listener_per_event_visitor { remove_listener_per_event_visitor(transwarp::event_type event, std::shared_ptr<transwarp::listener> listener) : event_(event), listener_(std::move(listener)) {} void operator()(transwarp::itask& task) { task.remove_listener(event_, listener_); } transwarp::event_type event_; std::shared_ptr<transwarp::listener> listener_; }; /// Removes all listeners from the given task struct remove_listeners_visitor { void operator()(transwarp::itask& task) { task.remove_listeners(); } }; /// Removes all listeners per event type from the given task struct remove_listeners_per_event_visitor { explicit remove_listeners_per_event_visitor(transwarp::event_type event) : event_(event) {} void operator()(transwarp::itask& task) { task.remove_listeners(event_); } transwarp::event_type event_; }; /// Visits the given task using the visitor given in the constructor struct visit_depth_visitor { explicit visit_depth_visitor(const std::function<void(transwarp::itask&)>& visitor) noexcept : visitor_(visitor) {} void operator()(transwarp::itask& task) const { task.visit_depth(visitor_); } const std::function<void(transwarp::itask&)>& visitor_; }; /// Unvisits the given task struct unvisit_visitor { void operator()(transwarp::itask& task) const noexcept { task.unvisit(); } }; /// Determines the result type of the Functor dispatching on the task type template<typename TaskType, typename Functor, typename... ParentResults> struct functor_result { static_assert(std::is_same<TaskType, transwarp::root_type>::value || std::is_same<TaskType, transwarp::accept_type>::value || std::is_same<TaskType, transwarp::accept_any_type>::value || std::is_same<TaskType, transwarp::consume_type>::value || std::is_same<TaskType, transwarp::consume_any_type>::value || std::is_same<TaskType, transwarp::wait_type>::value || std::is_same<TaskType, transwarp::wait_any_type>::value, "Invalid task type, must be one of: root, accept, accept_any, consume, consume_any, wait, wait_any"); }; template<typename Functor, typename... ParentResults> struct functor_result<transwarp::root_type, Functor, ParentResults...> { static_assert(sizeof...(ParentResults) == 0, "A root task cannot have parent tasks"); using type = decltype(std::declval<Functor>()()); }; template<typename Functor, typename... ParentResults> struct functor_result<transwarp::accept_type, Functor, ParentResults...> { static_assert(sizeof...(ParentResults) > 0, "An accept task must have at least one parent"); using type = decltype(std::declval<Functor>()(std::declval<std::shared_future<ParentResults>>()...)); }; template<typename Functor, typename ParentResultType> struct functor_result<transwarp::accept_type, Functor, std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>> { using type = decltype(std::declval<Functor>()(std::declval<std::vector<std::shared_future<ParentResultType>>>())); }; template<typename Functor, typename... ParentResults> struct functor_result<transwarp::accept_any_type, Functor, ParentResults...> { static_assert(sizeof...(ParentResults) > 0, "An accept_any task must have at least one parent"); using arg_t = typename std::tuple_element<0, std::tuple<ParentResults...>>::type; // Using first type as reference using type = decltype(std::declval<Functor>()(std::declval<std::shared_future<arg_t>>())); }; template<typename Functor, typename ParentResultType> struct functor_result<transwarp::accept_any_type, Functor, std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>> { using type = decltype(std::declval<Functor>()(std::declval<std::shared_future<ParentResultType>>())); }; template<typename Functor, typename... ParentResults> struct functor_result<transwarp::consume_type, Functor, ParentResults...> { static_assert(sizeof...(ParentResults) > 0, "A consume task must have at least one parent"); using type = decltype(std::declval<Functor>()(std::declval<ParentResults>()...)); }; template<typename Functor, typename ParentResultType> struct functor_result<transwarp::consume_type, Functor, std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>> { using type = decltype(std::declval<Functor>()(std::declval<std::vector<ParentResultType>>())); }; template<typename Functor, typename... ParentResults> struct functor_result<transwarp::consume_any_type, Functor, ParentResults...> { static_assert(sizeof...(ParentResults) > 0, "A consume_any task must have at least one parent"); using arg_t = typename std::tuple_element<0, std::tuple<ParentResults...>>::type; // Using first type as reference using type = decltype(std::declval<Functor>()(std::declval<arg_t>())); }; template<typename Functor, typename ParentResultType> struct functor_result<transwarp::consume_any_type, Functor, std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>> { using type = decltype(std::declval<Functor>()(std::declval<ParentResultType>())); }; template<typename Functor, typename... ParentResults> struct functor_result<transwarp::wait_type, Functor, ParentResults...> { static_assert(sizeof...(ParentResults) > 0, "A wait task must have at least one parent"); using type = decltype(std::declval<Functor>()()); }; template<typename Functor, typename ParentResultType> struct functor_result<transwarp::wait_type, Functor, std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>> { using type = decltype(std::declval<Functor>()()); }; template<typename Functor, typename... ParentResults> struct functor_result<transwarp::wait_any_type, Functor, ParentResults...> { static_assert(sizeof...(ParentResults) > 0, "A wait_any task must have at least one parent"); using type = decltype(std::declval<Functor>()()); }; template<typename Functor, typename ParentResultType> struct functor_result<transwarp::wait_any_type, Functor, std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>> { using type = decltype(std::declval<Functor>()()); }; template<bool is_transwarp_functor> struct assign_node_if_impl; template<> struct assign_node_if_impl<true> { template<typename Functor> void operator()(Functor& functor, std::shared_ptr<transwarp::node> node) const noexcept { functor.transwarp_node_ = std::move(node); } }; template<> struct assign_node_if_impl<false> { template<typename Functor> void operator()(Functor&, std::shared_ptr<transwarp::node>) const noexcept {} }; /// Assigns the node to the given functor if the functor is a subclass of transwarp::functor template<typename Functor> void assign_node_if(Functor& functor, std::shared_ptr<transwarp::node> node) noexcept { transwarp::detail::assign_node_if_impl<std::is_base_of<transwarp::functor, Functor>::value>{}(functor, std::move(node)); } /// Returns a ready future with the given value as its state template<typename ResultType, typename Value> std::shared_future<ResultType> make_future_with_value(Value&& value) { std::promise<ResultType> promise; promise.set_value(std::forward<Value>(value)); return promise.get_future(); } /// Returns a ready future inline std::shared_future<void> make_ready_future() { std::promise<void> promise; promise.set_value(); return promise.get_future(); } /// Returns a ready future with the given exception as its state template<typename ResultType> std::shared_future<ResultType> make_future_with_exception(std::exception_ptr exception) { if (!exception) { throw transwarp::invalid_parameter("exception pointer"); } std::promise<ResultType> promise; promise.set_exception(exception); return promise.get_future(); } /// Determines the type of the parents template<typename... ParentResults> struct parents { using type = std::tuple<std::shared_ptr<transwarp::task<ParentResults>>...>; }; /// Determines the type of the parents. Specialization for vector parents template<typename ParentResultType> struct parents<std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>> { using type = std::vector<std::shared_ptr<transwarp::task<ParentResultType>>>; }; template<typename ResultType, typename TaskType> class base_runner { protected: template<typename Task, typename Parents> void call(std::size_t node_id, const std::weak_ptr<Task>& task, const Parents& parents) { promise_.set_value(transwarp::detail::call<TaskType, ResultType>(node_id, task, parents)); } std::promise<ResultType> promise_; }; template<typename TaskType> class base_runner<void, TaskType> { protected: template<typename Task, typename Parents> void call(std::size_t node_id, const std::weak_ptr<Task>& task, const Parents& parents) { transwarp::detail::call<TaskType, void>(node_id, task, parents); promise_.set_value(); } std::promise<void> promise_; }; /// A callable to run a task given its parents template<typename ResultType, typename TaskType, typename Task, typename Parents> class runner : public transwarp::detail::base_runner<ResultType, TaskType> { public: runner(std::size_t node_id, const std::weak_ptr<Task>& task, const typename transwarp::decay<Parents>::type& parents) : node_id_(node_id), task_(task), parents_(parents) {} std::future<ResultType> get_future() { return this->promise_.get_future(); } void operator()() { if (const std::shared_ptr<Task> t = task_.lock()) { t->raise_event(transwarp::event_type::before_started); } try { this->call(node_id_, task_, parents_); } catch (const transwarp::task_canceled&) { this->promise_.set_exception(std::current_exception()); if (const std::shared_ptr<Task> t = task_.lock()) { t->raise_event(transwarp::event_type::after_canceled); } } catch (...) { this->promise_.set_exception(std::current_exception()); } if (const std::shared_ptr<Task> t = task_.lock()) { t->raise_event(transwarp::event_type::after_finished); } } private: const std::size_t node_id_; const std::weak_ptr<Task> task_; const typename transwarp::decay<Parents>::type parents_; }; /// A simple circular buffer (FIFO). /// ValueType must support default construction. The buffer lets you push /// new values onto the back and pop old values off the front. template<typename ValueType> class circular_buffer { public: static_assert(std::is_default_constructible<ValueType>::value, "ValueType must be default constructible"); using value_type = ValueType; /// Constructs a circular buffer with a given fixed capacity explicit circular_buffer(std::size_t capacity) : data_(capacity) { if (capacity < 1) { throw transwarp::invalid_parameter("capacity"); } } // delete copy/move semantics circular_buffer(const circular_buffer&) = delete; circular_buffer& operator=(const circular_buffer&) = delete; circular_buffer(circular_buffer&& other) = delete; circular_buffer& operator=(circular_buffer&&) = delete; /// Pushes a new value onto the end of the buffer. If that exceeds the capacity /// of the buffer then the oldest value gets dropped (the one at the front). template<typename T, typename = typename std::enable_if<std::is_same<typename std::decay<T>::type, value_type>::value>::type> void push(T&& value) { data_[end_] = std::forward<T>(value); increment(); } /// Returns the value at the front of the buffer (the oldest value). /// This is undefined if the buffer is empty const value_type& front() const { return data_[front_]; } /// Removes the value at the front of the buffer (the oldest value) void pop() { if (!empty()) { data_[front_] = ValueType{}; decrement(); } } /// Returns the capacity of the buffer std::size_t capacity() const { return data_.size(); } /// Returns the number of populated values of the buffer. Its maximum value /// equals the capacity of the buffer std::size_t size() const { return size_; } /// Returns whether the buffer is empty bool empty() const { return size_ == 0; } /// Returns whether the buffer is full bool full() const { return size_ == data_.size(); } /// Swaps this buffer with the given buffer void swap(circular_buffer& buffer) { std::swap(end_, buffer.end_); std::swap(front_, buffer.front_); std::swap(size_, buffer.size_); std::swap(data_, buffer.data_); } private: void increment_or_wrap(std::size_t& value) const { if (value == data_.size() - 1) { value = 0; } else { ++value; } } void increment() { increment_or_wrap(end_); if (full()) { increment_or_wrap(front_); } else { ++size_; } } void decrement() { increment_or_wrap(front_); --size_; } std::size_t end_{}; std::size_t front_{}; std::size_t size_{}; std::vector<value_type> data_; }; class spinlock { public: void lock() noexcept { while (locked_.test_and_set(std::memory_order_acquire)); } void unlock() noexcept { locked_.clear(std::memory_order_release); } private: std::atomic_flag locked_ = ATOMIC_FLAG_INIT; }; } // detail /// Executor for sequential execution. Runs functors sequentially on the same thread class sequential : public transwarp::executor { public: sequential() = default; // delete copy/move semantics sequential(const sequential&) = delete; sequential& operator=(const sequential&) = delete; sequential(sequential&&) = delete; sequential& operator=(sequential&&) = delete; /// Returns the name of the executor std::string get_name() const override { return "transwarp::sequential"; } /// Runs the functor on the current thread void execute(const std::function<void()>& functor, const std::shared_ptr<transwarp::node>&) override { functor(); } }; /// Executor for parallel execution. Uses a simple thread pool class parallel : public transwarp::executor { public: explicit parallel(std::size_t n_threads) : pool_(n_threads) {} // delete copy/move semantics parallel(const parallel&) = delete; parallel& operator=(const parallel&) = delete; parallel(parallel&&) = delete; parallel& operator=(parallel&&) = delete; /// Returns the name of the executor std::string get_name() const override { return "transwarp::parallel"; } /// Pushes the functor into the thread pool for asynchronous execution void execute(const std::function<void()>& functor, const std::shared_ptr<transwarp::node>&) override { pool_.push(functor); } private: transwarp::detail::thread_pool pool_; }; /// Detail namespace for internal functionality only namespace detail { /// The base task class that contains the functionality that can be used /// with all result types (void and non-void). template<typename ResultType, typename TaskType, typename Functor, typename... ParentResults> class task_impl_base : public transwarp::task<ResultType>, public std::enable_shared_from_this<task_impl_base<ResultType, TaskType, Functor, ParentResults...>> { public: /// The task type using task_type = TaskType; /// The result type of this task using result_type = ResultType; /// Assigns an executor to this task which takes precedence over /// the executor provided in schedule() or schedule_all() void set_executor(std::shared_ptr<transwarp::executor> executor) override { ensure_task_not_running(); if (!executor) { throw transwarp::invalid_parameter("executor pointer"); } executor_ = std::move(executor); transwarp::detail::node_manip::set_executor(*node_, std::shared_ptr<std::string>(new std::string(executor_->get_name()))); } /// Assigns an executor to all tasks which takes precedence over /// the executor provided in schedule() or schedule_all() void set_executor_all(std::shared_ptr<transwarp::executor> executor) override { ensure_task_not_running(); transwarp::detail::set_executor_visitor visitor(std::move(executor)); visit_depth_all(visitor); } /// Removes the executor from this task void remove_executor() override { ensure_task_not_running(); executor_.reset(); transwarp::detail::node_manip::set_executor(*node_, nullptr); } /// Removes the executor from all tasks void remove_executor_all() override { ensure_task_not_running(); transwarp::detail::remove_executor_visitor visitor; visit_depth_all(visitor); } /// Sets a task priority (defaults to 0). transwarp will not directly use this. /// This is only useful if something else is using the priority (e.g. a custom executor) void set_priority(std::size_t priority) override { ensure_task_not_running(); transwarp::detail::node_manip::set_priority(*node_, priority); } /// Sets a priority to all tasks (defaults to 0). transwarp will not directly use this. /// This is only useful if something else is using the priority (e.g. a custom executor) void set_priority_all(std::size_t priority) override { ensure_task_not_running(); transwarp::detail::set_priority_visitor visitor(priority); visit_depth_all(visitor); } /// Resets the task priority to 0 void reset_priority() override { ensure_task_not_running(); transwarp::detail::node_manip::set_priority(*node_, 0); } /// Resets the priority of all tasks to 0 void reset_priority_all() override { ensure_task_not_running(); transwarp::detail::reset_priority_visitor visitor; visit_depth_all(visitor); } /// Assigns custom data to this task. transwarp will not directly use this. /// This is only useful if something else is using this custom data (e.g. a custom executor) void set_custom_data(std::shared_ptr<void> custom_data) override { ensure_task_not_running(); if (!custom_data) { throw transwarp::invalid_parameter("custom data pointer"); } transwarp::detail::node_manip::set_custom_data(*node_, std::move(custom_data)); } /// Assigns custom data to all tasks. transwarp will not directly use this. /// This is only useful if something else is using this custom data (e.g. a custom executor) void set_custom_data_all(std::shared_ptr<void> custom_data) override { ensure_task_not_running(); transwarp::detail::set_custom_data_visitor visitor(std::move(custom_data)); visit_depth_all(visitor); } /// Removes custom data from this task void remove_custom_data() override { ensure_task_not_running(); transwarp::detail::node_manip::set_custom_data(*node_, nullptr); } /// Removes custom data from all tasks void remove_custom_data_all() override { ensure_task_not_running(); transwarp::detail::remove_custom_data_visitor visitor; visit_depth_all(visitor); } /// Returns the future associated to the underlying execution const std::shared_future<result_type>& get_future() const noexcept override { return future_; } /// Returns the associated node const std::shared_ptr<transwarp::node>& get_node() const noexcept override { return node_; } /// Adds a new listener for all event types void add_listener(std::shared_ptr<transwarp::listener> listener) override { ensure_task_not_running(); check_listener(listener); for (std::vector<std::shared_ptr<transwarp::listener>>& l : listeners_) { l.push_back(listener); } } /// Adds a new listener for the given event type only void add_listener(transwarp::event_type event, std::shared_ptr<transwarp::listener> listener) override { ensure_task_not_running(); check_listener(listener); listeners_[get_event_index(event)].push_back(std::move(listener)); } /// Adds a new listener for all event types and for all parents void add_listener_all(std::shared_ptr<transwarp::listener> listener) override { ensure_task_not_running(); transwarp::detail::add_listener_visitor visitor(std::move(listener)); visit_depth_all(visitor); } /// Adds a new listener for the given event type only and for all parents void add_listener_all(transwarp::event_type event, std::shared_ptr<transwarp::listener> listener) override { ensure_task_not_running(); transwarp::detail::add_listener_per_event_visitor visitor(event, std::move(listener)); visit_depth_all(visitor); } /// Removes the listener for all event types void remove_listener(const std::shared_ptr<transwarp::listener>& listener) override { ensure_task_not_running(); check_listener(listener); for (std::vector<std::shared_ptr<transwarp::listener>>& l : listeners_) { l.erase(std::remove(l.begin(), l.end(), listener), l.end()); } } /// Removes the listener for the given event type only void remove_listener(transwarp::event_type event, const std::shared_ptr<transwarp::listener>& listener) override { ensure_task_not_running(); check_listener(listener); std::vector<std::shared_ptr<transwarp::listener>>& l = listeners_[get_event_index(event)]; l.erase(std::remove(l.begin(), l.end(), listener), l.end()); } /// Removes the listener for all event types and for all parents void remove_listener_all(const std::shared_ptr<transwarp::listener>& listener) override { ensure_task_not_running(); transwarp::detail::remove_listener_visitor visitor(std::move(listener)); visit_depth_all(visitor); } /// Removes the listener for the given event type only and for all parents void remove_listener_all(transwarp::event_type event, const std::shared_ptr<transwarp::listener>& listener) override { ensure_task_not_running(); transwarp::detail::remove_listener_per_event_visitor visitor(event, std::move(listener)); visit_depth_all(visitor); } /// Removes all listeners void remove_listeners() override { ensure_task_not_running(); for (std::vector<std::shared_ptr<transwarp::listener>>& l : listeners_) { l.clear(); } } /// Removes all listeners for the given event type void remove_listeners(transwarp::event_type event) override { ensure_task_not_running(); listeners_[get_event_index(event)].clear(); } /// Removes all listeners and for all parents void remove_listeners_all() override { ensure_task_not_running(); transwarp::detail::remove_listeners_visitor visitor; visit_depth_all(visitor); } /// Removes all listeners for the given event type and for all parents void remove_listeners_all(transwarp::event_type event) override { ensure_task_not_running(); transwarp::detail::remove_listeners_per_event_visitor visitor(event); visit_depth_all(visitor); } /// Schedules this task for execution on the caller thread. /// The task-specific executor gets precedence if it exists. /// This overload will reset the underlying future. void schedule() override { ensure_task_not_running(); this->schedule_impl(true); } /// Schedules this task for execution on the caller thread. /// The task-specific executor gets precedence if it exists. /// reset denotes whether schedule should reset the underlying /// future and schedule even if the future is already valid. void schedule(bool reset) override { ensure_task_not_running(); this->schedule_impl(reset); } /// Schedules this task for execution using the provided executor. /// The task-specific executor gets precedence if it exists. /// This overload will reset the underlying future. void schedule(transwarp::executor& executor) override { ensure_task_not_running(); this->schedule_impl(true, &executor); } /// Schedules this task for execution using the provided executor. /// The task-specific executor gets precedence if it exists. /// reset denotes whether schedule should reset the underlying /// future and schedule even if the future is already valid. void schedule(transwarp::executor& executor, bool reset) override { ensure_task_not_running(); this->schedule_impl(reset, &executor); } /// Schedules all tasks in the graph for execution on the caller thread. /// The task-specific executors get precedence if they exist. /// This overload will reset the underlying futures. void schedule_all() override { ensure_task_not_running(); schedule_all_impl(true, transwarp::schedule_type::breadth); } /// Schedules all tasks in the graph for execution using the provided executor. /// The task-specific executors get precedence if they exist. /// This overload will reset the underlying futures. void schedule_all(transwarp::executor& executor) override { ensure_task_not_running(); schedule_all_impl(true, transwarp::schedule_type::breadth, &executor); } /// Schedules all tasks in the graph for execution on the caller thread. /// The task-specific executors get precedence if they exist. /// reset_all denotes whether schedule_all should reset the underlying /// futures and schedule even if the futures are already present. void schedule_all(bool reset_all) override { ensure_task_not_running(); schedule_all_impl(reset_all, transwarp::schedule_type::breadth); } /// Schedules all tasks in the graph for execution using the provided executor. /// The task-specific executors get precedence if they exist. /// reset_all denotes whether schedule_all should reset the underlying /// futures and schedule even if the futures are already present. void schedule_all(transwarp::executor& executor, bool reset_all) override { ensure_task_not_running(); schedule_all_impl(reset_all, transwarp::schedule_type::breadth, &executor); } /// Schedules all tasks in the graph for execution on the caller thread. /// The task-specific executors get precedence if they exist. /// This overload will reset the underlying futures. void schedule_all(transwarp::schedule_type type) override { ensure_task_not_running(); schedule_all_impl(true, type); } /// Schedules all tasks in the graph for execution using the provided executor. /// The task-specific executors get precedence if they exist. /// This overload will reset the underlying futures. void schedule_all(transwarp::executor& executor, transwarp::schedule_type type) override { ensure_task_not_running(); schedule_all_impl(true, type, &executor); } /// Schedules all tasks in the graph for execution on the caller thread. /// The task-specific executors get precedence if they exist. /// reset_all denotes whether schedule_all should reset the underlying /// futures and schedule even if the futures are already present. void schedule_all(transwarp::schedule_type type, bool reset_all) override { ensure_task_not_running(); schedule_all_impl(reset_all, type); } /// Schedules all tasks in the graph for execution using the provided executor. /// The task-specific executors get precedence if they exist. /// reset_all denotes whether schedule_all should reset the underlying /// futures and schedule even if the futures are already present. void schedule_all(transwarp::executor& executor, transwarp::schedule_type type, bool reset_all) override { ensure_task_not_running(); schedule_all_impl(reset_all, type, &executor); } /// Assigns an exception to this task. Scheduling will have no effect after an exception /// has been set. Calling reset() will remove the exception and re-enable scheduling. void set_exception(std::exception_ptr exception) override { ensure_task_not_running(); future_ = transwarp::detail::make_future_with_exception<result_type>(exception); schedule_mode_ = false; } /// Returns whether the task was scheduled and not reset afterwards. /// This means that the underlying future is valid bool was_scheduled() const noexcept override { return future_.valid(); } /// Waits for the task to complete. Should only be called if was_scheduled() /// is true, throws transwarp::control_error otherwise void wait() const override { ensure_task_was_scheduled(); future_.wait(); } /// Returns whether the task has finished processing. Should only be called /// if was_scheduled() is true, throws transwarp::control_error otherwise bool is_ready() const override { ensure_task_was_scheduled(); return future_.wait_for(std::chrono::seconds(0)) == std::future_status::ready; } /// Returns whether this task contains a result bool has_result() const noexcept override { return was_scheduled() && future_.wait_for(std::chrono::seconds(0)) == std::future_status::ready; } /// Resets this task void reset() override { ensure_task_not_running(); future_ = std::shared_future<result_type>(); transwarp::detail::node_manip::set_canceled(*node_, false); schedule_mode_ = true; } /// Resets all tasks in the graph void reset_all() override { ensure_task_not_running(); transwarp::detail::reset_visitor visitor; visit_depth_all(visitor); } /// If enabled then this task is canceled which will /// throw transwarp::task_canceled when retrieving the task result. /// Passing false is equivalent to resume. void cancel(bool enabled) noexcept override { transwarp::detail::node_manip::set_canceled(*node_, enabled); } /// If enabled then all pending tasks in the graph are canceled which will /// throw transwarp::task_canceled when retrieving the task result. /// Passing false is equivalent to resume. void cancel_all(bool enabled) noexcept override { transwarp::detail::cancel_visitor visitor(enabled); visit_depth_all(visitor); } /// Returns the graph of the task structure. This is mainly for visualizing /// the tasks and their interdependencies. Pass the result into transwarp::to_string /// to retrieve a dot-style graph representation for easy viewing. std::vector<transwarp::edge> get_graph() const override { std::vector<transwarp::edge> graph; transwarp::detail::graph_visitor visitor(graph); const_cast<task_impl_base*>(this)->visit_depth_all(visitor); return graph; } protected: template<typename F> task_impl_base(bool has_name, std::string name, F&& functor, std::shared_ptr<transwarp::task<ParentResults>>... parents) : node_(new transwarp::node), functor_(std::forward<F>(functor)), parents_(std::move(parents)...) { init(has_name, std::move(name)); } template<typename F, typename P> task_impl_base(bool has_name, std::string name, F&& functor, std::vector<std::shared_ptr<transwarp::task<P>>> parents) : node_(new transwarp::node), functor_(std::forward<F>(functor)), parents_(std::move(parents)) { if (parents_.empty()) { throw transwarp::invalid_parameter("parents are empty"); } init(has_name, std::move(name)); } void init(bool has_name, std::string name) { transwarp::detail::node_manip::set_type(*node_, task_type::value); transwarp::detail::node_manip::set_name(*node_, (has_name ? std::shared_ptr<std::string>(new std::string(std::move(name))) : nullptr)); transwarp::detail::assign_node_if(functor_, node_); transwarp::detail::call_with_each(transwarp::detail::parent_visitor(*node_), parents_); transwarp::detail::final_visitor visitor; visit_depth(visitor); unvisit(); } /// Checks if the task is currently running and throws transwarp::control_error if it is void ensure_task_not_running() const { if (future_.valid() && future_.wait_for(std::chrono::seconds(0)) != std::future_status::ready) { throw transwarp::control_error("task currently running: " + transwarp::to_string(*node_, " ")); } } /// Checks if the task was scheduled and throws transwarp::control_error if it's not void ensure_task_was_scheduled() const { if (!future_.valid()) { throw transwarp::control_error("task was not scheduled: " + transwarp::to_string(*node_, " ")); } } bool schedule_mode_ = true; std::shared_future<result_type> future_; private: template<typename R, typename Y, typename T, typename P> friend class transwarp::detail::runner; template<typename R, typename T, typename... A> friend R transwarp::detail::run_task(std::size_t, const std::weak_ptr<T>&, A&&...); /// Assigns the given id to the node void set_node_id(std::size_t id) noexcept override { transwarp::detail::node_manip::set_id(*node_, id); } /// Schedules this task for execution using the provided executor. /// The task-specific executor gets precedence if it exists. /// Runs the task on the same thread as the caller if neither the global /// nor the task-specific executor is found. void schedule_impl(bool reset, transwarp::executor* executor=nullptr) override { if (schedule_mode_ && (reset || !future_.valid())) { if (reset) { transwarp::detail::node_manip::set_canceled(*node_, false); } std::weak_ptr<task_impl_base> self = this->shared_from_this(); using runner_t = transwarp::detail::runner<result_type, task_type, task_impl_base, decltype(parents_)>; std::shared_ptr<runner_t> runner = std::shared_ptr<runner_t>(new runner_t(node_->get_id(), self, parents_)); raise_event(transwarp::event_type::before_scheduled); future_ = runner->get_future(); if (executor_) { executor_->execute([runner]{ (*runner)(); }, node_); } else if (executor) { executor->execute([runner]{ (*runner)(); }, node_); } else { (*runner)(); } } } /// Schedules all tasks in the graph for execution using the provided executor. /// The task-specific executors get precedence if they exist. /// Runs tasks on the same thread as the caller if neither the global /// nor a task-specific executor is found. void schedule_all_impl(bool reset_all, transwarp::schedule_type type, transwarp::executor* executor=nullptr) { transwarp::detail::schedule_visitor visitor(reset_all, executor); switch (type) { case transwarp::schedule_type::breadth: visit_breadth_all(visitor); break; case transwarp::schedule_type::depth: visit_depth_all(visitor); break; default: throw transwarp::invalid_parameter("schedule type"); } } /// Visits all tasks in a breadth-first traversal. template<typename Visitor> void visit_breadth_all(Visitor& visitor) { if (breadth_tasks_.empty()) { breadth_tasks_.reserve(node_->get_id() + 1); visit_depth(transwarp::detail::push_task_visitor(breadth_tasks_)); unvisit(); auto compare = [](const transwarp::itask* const l, const transwarp::itask* const r) { const std::size_t l_level = l->get_node()->get_level(); const std::size_t l_id = l->get_node()->get_id(); const std::size_t r_level = r->get_node()->get_level(); const std::size_t r_id = r->get_node()->get_id(); return std::tie(l_level, l_id) < std::tie(r_level, r_id); }; std::sort(breadth_tasks_.begin(), breadth_tasks_.end(), compare); } for (transwarp::itask* task : breadth_tasks_) { visitor(*task); } } /// Visits all tasks in a depth-first traversal. template<typename Visitor> void visit_depth_all(Visitor& visitor) { if (depth_tasks_.empty()) { depth_tasks_.reserve(node_->get_id() + 1); visit_depth(transwarp::detail::push_task_visitor(depth_tasks_)); unvisit(); } for (transwarp::itask* task : depth_tasks_) { visitor(*task); } } /// Visits each task in a depth-first traversal. void visit_depth(const std::function<void(transwarp::itask&)>& visitor) override { if (!visited_) { transwarp::detail::call_with_each(transwarp::detail::visit_depth_visitor(visitor), parents_); visitor(*this); visited_ = true; } } /// Traverses through each task and marks them as not visited. void unvisit() noexcept override { if (visited_) { visited_ = false; transwarp::detail::call_with_each(transwarp::detail::unvisit_visitor(), parents_); } } /// Returns the index for a given event type std::size_t get_event_index(transwarp::event_type event) const { const std::size_t index = static_cast<std::size_t>(event); if (index >= static_cast<std::size_t>(transwarp::event_type::count)) { throw transwarp::invalid_parameter("event type"); } return index; } /// Raises the given event to all listeners void raise_event(transwarp::event_type event) const { for (const std::shared_ptr<transwarp::listener>& listener : listeners_[static_cast<std::size_t>(event)]) { listener->handle_event(event, node_); } } /// Check for non-null listener pointer void check_listener(const std::shared_ptr<transwarp::listener>& listener) const { if (!listener) { throw transwarp::invalid_parameter("listener pointer"); } } std::shared_ptr<transwarp::node> node_; Functor functor_; typename transwarp::detail::parents<ParentResults...>::type parents_; bool visited_ = false; std::shared_ptr<transwarp::executor> executor_; std::vector<std::shared_ptr<transwarp::listener>> listeners_[static_cast<std::size_t>(transwarp::event_type::count)]; std::vector<transwarp::itask*> depth_tasks_; std::vector<transwarp::itask*> breadth_tasks_; }; /// A task proxy template<typename ResultType, typename TaskType, typename Functor, typename... ParentResults> class task_impl_proxy : public transwarp::detail::task_impl_base<ResultType, TaskType, Functor, ParentResults...> { public: /// The task type using task_type = TaskType; /// The result type of this task using result_type = ResultType; /// Assigns a value to this task. Scheduling will have no effect after a value /// has been set. Calling reset() will remove the value and re-enable scheduling. void set_value(const typename transwarp::decay<result_type>::type& value) override { this->ensure_task_not_running(); this->future_ = transwarp::detail::make_future_with_value<result_type>(value); this->schedule_mode_ = false; } /// Assigns a value to this task. Scheduling will have no effect after a value /// has been set. Calling reset() will remove the value and re-enable scheduling. void set_value(typename transwarp::decay<result_type>::type&& value) override { this->ensure_task_not_running(); this->future_ = transwarp::detail::make_future_with_value<result_type>(std::move(value)); this->schedule_mode_ = false; } /// Returns the result of this task. Throws any exceptions that the underlying /// functor throws. Should only be called if was_scheduled() is true, /// throws transwarp::control_error otherwise typename transwarp::result<result_type>::type get() const override { this->ensure_task_was_scheduled(); return this->future_.get(); } protected: template<typename F> task_impl_proxy(bool has_name, std::string name, F&& functor, std::shared_ptr<transwarp::task<ParentResults>>... parents) : transwarp::detail::task_impl_base<result_type, task_type, Functor, ParentResults...>(has_name, std::move(name), std::forward<F>(functor), std::move(parents)...) {} template<typename F, typename P> task_impl_proxy(bool has_name, std::string name, F&& functor, std::vector<std::shared_ptr<transwarp::task<P>>> parents) : transwarp::detail::task_impl_base<result_type, task_type, Functor, ParentResults...>(has_name, std::move(name), std::forward<F>(functor), std::move(parents)) {} }; /// A task proxy for reference result type. template<typename ResultType, typename TaskType, typename Functor, typename... ParentResults> class task_impl_proxy<ResultType&, TaskType, Functor, ParentResults...> : public transwarp::detail::task_impl_base<ResultType&, TaskType, Functor, ParentResults...> { public: /// The task type using task_type = TaskType; /// The result type of this task using result_type = ResultType&; /// Assigns a value to this task. Scheduling will have no effect after a value /// has been set. Calling reset() will remove the value and re-enable scheduling. void set_value(typename transwarp::decay<result_type>::type& value) override { this->ensure_task_not_running(); this->future_ = transwarp::detail::make_future_with_value<result_type>(value); this->schedule_mode_ = false; } /// Returns the result of this task. Throws any exceptions that the underlying /// functor throws. Should only be called if was_scheduled() is true, /// throws transwarp::control_error otherwise typename transwarp::result<result_type>::type get() const override { this->ensure_task_was_scheduled(); return this->future_.get(); } protected: template<typename F> task_impl_proxy(bool has_name, std::string name, F&& functor, std::shared_ptr<transwarp::task<ParentResults>>... parents) : transwarp::detail::task_impl_base<result_type, task_type, Functor, ParentResults...>(has_name, std::move(name), std::forward<F>(functor), std::move(parents)...) {} template<typename F, typename P> task_impl_proxy(bool has_name, std::string name, F&& functor, std::vector<std::shared_ptr<transwarp::task<P>>> parents) : transwarp::detail::task_impl_base<result_type, task_type, Functor, ParentResults...>(has_name, std::move(name), std::forward<F>(functor), std::move(parents)) {} }; /// A task proxy for void result type. template<typename TaskType, typename Functor, typename... ParentResults> class task_impl_proxy<void, TaskType, Functor, ParentResults...> : public transwarp::detail::task_impl_base<void, TaskType, Functor, ParentResults...> { public: /// The task type using task_type = TaskType; /// The result type of this task using result_type = void; /// Assigns a value to this task. Scheduling will have no effect after a call /// to this. Calling reset() will reset this and re-enable scheduling. void set_value() override { this->ensure_task_not_running(); this->future_ = transwarp::detail::make_ready_future(); this->schedule_mode_ = false; } /// Blocks until the task finishes. Throws any exceptions that the underlying /// functor throws. Should only be called if was_scheduled() is true, /// throws transwarp::control_error otherwise void get() const override { this->ensure_task_was_scheduled(); this->future_.get(); } protected: template<typename F> task_impl_proxy(bool has_name, std::string name, F&& functor, std::shared_ptr<transwarp::task<ParentResults>>... parents) : transwarp::detail::task_impl_base<result_type, task_type, Functor, ParentResults...>(has_name, std::move(name), std::forward<F>(functor), std::move(parents)...) {} template<typename F, typename P> task_impl_proxy(bool has_name, std::string name, F&& functor, std::vector<std::shared_ptr<transwarp::task<P>>> parents) : transwarp::detail::task_impl_base<result_type, task_type, Functor, ParentResults...>(has_name, std::move(name), std::forward<F>(functor), std::move(parents)) {} }; } // detail /// A task representing a piece of work given by functor and parent tasks. /// By connecting tasks a directed acyclic graph is built. /// Tasks should be created using the make_task factory functions. template<typename TaskType, typename Functor, typename... ParentResults> class task_impl : public transwarp::detail::task_impl_proxy<typename transwarp::detail::functor_result<TaskType, Functor, ParentResults...>::type, TaskType, Functor, ParentResults...> { public: /// The task type using task_type = TaskType; /// The result type of this task using result_type = typename transwarp::detail::functor_result<TaskType, Functor, ParentResults...>::type; /// A task is defined by name, functor, and parent tasks. /// Note: Don't use this constructor directly, use transwarp::make_task template<typename F> task_impl(bool has_name, std::string name, F&& functor, std::shared_ptr<transwarp::task<ParentResults>>... parents) : transwarp::detail::task_impl_proxy<result_type, task_type, Functor, ParentResults...>(has_name, std::move(name), std::forward<F>(functor), std::move(parents)...) {} /// A task is defined by name, functor, and parent tasks. /// Note: Don't use this constructor directly, use transwarp::make_task template<typename F, typename P> task_impl(bool has_name, std::string name, F&& functor, std::vector<std::shared_ptr<transwarp::task<P>>> parents) : transwarp::detail::task_impl_proxy<result_type, task_type, Functor, ParentResults...>(has_name, std::move(name), std::forward<F>(functor), std::move(parents)) {} // delete copy/move semantics task_impl(const task_impl&) = delete; task_impl& operator=(const task_impl&) = delete; task_impl(task_impl&&) = delete; task_impl& operator=(task_impl&&) = delete; /// Creates a continuation to this task template<typename TaskType_, typename Functor_> std::shared_ptr<transwarp::task_impl<TaskType_, typename std::decay<Functor_>::type, result_type>> then(TaskType_, std::string name, Functor_&& functor) const { using task_t = transwarp::task_impl<TaskType_, typename std::decay<Functor_>::type, result_type>; return std::shared_ptr<task_t>(new task_t(true, std::move(name), std::forward<Functor_>(functor), std::dynamic_pointer_cast<transwarp::task<result_type>>(const_cast<task_impl*>(this)->shared_from_this()))); } /// Creates a continuation to this task. Overload for omitting for task name template<typename TaskType_, typename Functor_> std::shared_ptr<transwarp::task_impl<TaskType_, typename std::decay<Functor_>::type, result_type>> then(TaskType_, Functor_&& functor) const { using task_t = transwarp::task_impl<TaskType_, typename std::decay<Functor_>::type, result_type>; return std::shared_ptr<task_t>(new task_t(false, "", std::forward<Functor_>(functor), std::dynamic_pointer_cast<transwarp::task<result_type>>(const_cast<task_impl*>(this)->shared_from_this()))); } }; /// A value task that stores a single value and doesn't require scheduling. /// Value tasks should be created using the make_value_task factory functions. template<typename ResultType> class value_task : public transwarp::task<ResultType>, public std::enable_shared_from_this<value_task<ResultType>> { public: /// The task type using task_type = transwarp::root_type; /// The result type of this task using result_type = ResultType; /// A value task is defined by name and value. /// Note: Don't use this constructor directly, use transwarp::make_value_task template<typename T> value_task(bool has_name, std::string name, T&& value) : node_(new transwarp::node), future_(transwarp::detail::make_future_with_value<result_type>(std::forward<T>(value))) { transwarp::detail::node_manip::set_type(*node_, task_type::value); transwarp::detail::node_manip::set_name(*node_, (has_name ? std::shared_ptr<std::string>(new std::string(std::move(name))) : nullptr)); } // delete copy/move semantics value_task(const value_task&) = delete; value_task& operator=(const value_task&) = delete; value_task(value_task&&) = delete; value_task& operator=(value_task&&) = delete; /// Creates a continuation to this task template<typename TaskType_, typename Functor_> std::shared_ptr<transwarp::task_impl<TaskType_, typename std::decay<Functor_>::type, result_type>> then(TaskType_, std::string name, Functor_&& functor) const { using task_t = transwarp::task_impl<TaskType_, typename std::decay<Functor_>::type, result_type>; return std::shared_ptr<task_t>(new task_t(true, std::move(name), std::forward<Functor_>(functor), std::dynamic_pointer_cast<transwarp::task<result_type>>(const_cast<value_task*>(this)->shared_from_this()))); } /// Creates a continuation to this task. Overload for omitting the task name template<typename TaskType_, typename Functor_> std::shared_ptr<transwarp::task_impl<TaskType_, typename std::decay<Functor_>::type, result_type>> then(TaskType_, Functor_&& functor) const { using task_t = transwarp::task_impl<TaskType_, typename std::decay<Functor_>::type, result_type>; return std::shared_ptr<task_t>(new task_t(false, "", std::forward<Functor_>(functor), std::dynamic_pointer_cast<transwarp::task<result_type>>(const_cast<value_task*>(this)->shared_from_this()))); } /// No-op because a value task never runs void set_executor(std::shared_ptr<transwarp::executor>) override {} /// No-op because a value task never runs and doesn't have parents void set_executor_all(std::shared_ptr<transwarp::executor>) override {} /// No-op because a value task never runs void remove_executor() override {} /// No-op because a value task never runs and doesn't have parents void remove_executor_all() override {} /// Sets a task priority (defaults to 0). transwarp will not directly use this. /// This is only useful if something else is using the priority void set_priority(std::size_t priority) override { transwarp::detail::node_manip::set_priority(*node_, priority); } /// Sets a priority to all tasks (defaults to 0). transwarp will not directly use this. /// This is only useful if something else is using the priority void set_priority_all(std::size_t priority) override { set_priority(priority); } /// Resets the task priority to 0 void reset_priority() override { transwarp::detail::node_manip::set_priority(*node_, 0); } /// Resets the priority of all tasks to 0 void reset_priority_all() override { reset_priority(); } /// Assigns custom data to this task. transwarp will not directly use this. /// This is only useful if something else is using this custom data void set_custom_data(std::shared_ptr<void> custom_data) override { if (!custom_data) { throw transwarp::invalid_parameter("custom data pointer"); } transwarp::detail::node_manip::set_custom_data(*node_, std::move(custom_data)); } /// Assigns custom data to all tasks. transwarp will not directly use this. /// This is only useful if something else is using this custom data void set_custom_data_all(std::shared_ptr<void> custom_data) override { set_custom_data(std::move(custom_data)); } /// Removes custom data from this task void remove_custom_data() override { transwarp::detail::node_manip::set_custom_data(*node_, nullptr); } /// Removes custom data from all tasks void remove_custom_data_all() override { remove_custom_data(); } /// Returns the future associated to the underlying execution const std::shared_future<result_type>& get_future() const noexcept override { return future_; } /// Returns the associated node const std::shared_ptr<transwarp::node>& get_node() const noexcept override { return node_; } /// No-op because a value task doesn't raise events void add_listener(std::shared_ptr<transwarp::listener>) override {} /// No-op because a value task doesn't raise events void add_listener(transwarp::event_type, std::shared_ptr<transwarp::listener>) override {} /// No-op because a value task doesn't raise events void add_listener_all(std::shared_ptr<transwarp::listener>) override {} /// No-op because a value task doesn't raise events void add_listener_all(transwarp::event_type, std::shared_ptr<transwarp::listener>) override {} /// No-op because a value task doesn't raise events void remove_listener(const std::shared_ptr<transwarp::listener>&) override {} /// No-op because a value task doesn't raise events void remove_listener(transwarp::event_type, const std::shared_ptr<transwarp::listener>&) override {} /// No-op because a value task doesn't raise events void remove_listener_all(const std::shared_ptr<transwarp::listener>&) override {} /// No-op because a value task doesn't raise events void remove_listener_all(transwarp::event_type, const std::shared_ptr<transwarp::listener>&) override {} /// No-op because a value task doesn't raise events void remove_listeners() override {} /// No-op because a value task doesn't raise events void remove_listeners(transwarp::event_type) override {} /// No-op because a value task doesn't raise events void remove_listeners_all() override {} /// No-op because a value task doesn't raise events void remove_listeners_all(transwarp::event_type) override {} /// No-op because a value task never runs void schedule() override {} /// No-op because a value task never runs void schedule(transwarp::executor&) override {} /// No-op because a value task never runs void schedule(bool) override {} /// No-op because a value task never runs void schedule(transwarp::executor&, bool) override {} /// No-op because a value task never runs and doesn't have parents void schedule_all() override {} /// No-op because a value task never runs and doesn't have parents void schedule_all(transwarp::executor&) override {} /// No-op because a value task never runs and doesn't have parents void schedule_all(bool) override {} /// No-op because a value task never runs and doesn't have parents void schedule_all(transwarp::executor&, bool) override {} /// No-op because a value task never runs and doesn't have parents void schedule_all(transwarp::schedule_type) override {} /// No-op because a value task never runs and doesn't have parents void schedule_all(transwarp::executor&, transwarp::schedule_type) override {} /// No-op because a value task never runs and doesn't have parents void schedule_all(transwarp::schedule_type, bool) override {} /// No-op because a value task never runs and doesn't have parents void schedule_all(transwarp::executor&, transwarp::schedule_type, bool) override {} /// Assigns a value to this task void set_value(const typename transwarp::decay<result_type>::type& value) override { future_ = transwarp::detail::make_future_with_value<result_type>(value); } /// Assigns a value to this task void set_value(typename transwarp::decay<result_type>::type&& value) override { future_ = transwarp::detail::make_future_with_value<result_type>(std::move(value)); }; /// Assigns an exception to this task void set_exception(std::exception_ptr exception) override { future_ = transwarp::detail::make_future_with_exception<result_type>(exception); } /// Returns true because a value task is scheduled once on construction bool was_scheduled() const noexcept override { return true; } /// No-op because a value task never runs void wait() const override {} /// Returns true because a value task is always ready bool is_ready() const override { return true; } /// Returns true because a value task always contains a result bool has_result() const noexcept override { return true; } /// Returns the result of this task typename transwarp::result<result_type>::type get() const override { return future_.get(); } /// No-op because a value task never runs void reset() override {} /// No-op because a value task never runs and doesn't have parents void reset_all() override {} /// No-op because a value task never runs void cancel(bool) noexcept override {} /// No-op because a value task never runs and doesn't have parents void cancel_all(bool) noexcept override {} /// Returns an empty graph because a value task doesn't have parents std::vector<transwarp::edge> get_graph() const override { return {}; } private: /// Assigns the given id to the node void set_node_id(std::size_t id) noexcept override { transwarp::detail::node_manip::set_id(*node_, id); } /// No-op because a value task never runs void schedule_impl(bool, transwarp::executor*) override {} /// Visits this task void visit_depth(const std::function<void(transwarp::itask&)>& visitor) override { if (!visited_) { visitor(*this); visited_ = true; } } /// Marks this task as not visited void unvisit() noexcept override { visited_ = false; } std::shared_ptr<transwarp::node> node_; std::shared_future<result_type> future_; bool visited_ = false; }; /// A factory function to create a new task template<typename TaskType, typename Functor, typename... Parents> std::shared_ptr<transwarp::task_impl<TaskType, typename std::decay<Functor>::type, typename Parents::result_type...>> make_task(TaskType, std::string name, Functor&& functor, std::shared_ptr<Parents>... parents) { using task_t = transwarp::task_impl<TaskType, typename std::decay<Functor>::type, typename Parents::result_type...>; return std::shared_ptr<task_t>(new task_t(true, std::move(name), std::forward<Functor>(functor), std::move(parents)...)); } /// A factory function to create a new task. Overload for omitting the task name template<typename TaskType, typename Functor, typename... Parents> std::shared_ptr<transwarp::task_impl<TaskType, typename std::decay<Functor>::type, typename Parents::result_type...>> make_task(TaskType, Functor&& functor, std::shared_ptr<Parents>... parents) { using task_t = transwarp::task_impl<TaskType, typename std::decay<Functor>::type, typename Parents::result_type...>; return std::shared_ptr<task_t>(new task_t(false, "", std::forward<Functor>(functor), std::move(parents)...)); } /// A factory function to create a new task with vector parents template<typename TaskType, typename Functor, typename ParentType> std::shared_ptr<transwarp::task_impl<TaskType, typename std::decay<Functor>::type, std::vector<ParentType>>> make_task(TaskType, std::string name, Functor&& functor, std::vector<ParentType> parents) { using task_t = transwarp::task_impl<TaskType, typename std::decay<Functor>::type, std::vector<ParentType>>; return std::shared_ptr<task_t>(new task_t(true, std::move(name), std::forward<Functor>(functor), std::move(parents))); } /// A factory function to create a new task with vector parents. Overload for omitting the task name template<typename TaskType, typename Functor, typename ParentType> std::shared_ptr<transwarp::task_impl<TaskType, typename std::decay<Functor>::type, std::vector<ParentType>>> make_task(TaskType, Functor&& functor, std::vector<ParentType> parents) { using task_t = transwarp::task_impl<TaskType, typename std::decay<Functor>::type, std::vector<ParentType>>; return std::shared_ptr<task_t>(new task_t(false, "", std::forward<Functor>(functor), std::move(parents))); } /// A factory function to create a new value task template<typename Value> std::shared_ptr<transwarp::value_task<typename transwarp::decay<Value>::type>> make_value_task(std::string name, Value&& value) { using task_t = transwarp::value_task<typename transwarp::decay<Value>::type>; return std::shared_ptr<task_t>(new task_t(true, std::move(name), std::forward<Value>(value))); } /// A factory function to create a new value task. Overload for omitting the task name template<typename Value> std::shared_ptr<transwarp::value_task<typename transwarp::decay<Value>::type>> make_value_task(Value&& value) { using task_t = transwarp::value_task<typename transwarp::decay<Value>::type>; return std::shared_ptr<task_t>(new task_t(false, "", std::forward<Value>(value))); } /// A graph interface giving access to the final task as required by transwarp::graph_pool template<typename ResultType> class graph { public: using result_type = ResultType; virtual ~graph() = default; /// Returns the final task of the graph virtual const std::shared_ptr<transwarp::task<result_type>>& final_task() const = 0; }; /// A graph pool that allows running multiple instances of the same graph in parallel. /// Graph must be a sub-class of transwarp::graph template<typename Graph> class graph_pool { public: static_assert(std::is_base_of<transwarp::graph<typename Graph::result_type>, Graph>::value, "Graph must be a sub-class of transwarp::graph"); /// Constructs a graph pool by passing a generator to create a new graph /// and a minimum and maximum size of the pool. The minimum size is used as /// the initial size of the pool. Graph should be a subclass of transwarp::graph graph_pool(std::function<std::shared_ptr<Graph>()> generator, std::size_t minimum_size, std::size_t maximum_size) : generator_(std::move(generator)), minimum_(minimum_size), maximum_(maximum_size), finished_(maximum_size) { if (minimum_ < 1) { throw transwarp::invalid_parameter("minimum size"); } if (minimum_ > maximum_) { throw transwarp::invalid_parameter("minimum or maximum size"); } for (std::size_t i=0; i<minimum_; ++i) { idle_.push(generate()); } } // delete copy/move semantics graph_pool(const graph_pool&) = delete; graph_pool& operator=(const graph_pool&) = delete; graph_pool(graph_pool&&) = delete; graph_pool& operator=(graph_pool&&) = delete; /// Returns the next idle graph. /// If there are no idle graphs then it will attempt to double the /// pool size. If that fails then it will return a nullptr. On successful /// retrieval of an idle graph the function will mark that graph as busy. std::shared_ptr<Graph> next_idle_graph(bool maybe_resize=true) { std::shared_ptr<transwarp::node> finished_node; { std::lock_guard<transwarp::detail::spinlock> lock(spinlock_); if (!finished_.empty()) { finished_node = finished_.front(); finished_.pop(); } } std::shared_ptr<Graph> g; if (finished_node) { g = busy_.find(finished_node)->second; } else { if (maybe_resize && idle_.empty()) { resize(size() * 2); // double pool size } if (idle_.empty()) { return nullptr; } g = idle_.front(); idle_.pop(); busy_.emplace(g->final_task()->get_node(), g); } const auto& future = g->final_task()->get_future(); if (future.valid()) { future.wait(); // will return immediately } return g; } /// Just like next_idle_graph() but waits for a graph to become available. /// The returned graph will always be a valid pointer std::shared_ptr<Graph> wait_for_next_idle_graph(bool maybe_resize=true) { for (;;) { std::shared_ptr<Graph> g = next_idle_graph(maybe_resize); if (g) { return g; } } } /// Returns the current total size of the pool (sum of idle and busy graphs) std::size_t size() const { return idle_.size() + busy_.size(); } /// Returns the minimum size of the pool std::size_t minimum_size() const { return minimum_; } /// Returns the maximum size of the pool std::size_t maximum_size() const { return maximum_; } /// Returns the number of idle graphs in the pool std::size_t idle_count() const { std::lock_guard<transwarp::detail::spinlock> lock(spinlock_); return idle_.size() + finished_.size(); } /// Returns the number of busy graphs in the pool std::size_t busy_count() const { std::lock_guard<transwarp::detail::spinlock> lock(spinlock_); return busy_.size() - finished_.size(); } /// Resizes the graph pool to the given new size if possible void resize(std::size_t new_size) { reclaim(); if (new_size > size()) { // grow const std::size_t count = new_size - size(); for (std::size_t i=0; i<count; ++i) { if (size() == maximum_) { break; } idle_.push(generate()); } } else if (new_size < size()) { // shrink const std::size_t count = size() - new_size; for (std::size_t i=0; i<count; ++i) { if (idle_.empty() || size() == minimum_) { break; } idle_.pop(); } } } /// Reclaims finished graphs by marking them as idle again void reclaim() { decltype(finished_) finished{finished_.capacity()}; { std::lock_guard<transwarp::detail::spinlock> lock(spinlock_); finished_.swap(finished); } while (!finished.empty()) { const std::shared_ptr<transwarp::node> node = finished.front(); finished.pop(); const auto it = busy_.find(node); idle_.push(it->second); busy_.erase(it); } } private: class finished_listener : public transwarp::listener { public: explicit finished_listener(graph_pool<Graph>& pool) : pool_(pool) {} // Called on a potentially high-priority thread void handle_event(transwarp::event_type, const std::shared_ptr<transwarp::node>& node) override { std::lock_guard<transwarp::detail::spinlock> lock(pool_.spinlock_); pool_.finished_.push(node); } private: graph_pool<Graph>& pool_; }; std::shared_ptr<Graph> generate() { std::shared_ptr<Graph> graph = generator_(); graph->final_task()->add_listener(transwarp::event_type::after_finished, listener_); return graph; } std::function<std::shared_ptr<Graph>()> generator_; std::size_t minimum_; std::size_t maximum_; mutable transwarp::detail::spinlock spinlock_; // protecting finished_ transwarp::detail::circular_buffer<std::shared_ptr<transwarp::node>> finished_; std::queue<std::shared_ptr<Graph>> idle_; std::unordered_map<std::shared_ptr<transwarp::node>, std::shared_ptr<Graph>> busy_; std::shared_ptr<transwarp::listener> listener_{new finished_listener(*this)}; }; /// A timer that tracks the average waittime and runtime of each task it listens to class timer : public transwarp::listener { public: timer() = default; // delete copy/move semantics timer(const timer&) = delete; timer& operator=(const timer&) = delete; timer(timer&&) = delete; timer& operator=(timer&&) = delete; /// Performs the actual timing and populates the node's average waittime and runtime member void handle_event(transwarp::event_type event, const std::shared_ptr<transwarp::node>& node) override { if (event == transwarp::event_type::before_started) { const std::chrono::time_point<std::chrono::steady_clock> now = std::chrono::steady_clock::now(); std::lock_guard<transwarp::detail::spinlock> lock(spinlock_); auto& track = tracks_[node]; track.startwait = now; } else if (event == transwarp::event_type::after_canceled) { const std::chrono::time_point<std::chrono::steady_clock> now = std::chrono::steady_clock::now(); track_waittime(node, now); } else if (event == transwarp::event_type::before_invoked) { const std::chrono::time_point<std::chrono::steady_clock> now = std::chrono::steady_clock::now(); track_waittime(node, now); std::lock_guard<transwarp::detail::spinlock> lock(spinlock_); auto& track = tracks_[node]; track.running = true; track.startrun = now; } else if (event == transwarp::event_type::after_finished) { const std::chrono::time_point<std::chrono::steady_clock> now = std::chrono::steady_clock::now(); track_runtime(node, now); } } /// Resets all timing information void reset() { std::lock_guard<transwarp::detail::spinlock> lock(spinlock_); tracks_.clear(); } private: void track_waittime(const std::shared_ptr<transwarp::node>& node, const std::chrono::time_point<std::chrono::steady_clock>& now) { std::int64_t avg_waittime_us; { std::lock_guard<transwarp::detail::spinlock> lock(spinlock_); auto& track = tracks_[node]; track.waittime += std::chrono::duration_cast<std::chrono::microseconds>(now - track.startwait).count(); ++track.waitcount; avg_waittime_us = static_cast<std::int64_t>(track.waittime / track.waitcount); } transwarp::detail::node_manip::set_avg_waittime_us(*node, avg_waittime_us); }; void track_runtime(const std::shared_ptr<transwarp::node>& node, const std::chrono::time_point<std::chrono::steady_clock>& now) { std::int64_t avg_runtime_us; { std::lock_guard<transwarp::detail::spinlock> lock(spinlock_); auto& track = tracks_[node]; if (!track.running) { return; } track.running = false; track.runtime += std::chrono::duration_cast<std::chrono::microseconds>(now - track.startrun).count(); ++track.runcount; avg_runtime_us = static_cast<std::int64_t>(track.runtime / track.runcount); } transwarp::detail::node_manip::set_avg_runtime_us(*node, avg_runtime_us); } struct track { bool running = false; std::chrono::time_point<std::chrono::steady_clock> startwait; std::chrono::time_point<std::chrono::steady_clock> startrun; std::chrono::microseconds::rep waittime = 0; std::chrono::microseconds::rep waitcount = 0; std::chrono::microseconds::rep runtime = 0; std::chrono::microseconds::rep runcount = 0; }; transwarp::detail::spinlock spinlock_; // protecting tracks_ std::unordered_map<std::shared_ptr<transwarp::node>, track> tracks_; }; } // transwarp
38.829519
215
0.681023
[ "vector" ]
5354e4d5a47620c41b5a128728de3c7c4b1940cf
1,646
h
C
include/symbolic/predicate.h
tmigimatsu/symbolic
5fab46700557412656bd84cc2396b001b6e6ad13
[ "MIT" ]
3
2021-02-16T19:57:25.000Z
2021-05-08T05:56:02.000Z
include/symbolic/predicate.h
tmigimatsu/symbolic
5fab46700557412656bd84cc2396b001b6e6ad13
[ "MIT" ]
null
null
null
include/symbolic/predicate.h
tmigimatsu/symbolic
5fab46700557412656bd84cc2396b001b6e6ad13
[ "MIT" ]
null
null
null
/** * predicate.h * * Copyright 2020. All Rights Reserved. * * Created: June 15, 2020 * Authors: Toki Migimatsu */ #ifndef SYMBOLIC_PREDICATE_H_ #define SYMBOLIC_PREDICATE_H_ #include "symbolic/action.h" namespace VAL { class pred_decl; } // namespace VAL namespace symbolic { class Predicate : public Action { public: Predicate(const Pddl& pddl, const VAL::pred_decl* symbol); const VAL::pred_decl* symbol() const { return symbol_; } /** * Predicate head. * * @seepython{symbolic.Predicate,name} */ const std::string& name() const { return name_; } /** * List of predicate parameters. * * @seepython{symbolic.Predicate,parameters} */ const std::vector<Object>& parameters() const { return parameters_; } /** * Combination generator for predicate parameters. * * @seepython{symbolic.Predicate,parameter_generator} */ const ParameterGenerator& parameter_generator() const { return param_gen_; } /** * Creates a string representation of the predicate with the default * parameters. * * @seepython{symbolic.Predicate,__repr__} */ std::string to_string() const; /** * Creates a string representation of the predicate with the given arguments. * * @seepython{symbolic.Predicate,to_string} */ std::string to_string(const std::vector<Object>& arguments) const; friend std::ostream& operator<<(std::ostream& os, const Predicate& pred); private: const VAL::pred_decl* symbol_ = nullptr; std::string name_; std::vector<Object> parameters_; ParameterGenerator param_gen_; }; } // namespace symbolic #endif // SYMBOLIC_PREDICATE_H_
21.376623
79
0.693803
[ "object", "vector" ]
535753c1a294329c57d8c698a260c3cb21f5251f
2,761
h
C
dockerdoom/trunk/src/r_state.h
scraly/kube-doom
c15b9d4dc69bfe9fe4a0bb209463c90093e8844d
[ "Apache-2.0" ]
null
null
null
dockerdoom/trunk/src/r_state.h
scraly/kube-doom
c15b9d4dc69bfe9fe4a0bb209463c90093e8844d
[ "Apache-2.0" ]
null
null
null
dockerdoom/trunk/src/r_state.h
scraly/kube-doom
c15b9d4dc69bfe9fe4a0bb209463c90093e8844d
[ "Apache-2.0" ]
null
null
null
// Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // Copyright(C) 1993-1996 Id Software, Inc. // Copyright(C) 2005 Simon Howard // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. // // DESCRIPTION: // Refresh/render internal state variables (global). // //----------------------------------------------------------------------------- #ifndef __R_STATE__ #define __R_STATE__ // Need data structure definitions. #include "d_player.h" #include "r_data.h" // // Refresh internal data structures, // for rendering. // // needed for texture pegging extern fixed_t* textureheight; // needed for pre rendering (fracs) extern fixed_t* spritewidth; extern fixed_t* spriteoffset; extern fixed_t* spritetopoffset; extern lighttable_t* colormaps; extern int viewwidth; extern int scaledviewwidth; extern int viewheight; extern int firstflat; // for global animation extern int* flattranslation; extern int* texturetranslation; // Sprite.... extern int firstspritelump; extern int lastspritelump; extern int numspritelumps; // // Lookup tables for map data. // extern int numsprites; extern spritedef_t* sprites; extern int numvertexes; extern vertex_t* vertexes; extern int numsegs; extern seg_t* segs; extern int numsectors; extern sector_t* sectors; extern int numsubsectors; extern subsector_t* subsectors; extern int numnodes; extern node_t* nodes; extern int numlines; extern line_t* lines; extern int numsides; extern side_t* sides; // // POV data. // extern fixed_t viewx; extern fixed_t viewy; extern fixed_t viewz; extern angle_t viewangle; extern player_t* viewplayer; // ? extern angle_t clipangle; extern int viewangletox[FINEANGLES/2]; extern angle_t xtoviewangle[SCREENWIDTH+1]; //extern fixed_t finetangent[FINEANGLES/2]; extern fixed_t rw_distance; extern angle_t rw_normalangle; // angle to line origin extern int rw_angle1; // Segs count? extern int sscount; extern visplane_t* floorplane; extern visplane_t* ceilingplane; #endif
20.301471
79
0.700833
[ "render" ]
53590f8deb1b12fc37f3433edc02f7cc5df90fef
671
h
C
ActorX_MAYA/BrushExport.h
galek/ActorX
96587f4f9fb14417bd493c0cd0b92871449b1900
[ "BSD-3-Clause" ]
77
2016-03-29T15:57:44.000Z
2021-12-20T07:31:47.000Z
ActorX_MAYA/BrushExport.h
galek/ActorX
96587f4f9fb14417bd493c0cd0b92871449b1900
[ "BSD-3-Clause" ]
8
2016-09-16T15:22:27.000Z
2021-09-11T08:49:58.000Z
ActorX_MAYA/BrushExport.h
galek/ActorX
96587f4f9fb14417bd493c0cd0b92871449b1900
[ "BSD-3-Clause" ]
35
2016-03-30T02:35:09.000Z
2022-02-13T12:43:48.000Z
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. // Licensed under the BSD license. See LICENSE.txt file in the project root for full license information. /************************************************************************** BrushExport.h - Maya specific, helper functions for static mesh digestion Created by Erik de Neve ***************************************************************************/ #ifdef MAYA #ifndef BRUSHEXPORT_H #define BRUSHEXPORT_H #include "MayaInclude.h" MStatus UTExportMesh( const MArgList& args ); MStatus AXWriteSequence(BOOL bUseSourceOutPath); MStatus AXWritePoses(); #endif #endif
26.84
106
0.57228
[ "mesh" ]
535c4ee711da4ec2c959a54d4efe1ea8eb3d2dd3
6,882
h
C
sdk/mac/ZoomSDK/ZoomSDK.framework/Versions/A/Headers/ZoomSDKInterpretationController.h
pramesywaraj/zoom-react-electron-implementation
94583834fe47dd29309114733c904ddcafdf928e
[ "MIT" ]
1
2021-09-08T11:49:12.000Z
2021-09-08T11:49:12.000Z
sdk/mac/ZoomSDK/ZoomSDK.framework/Versions/A/Headers/ZoomSDKInterpretationController.h
pramesywaraj/zoom-react-electron-implementation
94583834fe47dd29309114733c904ddcafdf928e
[ "MIT" ]
null
null
null
sdk/mac/ZoomSDK/ZoomSDK.framework/Versions/A/Headers/ZoomSDKInterpretationController.h
pramesywaraj/zoom-react-electron-implementation
94583834fe47dd29309114733c904ddcafdf928e
[ "MIT" ]
null
null
null
#import <Foundation/Foundation.h> #import "ZoomSDKErrors.h" NS_ASSUME_NONNULL_BEGIN @interface ZoomSDKInterpretationLanguageInfo : NSObject /** @brief Get language id. @return If the function succeeds, it will return language id. */ -(int)getLanguageID; /** @brief Get language alisa. @return If the function succeeds, it will return language alisa. */ -(NSString*)getLanguageAbbreviations; /** @brief Get language name. @return TIf the function succeeds, it will return language name. */ -(NSString*)getLanguageName; @end @interface ZoomSDKInterpreter : NSObject /** @brief Get the user ID. @return If the function succeeds, it will return user ID. */ -(int)getUserID; /** @brief Get the language id of the interpreter support. @return If the function succeeds, it will return language id. */ -(int)getLanguageID1; /** @brief Get the language id of the interpreter support. @return If the function succeeds, it will return language id. */ -(int)getLanguageID2; /** @brief Determine if the interpreter is available. @return YES means the interpreter is available and had join meeting,otherwise not. */ -(BOOL)isAvailable; @end @protocol ZoomSDKInterpretationControllerDelegate <NSObject> /** @brief Notify the interpretation is started. */ -(void)onInterpretationStart; /** @brief Notify the interpretation is stoped. */ -(void)onInterpretationStop; /** @brief Notify the interpreter role is changed. @param userID The user id of the interpreter role change. @param interpreter YES means is interpreter,otherwise not. */ -(void)onInterpreterRoleChanged:(unsigned int)userID isInterpreter:(BOOL)interpreter; /** @brief Notify the interpreter role is changed. @param userID The user id of the interpreter. @param languageID The current active language id. */ -(void)onInterpreterActiveLanuageChanged:(unsigned int)userID activeLanguageID:(int)languageID; /** @brief Notify the interpreter language changed. @param lanID1 The language id of the first language id. @param lanID2 The language id of the second language id. */ -(void)onInterpreterLanuageChanged:(int)lanID1 theLanguageID2:(int)lanID2; /** @brief Notify the available language. @param availableLanguageArr The array contain available language object (The language object is ZoomSDKInterpretationLanguageInfo). */ -(void)onAvailableLanguageListUpdated:(NSArray*)availableLanguageArr; /** @brief Notify the interpreter list changed. */ -(void)onInterpreterListChanged; @end @interface ZoomSDKInterpretationController : NSObject @property(nonatomic,assign)id<ZoomSDKInterpretationControllerDelegate> delegate; /** @brief Determine if the interpretation function is enabled. @return YES means interpretation function is enable,otherwise not. */ -(BOOL)isInterpretationEnabled; /** @brief Determine if the interpretation function is started. @return YES means interpretation is started,otherwise not. */ -(BOOL)isInterpretationStarted; /** @brief Determine if self is interpreter. @return YES means self is interpreter,otherwise not. */ -(BOOL)isInterpreter; /** @brief Get interpretation language. @param languageID The id of language. @return If the function succeeds, the return value is ZoomSDKInterpretationLanguageInfo object. */ -(ZoomSDKInterpretationLanguageInfo*)getInterpretationLanguageByID:(int)languageID; /** @brief Get all language list of interpretation support. @return If the function succeeds, the return array contain language object.(The language object is ZoomSDKInterpretationLanguageInfo) */ -(NSArray*)getAllLanguageList; /** @brief Get all interpreter list. @return If the function succeeds, the return array contain interpreter object.(The language object is ZoomSDKInterpreter) */ -(NSArray*)getAllInterpreterList; /** @brief Add interpreter. @param userID The unique identity of the user. @param lanID1 The id of language. @param lanID2 The id of language. @return If the function succeeds, it will return ZoomSDKError_succuss, otherwise not. */ -(ZoomSDKError)addInterpreter:(unsigned int)userID languageID1:(int)lanID1 languageID2:(int)lanID2; /** @brief Remove interpreter. @param userID The unique identity of the user. @return If the function succeeds, it will return ZoomSDKError_succuss, otherwise not. */ -(ZoomSDKError)removeInterpreter:(unsigned int)userID; /** @brief Modify interpreter suport language. @param userID The unique identity of the user. @param lanID1 The id of language. @param lanID2 The id of language. @return If the function succeeds, it will return ZoomSDKError_succuss, otherwise not. */ -(ZoomSDKError)modifyInterpreter:(unsigned int)userID languageID1:(int)lanID1 languageID2:(int)lanID2; /** @brief Start interppretation. @return If the function succeeds, it will return ZoomSDKError_succuss, otherwise not. */ -(ZoomSDKError)startInterpretation; /** @brief Stop interppretation. @return If the function succeeds, it will return ZoomSDKError_succuss, otherwise not. */ -(ZoomSDKError)StopInterpretation; /** @brief Get available language list. @return The array contain available language object (The language object is ZoomSDKInterpretationLanguageInfo). */ -(NSArray*)getAvailableLanguageList; /** @brief Join language channel by language id. @param languageID The language id. @return If the function succeeds, it will return ZoomSDKError_succuss, otherwise not. @note LanguageID is -1 means join major meeting. */ -(ZoomSDKError)joinLanguageChannel:(int)languageID; /** @brief Get the language id of user joined. @return If the function succeeds, it will return language id. */ -(int)getJoinedLanguageID; /** @brief Turn off the major meeting audio. @return If the function succeeds, it will return ZoomSDKError_succuss, otherwise not. */ -(ZoomSDKError)turnOffMajorAudio; /** @brief Turn on the major meeting audio. @return If the function succeeds, it will return ZoomSDKError_succuss, otherwise not. */ -(ZoomSDKError)turnOnMajorAudio; /** @brief Determine if major audio is turn off. @return YES means major audio is turn off,otherwise not. */ -(BOOL)isMajorAudioTurnOff; /** @brief Get interpreter support language. @param lanID1 The id is interpreter first language. @param lanID2 The id is interpreter second language. @return If the function succeeds, it will return ZoomSDKError_succuss, otherwise not. */ -(ZoomSDKError)getInterpreterLans:(int*)lanID1 languageID2:(int*)lanID2; /** @brief Set interpreter active language. @param activeLanID The id of language id. @return If the function succeeds, it will return ZoomSDKError_succuss, otherwise not. */ -(ZoomSDKError)setInterpreterActiveLan:(int)activeLanID; /** @brief Get interpreter current active language id. @return If the function succeeds, it will return language id. */ -(int)getInterpreterActiveLanID; @end NS_ASSUME_NONNULL_END
28.794979
134
0.774629
[ "object" ]
536829844d8ecb216c047d4f0f8c54ac8546de7d
2,135
h
C
copasi/sbmlunit/Expression2PresentationMML.h
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
copasi/sbmlunit/Expression2PresentationMML.h
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
copasi/sbmlunit/Expression2PresentationMML.h
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
// Begin CVS Header // $Source: /fs/turing/cvs/copasi_dev/cvs_admin/addHeader,v $ // $Revision: 1.10 $ // $Name: $ // $Author: shoops $ // $Date: 2008/04/11 15:21:36 $ // End CVS Header // Copyright (C) 2011 - 2010 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Sven Sahle and University of Heidelberg // All rights reserved. #ifndef EXPRESSION2PRESENTATIONMML_H #define EXPRESSION2PRESENTATIONMML_H #include <iostream> class ASTNode; class Model; class Reaction; class Expression2PresentationMML { public: Expression2PresentationMML(const ASTNode* rootnode); virtual ~Expression2PresentationMML() {}; void setModel(const Model* m) {mpModel = m;}; /** * set the reaction to be used as the environment for finding local parameters */ void setReaction(const Reaction* m) {mpReaction = m;}; /** * If this is set to true (the default) the actual name/id of a reaction is added * to the name of local parameter. This may lead to rather long expressions. * In cases where the reaction is identifiable by other means it should be set to false * for more compact expression display. */ void setUseReactionNameInLocalParameters(bool b) {mUseReactionNameInLocalParameters = b;}; void writeMathML(std::ostream & out) const; protected: void writeMathML(std::ostream & out, const ASTNode* node, size_t l) const; virtual void writeMathMLFunction(std::ostream & out, const ASTNode* node, size_t l) const; virtual void writeMathMLName(std::ostream & out, const ASTNode* node, size_t l) const; virtual void writeMathMLNumber(std::ostream & out, const ASTNode* node, size_t l) const; const ASTNode* mRootNode; const Model* mpModel; const Reaction* mpReaction; bool mUseReactionNameInLocalParameters; }; #endif // EXPRESSION2PRESENTATIONMML_H
31.397059
92
0.735831
[ "model" ]
536b2c18e103c2cc5336c9f84a587f134a9c00fb
817
h
C
P0267_RefImpl/Samples/CPULoad/data_source.h
DavidLudwig/P0267_RefImpl
22720d0eeae43b503400f6dbb368f79c8fdacdc7
[ "BSL-1.0" ]
null
null
null
P0267_RefImpl/Samples/CPULoad/data_source.h
DavidLudwig/P0267_RefImpl
22720d0eeae43b503400f6dbb368f79c8fdacdc7
[ "BSL-1.0" ]
1
2018-05-30T18:58:41.000Z
2018-05-30T18:58:41.000Z
P0267_RefImpl/Samples/CPULoad/data_source.h
DavidLudwig/P0267_Modified
22720d0eeae43b503400f6dbb368f79c8fdacdc7
[ "BSL-1.0" ]
null
null
null
#pragma once #include <vector> #include <chrono> #include <deque> #include <algorithm> class DataSource { public: DataSource(int max_samples = 4096, std::chrono::milliseconds fetch_interval = std::chrono::milliseconds{100}); void Fetch(); int CoresCount() const noexcept { return m_Cores; } int SamplesCount() const noexcept { return std::max(int(m_Samples[0].size()) - 2, 0); } float At(int core, int sample) const noexcept { return m_Samples[core][sample]; } private: void Consume(const std::vector<float> &loads); static void Smooth(std::deque<float> &data); int m_MaxSamples; int m_Cores; std::vector<std::deque<float>> m_Samples; std::chrono::milliseconds m_FetchInterval; std::chrono::high_resolution_clock::time_point m_LastFetched; };
28.172414
114
0.685435
[ "vector" ]
536fa02c579c5934db4bef8e5b3071883f927642
2,716
c
C
mesh.c
sdukshis/ComputerGraphics
ec4ac4da14dad4351dd56c693050df6b1e9f91ca
[ "Apache-2.0" ]
null
null
null
mesh.c
sdukshis/ComputerGraphics
ec4ac4da14dad4351dd56c693050df6b1e9f91ca
[ "Apache-2.0" ]
9
2015-06-01T05:54:40.000Z
2021-04-18T17:57:11.000Z
mesh.c
sdukshis/ComputerGraphics
ec4ac4da14dad4351dd56c693050df6b1e9f91ca
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include "tga.h" #include "model.h" #include <assert.h> void swap(int *a, int *b); int iabs(int a); /* * Using Digital Differential Analyzer algorihm * to draw interval connecting (x0, y0) with (x1, y1) * on image using color */ void line (int x0, int y0, int x1, int y1, tgaImage *image, tgaColor color); void meshgrid(tgaImage *image, Model *model); int main(int argc, char const *argv[]) { if (argc < 3) { fprintf(stderr, "Usage: %s <objfile> <outfile>\n", argv[0]); return -1; } Model *model = loadFromObj(argv[1]); if (!model) { perror("loadFromObj"); return -1; } printf("model with %d vertices, %d faces loaded\n", model->nvert, model->nface); int rv = 0; int height = 800; int width = 800; tgaImage * image = tgaNewImage(height, width, RGB); meshgrid(image, model); if (-1 == tgaSaveToFile(image, argv[2])) { perror("tgaSateToFile"); rv = -1; } tgaFreeImage(image); freeModel(model); return rv; } void meshgrid(tgaImage *image, Model *model) { assert(image); assert(model); int i; int h = image->height; int w = image->width; for (i = 0; i < model->nface; ++i) { Vec3 *v0 = &(model->vertices[model->faces[i][0]]); Vec3 *v1 = &(model->vertices[model->faces[i][3]]); Vec3 *v2 = &(model->vertices[model->faces[i][6]]); line(((*v0)[0] + 1) * w / 2,(1 - (*v0)[1]) * h / 2, ((*v1)[0] + 1) * w / 2,(1 - (*v1)[1]) * h / 2, image, tgaRGB(255, 255, 255)); line(((*v1)[0] + 1) * w / 2,(1 - (*v1)[1]) * h / 2, ((*v2)[0] + 1) * w / 2,(1 - (*v2)[1]) * h / 2, image, tgaRGB(255, 255, 255)); line(((*v2)[0] + 1) * w / 2,(1 - (*v2)[1]) * h / 2, ((*v0)[0] + 1) * w / 2,(1 - (*v0)[1]) * h / 2, image, tgaRGB(255, 255, 255)); } } void line (int x0, int y0, int x1, int y1, tgaImage *image, tgaColor color) { int steep = 0; if (iabs(y1 - y0) > iabs(x1 - x0)) { steep = 1; swap(&x0, &y0); swap(&x1, &y1); } if (x0 > x1) { swap(&x0, &x1); swap(&y0, &y1); } int x; double y; double k = ((double)(y1 - y0))/(x1 - x0); for (x = x0, y = y0; x <= x1; ++x, y += k) { if (steep) { tgaSetPixel(image, (unsigned int)y, (unsigned int)x, color); } else { tgaSetPixel(image, (unsigned int)x, (unsigned int)y, color); } } } void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } int iabs(int a) { return (a >= 0) ? a : -a; }
23.016949
84
0.474595
[ "model" ]
5376846518532c1ba9d27b3be80075fa4e33ed2c
9,799
c
C
tasklist.c
martindisch/tasuke
885e4f97adee34441525addac0e3f5ece2840e62
[ "MIT" ]
null
null
null
tasklist.c
martindisch/tasuke
885e4f97adee34441525addac0e3f5ece2840e62
[ "MIT" ]
null
null
null
tasklist.c
martindisch/tasuke
885e4f97adee34441525addac0e3f5ece2840e62
[ "MIT" ]
null
null
null
/* Using strdup & strndup, need POSIX 2008 */ #define _POSIX_C_SOURCE 200809L #include <stdlib.h> #include <stdio.h> #include <string.h> #include <limits.h> #include "tasklist.h" #define STARTING_CAPACITY 16 struct tasklist { char *path; char *name; char **tasks; int array_size; int length; }; /** * Returns the name of a task list based on its full path. * * It isolates the final part of the path, minus the file extension (.txt). * Because a new string needs to be allocated, the user must free it. * * @param path The full path to the file * @return The list name (freed by user) */ static char *path_to_name(const char *path) { // Find the first character of the name (inclusive) const char *name_start = strrchr(path, '/') + 1; // Continue and find the end of the name (exclusive) const char *name_end = strrchr(name_start, '.'); // Get number of characters in the name int length = name_end - name_start; // Get a copy of the substring containing the list name char *name = strndup(name_start, length); return name; } /** * Copies at most n chars from src into dest, splitting at spaces. * * It returns a pointer to the next character after the space where the * split was made. * It's imperative that the string is at least n characters long, because this * function does not check for the end. * The dest buffer needs to be n + 1 bytes large for the \0 terminator. * * @param dest The buffer characters are copied into * @param src The string characters are copied from * @param n Maximum number of characters to copy * @return Pointer to the character that should be printed next */ static const char *fold(char *dest, const char *src, int n) { // Initialize end of copy (exclusive) to maximum number of characters, // because that's where we'll split if there are no spaces const char *end = src + n; // This is the next character that should be printed const char *next = src + n; // Find the last space within n characters for (int i = 0; i <= n; ++i) { if (src[i] == ' ') { // Set end (exclusive) to the space end = src + i; // The character after that is the next one that should be printed next = src + i + 1; } } // Copy characters before the last space into the destination buffer strncpy(dest, src, end - src); // Terminate the string dest[end - src] = '\0'; return next; } TaskList tasklist_init(const char *path) { // Allocate memory for ADT TaskList list; list = malloc(sizeof(*list)); // Initialize members list->path = strdup(path); list->name = path_to_name(list->path); list->tasks = malloc(STARTING_CAPACITY * sizeof(char *)); list->array_size = STARTING_CAPACITY; list->length = 0; return list; } void tasklist_destroy(TaskList list) { // Free content of tasks array for (int i = 0; i < list->length; ++i) { free(list->tasks[i]); } // Free tasks array free(list->tasks); // Free other properties free(list->path); free(list->name); // Free ADT free(list); } void tasklist_print(TaskList list) { // Print list name printf("\x1b[4m\x1b[1m%s\x1b[0m\n", list->name); // If there are no tasks, show notice and return early if (list->length == 0) { printf(" No tasks\n"); return; } // Determine format (for padding) depending on number of tasks const char *format, *pad; int space; if (list->length < 10) { format = " \x1b[1m%d\x1b[0m %s"; pad = " "; space = 80 - 3; } else if (list->length < 100) { format = " \x1b[1m%2d\x1b[0m %s"; pad = " "; space = 80 - 4; } else { format = " \x1b[1m%3d\x1b[0m %s"; pad = " "; space = 80 - 5; } // Print tasks for (int i = 0; i < list->length; ++i) { if (strlen(list->tasks[i]) <= space + 1) { // There is enough space to print the whole task on one line printf(format, i + 1, list->tasks[i]); } else { // Need to split the task over several lines const char *task = list->tasks[i]; char out[space + 1]; // Print the first line task = fold(out, task, space); printf(format, i + 1, out); printf("\n"); // Print remaining lines while (strlen(task) > space + 1) { task = fold(out, task, space); printf("%s%s\n", pad, out); } // Print final line printf("%s%s", pad, task); } } } const char *tasklist_insert( TaskList list, long position, const char *task) { /* * Preparatory work: sanity check, memory allocation */ // Handle position out of range if (position < 1 || position > list->length + 1) { return "Invalid position\n"; } // If task array is full, allocate memory for an additional element if (list->array_size == list->length) { list->tasks = realloc( list->tasks, (list->array_size + 1) * sizeof(char *)); ++(list->array_size); } // Allocate memory for the task char *new_task = malloc((strlen(task) + 2) * sizeof(char)); // Copy the task into the new memory, appending newline sprintf(new_task, "%s\n", task); // Turn 1-based position into 0-based index long index = position - 1; /* * Insertion */ if (index == list->length) { // Simple case: append task to end list->tasks[list->length] = new_task; } else { // Normal case: insert somewhere and bubble other elements down char *current, *previous = new_task; for (int i = index; i < list->length + 1; ++i) { current = list->tasks[i]; list->tasks[i] = previous; previous = current; } } // Increment length ++(list->length); return NULL; } const char *tasklist_done(TaskList list, const long *positions) { /* * Delete selected tasks */ int done_count = 0; // Iterate over given positions for ( ; *positions != -1; ++positions) { // Handle position out of range if (*positions < 1 || *positions > list->length) { return "Invalid position\n"; } // Turn 1-based position into 0-based index long index = *positions - 1; // Remove task from list free(list->tasks[index]); list->tasks[index] = NULL; // Remember we deleted a task ++done_count; } /* * Build new task list with the remaining ones */ int new_length = list->length - done_count; // If no tasks remain, just update the count and terminate if (new_length == 0) { list->length = 0; return NULL; } // Allocate memory for the new task list char **tasks = malloc(new_length * sizeof(char *)); // Iterate over the old list, copying over the surviving elements for (int i = 0, y = 0; i < list->length; ++i) { if (list->tasks[i]) { tasks[y++] = list->tasks[i]; } } // Free the old list of task references free(list->tasks); // Use the new list of references instead list->tasks = tasks; // Update the count list->length = new_length; list->array_size = new_length; return NULL; } const char *tasklist_move(TaskList list, long from_pos, long to_pos) { /* * Preparatory work with sanity checking */ // Handle positions out of range if (from_pos < 1 || from_pos > list->length || to_pos < 1 || to_pos > list->length) { return "Invalid position\n"; } // Abort when there's nothing to do if (from_pos == to_pos) { return NULL; } // Turn 1-based positions into 0-based indices long from = from_pos - 1, to = to_pos - 1; /* * Movement */ if (from < to) { for (int i = from; i < to; ++i) { char *current = list->tasks[i]; list->tasks[i] = list->tasks[i + 1]; list->tasks[i + 1] = current; } } else { for (int i = from; i > to; --i) { char *current = list->tasks[i]; list->tasks[i] = list->tasks[i - 1]; list->tasks[i - 1] = current; } } return NULL; } const char *tasklist_read(TaskList list) { // Open file in read mode FILE *fp; if ((fp = fopen(list->path, "r")) == NULL) { return "Unable to open list\n"; } // Read tasks char line[LINE_MAX]; int i = 0; while (fgets(line, LINE_MAX, fp) != NULL) { if (list->array_size - i == 0) { // Double array size list->tasks = realloc( list->tasks, 2 * list->array_size * sizeof(char *)); list->array_size *= 2; } // Make a copy of the task char *task = strdup(line); // Add task to list list->tasks[i++] = task; ++(list->length); } // Close file if (fclose(fp) == EOF) { return "Unable to close list\n"; } return NULL; } const char *tasklist_write(TaskList list) { // Open file in write mode FILE *fp; if ((fp = fopen(list->path, "w")) == NULL) { return "Unable to open list\n"; } // Write all tasks to file for (int i = 0; i < list->length; ++i) { // Attempt write if (fputs(list->tasks[i], fp) == EOF) { fclose(fp); return "Unable to write to list\n"; } } // Close file if (fclose(fp) == EOF) { return "Unable to close list\n"; } return NULL; }
28.905605
78
0.561282
[ "3d" ]
537e9babbfe522d624b4eb18b2379c4e909afb56
8,668
c
C
ccx_prool/SPOOLES.2.2/DV/src/util.c
alleindrach/calculix-desktop
2cb2c434b536eb668ff88bdf82538d22f4f0f711
[ "MIT" ]
null
null
null
ccx_prool/SPOOLES.2.2/DV/src/util.c
alleindrach/calculix-desktop
2cb2c434b536eb668ff88bdf82538d22f4f0f711
[ "MIT" ]
4
2017-09-21T17:03:55.000Z
2018-01-25T16:08:31.000Z
ccx_prool/SPOOLES.2.2/DV/src/util.c
alleindrach/calculix-desktop
2cb2c434b536eb668ff88bdf82538d22f4f0f711
[ "MIT" ]
1
2019-08-29T18:41:28.000Z
2019-08-29T18:41:28.000Z
/* basics.C */ #include "../DV.h" /*--------------------------------------------------------------------*/ /* ----------------------------------------------------------- shift the base of the entries and adjust the dimensions note: this is a dangerous operation because the dv->vec does not point to the base of the entries any longer, and thus if the object owns its entries and it is called to resize them or to free them, malloc and free will choke. USE WITH CAUTION! created -- 96aug25, cca modified -- 96aug28, cca structure changed ----------------------------------------------------------- */ void DV_shiftBase ( DV *dv, int offset ) { if ( dv == NULL ) { fprintf(stderr, "\n fatal error in DV_shiftBase(%p,%d)" "\n bad input\n", dv, offset) ; exit(-1) ; } dv->vec += offset ; dv->maxsize -= offset ; dv->size -= offset ; return ; } /*--------------------------------------------------------------------*/ /* -------------------------------------- push an entry onto the list created -- 95oct06, cca -------------------------------------- */ void DV_push ( DV *dv, double val ) { if ( dv == NULL ) { fprintf(stderr, "\n fatal error in DV_push(%p,%f)" "\n bad input\n", dv, val) ; exit(-1) ; } if ( dv->size == dv->maxsize ) { if ( dv->maxsize > 0 ) { DV_setMaxsize(dv, 2*dv->maxsize) ; } else { DV_setMaxsize(dv, 10) ; } } dv->vec[dv->size++] = val ; return ; } /*--------------------------------------------------------------------*/ /* ----------------------------------- minimum and maximum entries and sum created -- 95oct06, cca ----------------------------------- */ double DV_min ( DV *dv ) { int i ; if ( dv == NULL || dv->size <= 0 || dv->vec == NULL ) { fprintf(stderr, "\n fatal error in DV_min(%p), size = %d, vec = %p", dv, dv->size, dv->vec) ; exit(-1) ; } return(DVmin(dv->size, dv->vec, &i)) ; } double DV_max ( DV *dv ) { int i ; if ( dv == NULL || dv->size <= 0 || dv->vec == NULL ) { fprintf(stderr, "\n fatal error in DV_max(%p), size = %d, vec = %p", dv, dv->size, dv->vec) ; exit(-1) ; } return(DVmax(dv->size, dv->vec, &i)) ; } double DV_sum ( DV *dv ) { if ( dv == NULL || dv->size <= 0 || dv->vec == NULL ) { fprintf(stderr, "\n fatal error in DV_sum(%p), size = %d, vec = %p", dv, dv->size, dv->vec) ; exit(-1) ; } return(DVsum(dv->size, dv->vec)) ; } /*--------------------------------------------------------------------*/ /* ------------------------------------------------------- sort each index list into ascending or descending order created -- 95oct06, cca ------------------------------------------------------- */ void DV_sortUp ( DV *dv ) { if ( dv == NULL || dv->size <= 0 || dv->vec == NULL ) { fprintf(stderr, "\n fatal error in DV_sortUp(%p), size = %d, vec = %p", dv, dv->size, dv->vec) ; exit(-1) ; } DVqsortUp(dv->size, dv->vec) ; return ; } void DV_sortDown ( DV *dv ) { if ( dv == NULL || dv->size <= 0 || dv->vec == NULL ) { fprintf(stderr, "\n fatal error in DV_sortDown(%p), size = %d, vec = %p", dv, dv->size, dv->vec) ; exit(-1) ; } DVqsortDown(dv->size, dv->vec) ; return ; } /*--------------------------------------------------------------------*/ /* ----------------------- ramp the entries created -- 95oct06, cca ----------------------- */ void DV_ramp ( DV *dv, double base, double incr ) { if ( dv == NULL || dv->size <= 0 || dv->vec == NULL ) { fprintf(stderr, "\n fatal error in DV_ramp(%p,%f,%f), size = %d, vec = %p", dv, base, incr, dv->size, dv->vec) ; exit(-1) ; } DVramp(dv->size, dv->vec, base, incr) ; return ; } /*--------------------------------------------------------------------*/ /* ----------------------- shuffle the list created -- 95oct06, cca ----------------------- */ void DV_shuffle ( DV *dv, int seed ) { if ( dv == NULL || dv->size <= 0 || dv->vec == NULL ) { fprintf(stderr, "\n fatal error in DV_shuffle(%p,%d), size = %d, vec = %p", dv, seed, dv->size, dv->vec) ; exit(-1) ; } DVshuffle(dv->size, dv->vec, seed) ; return ; } /*--------------------------------------------------------------------*/ /* ---------------------------------------------- return the number of bytes taken by the object created -- 95oct06, cca ---------------------------------------------- */ int DV_sizeOf ( DV *dv ) { int nbytes ; if ( dv == NULL ) { fprintf(stderr, "\n fatal error in DV_sizeOf(%p)" "\n bad input \n", dv) ; exit(-1) ; } nbytes = sizeof(struct _DV) ; if ( dv->owned == 1 ) { nbytes += + dv->maxsize*sizeof(double) ; } return(nbytes) ; } /*--------------------------------------------------------------------*/ /* -------------------------------------------- iterator : return the pointer to the head of the vector created -- 95oct06, cca -------------------------------------------- */ double * DV_first ( DV *dv ) { double *pd ; /* --------------- check the input --------------- */ if ( dv == NULL ) { fprintf(stderr, "\n fatal error in DV_first(%p)" "\n bad input", dv) ; exit(-1) ; } if ( dv->size == 0 ) { pd = NULL ; } else { pd = dv->vec ; } return(pd) ; } /*--------------------------------------------------------------------*/ /* ----------------------------------------------------- iterator : return the pointer to the next location in the vector created -- 95oct06, cca ----------------------------------------------------- */ double * DV_next ( DV *dv, double *pd ) { int offset ; /* --------------- check the input --------------- */ if ( pd == NULL ) { fprintf(stderr, "\n fatal error in DV_next(%p,%p)" "\n bad input", dv, pd) ; fflush(stderr) ; exit(-1) ; } /* --------------- check the input --------------- */ if ( (offset = pd - dv->vec) < 0 || offset >= dv->size ) { /* ----------------------------- error, offset is out of range ----------------------------- */ fprintf(stderr, "\n fatal error in DV_next(%p,%p)" "\n offset = %d, must be in [0,%d)", dv, pd, offset, dv->size) ; fflush(stderr) ; exit(-1) ; } else if ( offset == dv->size - 1 ) { /* ---------------------------- end of the list, return NULL ---------------------------- */ pd = NULL ; } else { /* ---------------------------------------- middle of the list, return next location ---------------------------------------- */ pd++ ; } return(pd) ; } /*--------------------------------------------------------------------*/ /* -------------------------- fill a vector with a value created -- 96jun22, cca -------------------------- */ void DV_fill ( DV *dv, double value ) { /* --------------- check the input --------------- */ if ( dv == NULL ) { fprintf(stderr, "\n fatal error in DV_fill(%p,%f)" "\n bad input\n", dv, value) ; exit(-1) ; } if ( dv->size > 0 ) { DVfill(dv->size, dv->vec, value) ; } return ; } /*--------------------------------------------------------------------*/ /* -------------------------- fill a vector with zeros created -- 98jun02, cca -------------------------- */ void DV_zero ( DV *dv ) { /* --------------- check the input --------------- */ if ( dv == NULL ) { fprintf(stderr, "\n fatal error in DV_zero(%p)" "\n bad input\n", dv) ; exit(-1) ; } if ( dv->size > 0 ) { DVzero(dv->size, dv->vec) ; } return ; } /*--------------------------------------------------------------------*/ /* -------------------------------------- copy entries from dv2 into dv1. note: this is a "mapped" copy, dv1 and dv2 need not be the same size. created -- 96aug31, cca -------------------------------------- */ void DV_copy ( DV *dv1, DV *dv2 ) { int ii, size ; double *vec1, *vec2 ; /* --------------- check the input --------------- */ if ( dv1 == NULL || dv2 == NULL ) { fprintf(stderr, "\n fatal error in DV_copy(%p,%p)" "\n bad input\n", dv1, dv2) ; exit(-1) ; } size = dv1->size ; if ( size > dv2->size ) { size = dv2->size ; } vec1 = dv1->vec ; vec2 = dv2->vec ; for ( ii = 0 ; ii < size ; ii++ ) { vec1[ii] = vec2[ii] ; } return ; } /*--------------------------------------------------------------------*/
21.455446
72
0.377711
[ "object", "vector" ]
7afbfed1df6e2a9a7419268c6c64452c22180549
696
h
C
aws-cpp-sdk-iotanalytics/include/aws/iotanalytics/model/DatastoreStatus.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-iotanalytics/include/aws/iotanalytics/model/DatastoreStatus.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-iotanalytics/include/aws/iotanalytics/model/DatastoreStatus.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/iotanalytics/IoTAnalytics_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace IoTAnalytics { namespace Model { enum class DatastoreStatus { NOT_SET, CREATING, ACTIVE, DELETING }; namespace DatastoreStatusMapper { AWS_IOTANALYTICS_API DatastoreStatus GetDatastoreStatusForName(const Aws::String& name); AWS_IOTANALYTICS_API Aws::String GetNameForDatastoreStatus(DatastoreStatus value); } // namespace DatastoreStatusMapper } // namespace Model } // namespace IoTAnalytics } // namespace Aws
21.090909
88
0.764368
[ "model" ]
bb0080b5ffc87ba0add5775c1a3729e6044729a9
38,658
h
C
indra/newview/llselectmgr.h
SaladDais/LLUDP-Encryption
8a426cd0dd154e1a10903e0e6383f4deb2a6098a
[ "ISC" ]
1
2022-01-29T07:10:03.000Z
2022-01-29T07:10:03.000Z
indra/newview/llselectmgr.h
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
null
null
null
indra/newview/llselectmgr.h
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
1
2021-10-01T22:22:27.000Z
2021-10-01T22:22:27.000Z
/** * @file llselectmgr.h * @brief A manager for selected objects and TEs. * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #ifndef LL_LLSELECTMGR_H #define LL_LLSELECTMGR_H #include "llcharacter.h" #include "lleditmenuhandler.h" #include "llundo.h" #include "lluuid.h" #include "llpointer.h" #include "llsafehandle.h" #include "llsaleinfo.h" #include "llcategory.h" #include "v3dmath.h" #include "llquaternion.h" #include "llcoord.h" #include "llframetimer.h" #include "llbbox.h" #include "llpermissions.h" #include "llcontrol.h" #include "llviewerobject.h" // LLObjectSelection::getSelectedTEValue template #include "llmaterial.h" #include <deque> #include <boost/iterator/filter_iterator.hpp> #include <boost/signals2.hpp> #include <boost/make_shared.hpp> // boost::make_shared class LLMessageSystem; class LLViewerTexture; class LLColor4; class LLVector3; class LLSelectNode; const U8 UPD_NONE = 0x00; const U8 UPD_POSITION = 0x01; const U8 UPD_ROTATION = 0x02; const U8 UPD_SCALE = 0x04; const U8 UPD_LINKED_SETS = 0x08; const U8 UPD_UNIFORM = 0x10; // used with UPD_SCALE // <FS:Ansariel> Moved here to make them publically accessible // For linked sets const S32 MAX_CHILDREN_PER_TASK = 255; const S32 MAX_CHILDREN_PER_PHYSICAL_TASK = 32; // </FS:Ansariel> // <FS:KC> show/hide build highlight enum EFSShowHideHighlight { FS_SHOW_HIDE_HIGHLIGHT_NORMAL = 0, FS_SHOW_HIDE_HIGHLIGHT_SHOW = 1, FS_SHOW_HIDE_HIGHLIGHT_HIDE = 2 }; // </FS:KC> // This is used by the DeRezObject message to determine where to put // derezed tasks. enum EDeRezDestination { DRD_SAVE_INTO_AGENT_INVENTORY = 0, DRD_ACQUIRE_TO_AGENT_INVENTORY = 1, // try to leave copy in world DRD_SAVE_INTO_TASK_INVENTORY = 2, DRD_ATTACHMENT = 3, DRD_TAKE_INTO_AGENT_INVENTORY = 4, // delete from world DRD_FORCE_TO_GOD_INVENTORY = 5, // force take copy DRD_TRASH = 6, DRD_ATTACHMENT_TO_INV = 7, DRD_ATTACHMENT_EXISTS = 8, DRD_RETURN_TO_OWNER = 9, // back to owner's inventory DRD_RETURN_TO_LAST_OWNER = 10, // deeded object back to last owner's inventory DRD_COUNT = 11 }; const S32 SELECT_ALL_TES = -1; const S32 SELECT_MAX_TES = 32; // Do something to all objects in the selection manager. // The BOOL return value can be used to indicate if all // objects are identical (gathering information) or if // the operation was successful. struct LLSelectedObjectFunctor { virtual ~LLSelectedObjectFunctor() {}; virtual bool apply(LLViewerObject* object) = 0; }; // Do something to all select nodes in the selection manager. // The BOOL return value can be used to indicate if all // objects are identical (gathering information) or if // the operation was successful. struct LLSelectedNodeFunctor { virtual ~LLSelectedNodeFunctor() {}; virtual bool apply(LLSelectNode* node) = 0; }; struct LLSelectedTEFunctor { virtual ~LLSelectedTEFunctor() {}; virtual bool apply(LLViewerObject* object, S32 face) = 0; }; struct LLSelectedTEMaterialFunctor { virtual ~LLSelectedTEMaterialFunctor() {}; virtual LLMaterialPtr apply(LLViewerObject* object, S32 face, LLTextureEntry* tep, LLMaterialPtr& current_material) = 0; }; template <typename T> struct LLSelectedTEGetFunctor { virtual ~LLSelectedTEGetFunctor() {}; virtual T get(LLViewerObject* object, S32 te) = 0; }; template <typename T> struct LLCheckIdenticalFunctor { static bool same(const T& a, const T& b, const T& tolerance); }; typedef enum e_send_type { SEND_ONLY_ROOTS, SEND_INDIVIDUALS, SEND_ROOTS_FIRST, // useful for serial undos on linked sets SEND_CHILDREN_FIRST // useful for serial transforms of linked sets } ESendType; typedef enum e_grid_mode { GRID_MODE_WORLD, GRID_MODE_LOCAL, GRID_MODE_REF_OBJECT } EGridMode; typedef enum e_action_type { SELECT_ACTION_TYPE_BEGIN, SELECT_ACTION_TYPE_PICK, SELECT_ACTION_TYPE_MOVE, SELECT_ACTION_TYPE_ROTATE, SELECT_ACTION_TYPE_SCALE, NUM_ACTION_TYPES }EActionType; typedef enum e_selection_type { SELECT_TYPE_WORLD, SELECT_TYPE_ATTACHMENT, SELECT_TYPE_HUD }ESelectType; const S32 TE_SELECT_MASK_ALL = 0xFFFFFFFF; //<FS:Beq> Physics view in edit mode changes void pushWireframe(LLDrawable* drawable); //</FS:Beq> // Contains information about a selected object, particularly which TEs are selected. class LLSelectNode { public: LLSelectNode(LLViewerObject* object, BOOL do_glow); LLSelectNode(const LLSelectNode& nodep); ~LLSelectNode(); void selectAllTEs(BOOL b); void selectTE(S32 te_index, BOOL selected); BOOL isTESelected(S32 te_index) const; bool hasSelectedTE() const { return TE_SELECT_MASK_ALL & mTESelectMask; } S32 getLastSelectedTE() const; S32 getLastOperatedTE() const { return mLastTESelected; } S32 getTESelectMask() { return mTESelectMask; } void renderOneSilhouette(const LLColor4 &color); void setTransient(BOOL transient) { mTransient = transient; } BOOL isTransient() const { return mTransient; } LLViewerObject* getObject(); void setObject(LLViewerObject* object); // *NOTE: invalidate stored textures and colors when # faces change void saveColors(); void saveShinyColors(); void saveTextures(const uuid_vec_t& textures); void saveTextureScaleRatios(LLRender::eTexIndex index_to_query); BOOL allowOperationOnNode(PermissionBit op, U64 group_proxy_power) const; public: BOOL mIndividualSelection; // For root objects and objects individually selected BOOL mTransient; BOOL mValid; // is extra information valid? LLPermissions* mPermissions; LLSaleInfo mSaleInfo; LLAggregatePermissions mAggregatePerm; LLAggregatePermissions mAggregateTexturePerm; LLAggregatePermissions mAggregateTexturePermOwner; std::string mName; std::string mDescription; LLCategory mCategory; S16 mInventorySerial; LLVector3 mSavedPositionLocal; // for interactively modifying object position LLVector3 mLastPositionLocal; LLVector3d mSavedPositionGlobal; // for interactively modifying object position LLVector3 mSavedScale; // for interactively modifying object scale LLVector3 mLastScale; LLQuaternion mSavedRotation; // for interactively modifying object rotation LLQuaternion mLastRotation; BOOL mDuplicated; LLVector3d mDuplicatePos; LLQuaternion mDuplicateRot; LLUUID mItemID; LLUUID mFolderID; LLUUID mFromTaskID; std::string mTouchName; std::string mSitName; U64 mCreationDate; std::vector<LLColor4> mSavedColors; std::vector<LLColor4> mSavedShinyColors; uuid_vec_t mSavedTextures; std::vector<LLVector3> mTextureScaleRatios; std::vector<LLVector3> mSilhouetteVertices; // array of vertices to render silhouette of object std::vector<LLVector3> mSilhouetteNormals; // array of normals to render silhouette of object BOOL mSilhouetteExists; // need to generate silhouette? protected: LLPointer<LLViewerObject> mObject; S32 mTESelectMask; S32 mLastTESelected; // <FS:ND> For const access. Need to check for isDead yourself. public: LLViewerObject const* getObject() const { return mObject; } // </FS:ND> }; class LLObjectSelection : public LLRefCount { friend class LLSelectMgr; friend class LLSafeHandle<LLObjectSelection>; friend class LLSelectionCallbackData; protected: ~LLObjectSelection(); public: typedef std::list<LLSelectNode*> list_t; // Iterators struct is_non_null { bool operator()(LLSelectNode* node) { return (node->getObject() != NULL); } }; typedef boost::filter_iterator<is_non_null, list_t::iterator > iterator; iterator begin() { return iterator(mList.begin(), mList.end()); } iterator end() { return iterator(mList.end(), mList.end()); } struct is_valid { bool operator()(LLSelectNode* node) { return (node->getObject() != NULL) && node->mValid; } }; typedef boost::filter_iterator<is_valid, list_t::iterator > valid_iterator; valid_iterator valid_begin() { return valid_iterator(mList.begin(), mList.end()); } valid_iterator valid_end() { return valid_iterator(mList.end(), mList.end()); } struct is_root { bool operator()(LLSelectNode* node); }; typedef boost::filter_iterator<is_root, list_t::iterator > root_iterator; root_iterator root_begin() { return root_iterator(mList.begin(), mList.end()); } root_iterator root_end() { return root_iterator(mList.end(), mList.end()); } struct is_valid_root { bool operator()(LLSelectNode* node); }; typedef boost::filter_iterator<is_valid_root, list_t::iterator > valid_root_iterator; valid_root_iterator valid_root_begin() { return valid_root_iterator(mList.begin(), mList.end()); } valid_root_iterator valid_root_end() { return valid_root_iterator(mList.end(), mList.end()); } struct is_root_object { bool operator()(LLSelectNode* node); }; typedef boost::filter_iterator<is_root_object, list_t::iterator > root_object_iterator; root_object_iterator root_object_begin() { return root_object_iterator(mList.begin(), mList.end()); } root_object_iterator root_object_end() { return root_object_iterator(mList.end(), mList.end()); } public: LLObjectSelection(); void updateEffects(); BOOL isEmpty() const; LLSelectNode* getFirstNode(LLSelectedNodeFunctor* func = NULL); LLSelectNode* getFirstRootNode(LLSelectedNodeFunctor* func = NULL, BOOL non_root_ok = FALSE); LLViewerObject* getFirstSelectedObject(LLSelectedNodeFunctor* func, BOOL get_parent = FALSE); LLViewerObject* getFirstObject(); LLViewerObject* getFirstRootObject(BOOL non_root_ok = FALSE); LLSelectNode* getFirstMoveableNode(BOOL get_root_first = FALSE); LLViewerObject* getFirstEditableObject(BOOL get_parent = FALSE); LLViewerObject* getFirstCopyableObject(BOOL get_parent = FALSE); LLViewerObject* getFirstDeleteableObject(); LLViewerObject* getFirstMoveableObject(BOOL get_parent = FALSE); LLViewerObject* getFirstUndoEnabledObject(BOOL get_parent = FALSE); /// Return the object that lead to this selection, possible a child LLViewerObject* getPrimaryObject() { return mPrimaryObject; } // iterate through texture entries template <typename T> bool getSelectedTEValue(LLSelectedTEGetFunctor<T>* func, T& res, bool has_tolerance = false, T tolerance = T()); template <typename T> bool isMultipleTEValue(LLSelectedTEGetFunctor<T>* func, const T& ignore_value); S32 getNumNodes(); LLSelectNode* findNode(LLViewerObject* objectp); // count members S32 getObjectCount(); F32 getSelectedObjectCost(); F32 getSelectedLinksetCost(); F32 getSelectedPhysicsCost(); F32 getSelectedLinksetPhysicsCost(); S32 getSelectedObjectRenderCost(); F32 getSelectedObjectStreamingCost(S32* total_bytes = NULL, S32* visible_bytes = NULL); U32 getSelectedObjectTriangleCount(S32* vcount = NULL); S32 getTECount(); S32 getRootObjectCount(); BOOL isMultipleTESelected(); BOOL contains(LLViewerObject* object); BOOL contains(LLViewerObject* object, S32 te); // returns TRUE is any node is currenly worn as an attachment BOOL isAttachment(); bool checkAnimatedObjectEstTris(); bool checkAnimatedObjectLinkable(); // Apply functors to various subsets of the selected objects // If firstonly is FALSE, returns the AND of all apply() calls. // Else returns TRUE immediately if any apply() call succeeds (i.e. OR with early exit) bool applyToRootObjects(LLSelectedObjectFunctor* func, bool firstonly = false); bool applyToObjects(LLSelectedObjectFunctor* func); bool applyToTEs(LLSelectedTEFunctor* func, bool firstonly = false); bool applyToRootNodes(LLSelectedNodeFunctor* func, bool firstonly = false); bool applyToNodes(LLSelectedNodeFunctor* func, bool firstonly = false); /* * Used to apply (no-copy) textures to the selected object or * selected face/faces of the object. * This method moves (no-copy) texture to the object's inventory * and doesn't make copy of the texture for each face. * Then this only texture is used for all selected faces. */ void applyNoCopyTextureToTEs(LLViewerInventoryItem* item); ESelectType getSelectType() const { return mSelectType; } private: void addNode(LLSelectNode *nodep); void addNodeAtEnd(LLSelectNode *nodep); void moveNodeToFront(LLSelectNode *nodep); void removeNode(LLSelectNode *nodep); void deleteAllNodes(); void cleanupNodes(); private: list_t mList; const LLObjectSelection &operator=(const LLObjectSelection &); LLPointer<LLViewerObject> mPrimaryObject; std::map<LLPointer<LLViewerObject>, LLSelectNode*> mSelectNodeMap; ESelectType mSelectType; // <FS:Zi> Fix for crash while selecting objects with derendered child prims list_t mFailedNodesList; bool checkNode(LLSelectNode* nodep); // </FS:Zi> }; typedef LLSafeHandle<LLObjectSelection> LLObjectSelectionHandle; // Build time optimization, generate this once in .cpp file #ifndef LLSELECTMGR_CPP extern template class LLSelectMgr* LLSingleton<class LLSelectMgr>::getInstance(); #endif // For use with getFirstTest() struct LLSelectGetFirstTest; // <FS:ND> To listened into received prop. messages namespace nd { namespace selection { class PropertiesListener { public: virtual void onProperties( LLSelectNode const * ) = 0; }; class PropertiesServer { public: PropertiesServer() : mBatchMode( false ) { } void registerPropertyListener( nd::selection::PropertiesListener *aP) { mListener.insert( aP ); } void removePropertyListener( nd::selection::PropertiesListener *aP) { mListener.erase( aP ); } void enableBatchMode( ) { mBatchMode = true; } void disableBatchMode( ) { mBatchMode = false; } bool isBatchMode() const { return mBatchMode; } protected: void firePropertyReceived( LLSelectNode const *aNode ) { for( std::set< nd::selection::PropertiesListener * >::iterator itr = mListener.begin(); itr != mListener.end(); ++itr ) (*itr)->onProperties( aNode ); } private: std::set< nd::selection::PropertiesListener * > mListener; bool mBatchMode; }; } } // </FS:ND> // temporary storage, Ex: to attach objects after autopilot class LLSelectionCallbackData { public: LLSelectionCallbackData(); LLObjectSelectionHandle getSelection() { return mSelectedObjects; } private: LLObjectSelectionHandle mSelectedObjects; }; class LLSelectMgr : public LLEditMenuHandler, public LLSingleton<LLSelectMgr>, public nd::selection::PropertiesServer { LLSINGLETON(LLSelectMgr); ~LLSelectMgr(); public: static BOOL sRectSelectInclusive; // do we need to surround an object to pick it? static BOOL sRenderHiddenSelections; // do we show selection silhouettes that are occluded? static BOOL sRenderLightRadius; // do we show the radius of selected lights? static F32 sHighlightThickness; static F32 sHighlightUScale; static F32 sHighlightVScale; static F32 sHighlightAlpha; static F32 sHighlightAlphaTest; static F32 sHighlightUAnim; static F32 sHighlightVAnim; static LLColor4 sSilhouetteParentColor; static LLColor4 sSilhouetteChildColor; static LLColor4 sHighlightParentColor; static LLColor4 sHighlightChildColor; static LLColor4 sHighlightInspectColor; static LLColor4 sContextSilhouetteColor; LLCachedControl<bool> mHideSelectedObjects; LLCachedControl<bool> mRenderHighlightSelections; LLCachedControl<bool> mAllowSelectAvatar; LLCachedControl<bool> mDebugSelectMgr; public: static void cleanupGlobals(); // LLEditMenuHandler interface virtual BOOL canUndo() const; virtual void undo(); virtual BOOL canRedo() const; virtual void redo(); virtual BOOL canDoDelete() const; virtual void doDelete(); virtual void deselect(); virtual BOOL canDeselect() const; virtual void duplicate(); virtual BOOL canDuplicate() const; void clearSelections(); void update(); void updateEffects(); // Update HUD effects // When we edit object's position/rotation/scale we set local // overrides and ignore any updates (override received valeus). // When we send data to server, we send local values and reset // overrides void resetObjectOverrides(); void resetObjectOverrides(LLObjectSelectionHandle selected_handle); void overrideObjectUpdates(); // Returns the previous value of mForceSelection BOOL setForceSelection(BOOL force); //////////////////////////////////////////////////////////////// // Selection methods //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // Add //////////////////////////////////////////////////////////////// // This method is meant to select an object, and then select all // of the ancestors and descendants. This should be the normal behavior. // // *NOTE: You must hold on to the object selection handle, otherwise // the objects will be automatically deselected in 1 frame. LLObjectSelectionHandle selectObjectAndFamily(LLViewerObject* object, BOOL add_to_end = FALSE, BOOL ignore_select_owned = FALSE); // For when you want just a child object. LLObjectSelectionHandle selectObjectOnly(LLViewerObject* object, S32 face = SELECT_ALL_TES); // Same as above, but takes a list of objects. Used by rectangle select. LLObjectSelectionHandle selectObjectAndFamily(const std::vector<LLViewerObject*>& object_list, BOOL send_to_sim = TRUE); // converts all objects currently highlighted to a selection, and returns it LLObjectSelectionHandle selectHighlightedObjects(); LLObjectSelectionHandle setHoverObject(LLViewerObject *objectp, S32 face = -1); LLSelectNode *getHoverNode(); LLSelectNode *getPrimaryHoverNode(); void highlightObjectOnly(LLViewerObject *objectp); void highlightObjectAndFamily(LLViewerObject *objectp); void highlightObjectAndFamily(const std::vector<LLViewerObject*>& list); //////////////////////////////////////////////////////////////// // Remove //////////////////////////////////////////////////////////////// void deselectObjectOnly(LLViewerObject* object, BOOL send_to_sim = TRUE); void deselectObjectAndFamily(LLViewerObject* object, BOOL send_to_sim = TRUE, BOOL include_entire_object = FALSE); // Send deselect messages to simulator, then clear the list void deselectAll(); void deselectAllForStandingUp(); // deselect only if nothing else currently referencing the selection void deselectUnused(); // Deselect if the selection center is too far away from the agent. void deselectAllIfTooFar(); // Removes all highlighted objects from current selection void deselectHighlightedObjects(); void unhighlightObjectOnly(LLViewerObject *objectp); void unhighlightObjectAndFamily(LLViewerObject *objectp); void unhighlightAll(); BOOL removeObjectFromSelections(const LLUUID &id); //////////////////////////////////////////////////////////////// // Selection editing //////////////////////////////////////////////////////////////// bool linkObjects(); bool unlinkObjects(); void confirmUnlinkObjects(const LLSD& notification, const LLSD& response); bool enableLinkObjects(); bool enableUnlinkObjects(); //////////////////////////////////////////////////////////////// // Selection accessors //////////////////////////////////////////////////////////////// LLObjectSelectionHandle getHoverObjects() { return mHoverObjects; } LLObjectSelectionHandle getSelection() { return mSelectedObjects; } // right now this just renders the selection with root/child colors instead of a single color LLObjectSelectionHandle getEditSelection() { convertTransient(); return mSelectedObjects; } LLObjectSelectionHandle getHighlightedObjects() { return mHighlightedObjects; } //////////////////////////////////////////////////////////////// // Grid manipulation //////////////////////////////////////////////////////////////// void addGridObject(LLViewerObject* objectp); void clearGridObjects(); void setGridMode(EGridMode mode); EGridMode getGridMode() { return mGridMode; } void getGrid(LLVector3& origin, LLQuaternion& rotation, LLVector3 &scale, bool for_snap_guides = false); BOOL getTEMode() const { return mTEMode; } void setTEMode(BOOL b) { mTEMode = b; } BOOL shouldShowSelection() const { return mShowSelection; } LLBBox getBBoxOfSelection() const; LLBBox getSavedBBoxOfSelection() const { return mSavedSelectionBBox; } void dump(); void cleanup(); void updateSilhouettes(); void renderSilhouettes(BOOL for_hud); void enableSilhouette(BOOL enable) { mRenderSilhouettes = enable; } // <FS:KC> show/hide build highlight void setFSShowHideHighlight(EFSShowHideHighlight state) { mFSShowHideHighlight = state; } // </FS:KC> //////////////////////////////////////////////////////////////// // Utility functions that operate on the current selection //////////////////////////////////////////////////////////////// void saveSelectedObjectTransform(EActionType action_type); void saveSelectedObjectColors(); void saveSelectedShinyColors(); void saveSelectedObjectTextures(); // Sets which texture channel to query for scale and rot of display // and depends on UI state of LLPanelFace when editing void setTextureChannel(LLRender::eTexIndex texIndex) { mTextureChannel = texIndex; } LLRender::eTexIndex getTextureChannel() { return mTextureChannel; } void selectionUpdatePhysics(BOOL use_physics); void selectionUpdateTemporary(BOOL is_temporary); void selectionUpdatePhantom(BOOL is_ghost); void selectionDump(); BOOL selectionAllPCode(LLPCode code); // all objects have this PCode BOOL selectionGetClickAction(U8 *out_action); bool selectionGetIncludeInSearch(bool* include_in_search_out); // true if all selected objects have same BOOL selectionGetGlow(F32 *glow); void selectionSetPhysicsType(U8 type); void selectionSetGravity(F32 gravity); void selectionSetFriction(F32 friction); void selectionSetDensity(F32 density); void selectionSetRestitution(F32 restitution); void selectionSetMaterial(U8 material); void selectionSetImage(const LLUUID& imageid); // could be item or asset id void selectionSetColor(const LLColor4 &color); void selectionSetColorOnly(const LLColor4 &color); // Set only the RGB channels void selectionSetAlphaOnly(const F32 alpha); // Set only the alpha channel void selectionRevertColors(); void selectionRevertShinyColors(); BOOL selectionRevertTextures(); void selectionSetBumpmap( U8 bumpmap ); void selectionSetTexGen( U8 texgen ); void selectionSetShiny( U8 shiny ); void selectionSetFullbright( U8 fullbright ); void selectionSetMedia( U8 media_type, const LLSD &media_data ); void selectionSetClickAction(U8 action); void selectionSetIncludeInSearch(bool include_in_search); void selectionSetGlow(const F32 glow); void selectionSetMaterialParams(LLSelectedTEMaterialFunctor* material_func, int specific_te = -1); void selectionRemoveMaterial(); void selectionSetObjectPermissions(U8 perm_field, BOOL set, U32 perm_mask, BOOL override = FALSE); void selectionSetObjectName(const std::string& name); void selectionSetObjectDescription(const std::string& desc); void selectionSetObjectCategory(const LLCategory& category); void selectionSetObjectSaleInfo(const LLSaleInfo& sale_info); void selectionTexScaleAutofit(F32 repeats_per_meter); void adjustTexturesByScale(BOOL send_to_sim, BOOL stretch); bool selectionMove(const LLVector3& displ, F32 rx, F32 ry, F32 rz, U32 update_type); void sendSelectionMove(); void sendGodlikeRequest(const std::string& request, const std::string& parameter); // will make sure all selected object meet current criteria, or deselect them otherwise void validateSelection(); // returns TRUE if it is possible to select this object BOOL canSelectObject(LLViewerObject* object, BOOL ignore_select_owned = FALSE); // Returns TRUE if the viewer has information on all selected objects BOOL selectGetAllRootsValid(); BOOL selectGetAllValid(); BOOL selectGetAllValidAndObjectsFound(); // returns TRUE if you can modify all selected objects. BOOL selectGetRootsModify(); BOOL selectGetModify(); // returns TRUE if all objects are in same region BOOL selectGetSameRegion(); // returns TRUE if is all objects are non-permanent-enforced BOOL selectGetRootsNonPermanentEnforced(); BOOL selectGetNonPermanentEnforced(); // returns TRUE if is all objects are permanent BOOL selectGetRootsPermanent(); BOOL selectGetPermanent(); // returns TRUE if is all objects are character BOOL selectGetRootsCharacter(); BOOL selectGetCharacter(); // returns TRUE if is all objects are not permanent BOOL selectGetRootsNonPathfinding(); BOOL selectGetNonPathfinding(); // returns TRUE if is all objects are not permanent BOOL selectGetRootsNonPermanent(); BOOL selectGetNonPermanent(); // returns TRUE if is all objects are not character BOOL selectGetRootsNonCharacter(); BOOL selectGetNonCharacter(); BOOL selectGetEditableLinksets(); BOOL selectGetViewableCharacters(); // returns TRUE if selected objects can be transferred. BOOL selectGetRootsTransfer(); // returns TRUE if selected objects can be copied. BOOL selectGetRootsCopy(); BOOL selectGetCreator(LLUUID& id, std::string& name); // TRUE if all have same creator, returns id BOOL selectGetOwner(LLUUID& id, std::string& name); // TRUE if all objects have same owner, returns id BOOL selectGetLastOwner(LLUUID& id, std::string& name); // TRUE if all objects have same owner, returns id // returns TRUE if all are the same. id is stuffed with // the value found if available. BOOL selectGetGroup(LLUUID& id); BOOL selectGetPerm( U8 which_perm, U32* mask_on, U32* mask_off); // TRUE if all have data, returns two masks, each indicating which bits are all on and all off BOOL selectIsGroupOwned(); // TRUE if all root objects have valid data and are group owned. // returns TRUE if all the nodes are valid. Accumulates // permissions in the parameter. BOOL selectGetPermissions(LLPermissions& perm); // returns TRUE if all the nodes are valid. Depends onto "edit linked" state // Children in linksets are a bit special - they require not only move permission // but also modify if "edit linked" is set, since you move them relative to parent BOOL selectGetEditMoveLinksetPermissions(bool &move, bool &modify); // Get a bunch of useful sale information for the object(s) selected. // "_mixed" is true if not all objects have the same setting. void selectGetAggregateSaleInfo(U32 &num_for_sale, BOOL &is_for_sale_mixed, BOOL &is_sale_price_mixed, S32 &total_sale_price, S32 &individual_sale_price); // returns TRUE if all nodes are valid. BOOL selectGetCategory(LLCategory& category); // returns TRUE if all nodes are valid. method also stores an // accumulated sale info. BOOL selectGetSaleInfo(LLSaleInfo& sale_info); // returns TRUE if all nodes are valid. fills passed in object // with the aggregate permissions of the selection. BOOL selectGetAggregatePermissions(LLAggregatePermissions& ag_perm); // returns TRUE if all nodes are valid. fills passed in object // with the aggregate permissions for texture inventory items of the selection. BOOL selectGetAggregateTexturePermissions(LLAggregatePermissions& ag_perm); LLPermissions* findObjectPermissions(const LLViewerObject* object); BOOL isMovableAvatarSelected(); void selectDelete(); // Delete on simulator void selectForceDelete(); // just delete, no into trash void selectDuplicate(const LLVector3& offset, BOOL select_copy); // Duplicate on simulator void repeatDuplicate(); void selectDuplicateOnRay(const LLVector3 &ray_start_region, const LLVector3 &ray_end_region, BOOL bypass_raycast, BOOL ray_end_is_intersection, const LLUUID &ray_target_id, BOOL copy_centers, BOOL copy_rotates, BOOL select_copy); void sendMultipleUpdate(U32 type); // Position, rotation, scale all in one void sendOwner(const LLUUID& owner_id, const LLUUID& group_id, BOOL override = FALSE); void sendGroup(const LLUUID& group_id); // Category ID is the UUID of the folder you want to contain the purchase. // *NOTE: sale_info check doesn't work for multiple object buy, // which UI does not currently support sale info is used for // verification only, if it doesn't match region info then sale is // canceled void sendBuy(const LLUUID& buyer_id, const LLUUID& category_id, const LLSaleInfo sale_info); void sendAttach(U8 attachment_point, bool replace); void sendAttach(LLObjectSelectionHandle selection_handle, U8 attachment_point, bool replace); void sendDetach(); void sendDropAttachment(); void sendLink(); void sendDelink(); //void sendHinge(U8 type); //void sendDehinge(); void sendSelect(); void requestObjectPropertiesFamily(LLViewerObject* object); // asks sim for creator, permissions, resources, etc. static void processObjectProperties(LLMessageSystem *mesgsys, void **user_data); static void processObjectPropertiesFamily(LLMessageSystem *mesgsys, void **user_data); static void processForceObjectSelect(LLMessageSystem* msg, void**); void requestGodInfo(); LLVector3d getSelectionCenterGlobal() const { return mSelectionCenterGlobal; } void updateSelectionCenter(); void pauseAssociatedAvatars(); void resetAgentHUDZoom(); void setAgentHUDZoom(F32 target_zoom, F32 current_zoom); void getAgentHUDZoom(F32 &target_zoom, F32 &current_zoom) const; void updatePointAt(); // Internal list maintenance functions. TODO: Make these private! void remove(std::vector<LLViewerObject*>& objects); void remove(LLViewerObject* object, S32 te = SELECT_ALL_TES, BOOL undoable = TRUE); void removeAll(); void addAsIndividual(LLViewerObject* object, S32 te = SELECT_ALL_TES, BOOL undoable = TRUE); void promoteSelectionToRoot(); void demoteSelectionToIndividuals(); private: void convertTransient(); // converts temporarily selected objects to full-fledged selections ESelectType getSelectTypeForObject(LLViewerObject* object); void addAsFamily(std::vector<LLViewerObject*>& objects, BOOL add_to_end = FALSE); void generateSilhouette(LLSelectNode *nodep, const LLVector3& view_point); void updateSelectionSilhouette(LLObjectSelectionHandle object_handle, S32& num_sils_genned, std::vector<LLViewerObject*>& changed_objects); // Send one message to each region containing an object on selection list. void sendListToRegions( const std::string& message_name, void (*pack_header)(void *user_data), void (*pack_body)(LLSelectNode* node, void *user_data), void (*log_func)(LLSelectNode* node, void *user_data), void *user_data, ESendType send_type); void sendListToRegions( LLObjectSelectionHandle selected_handle, const std::string& message_name, void (*pack_header)(void *user_data), void (*pack_body)(LLSelectNode* node, void *user_data), void (*log_func)(LLSelectNode* node, void *user_data), void *user_data, ESendType send_type); static void packAgentID( void *); static void packAgentAndSessionID(void* user_data); static void packAgentAndGroupID(void* user_data); static void packAgentAndSessionAndGroupID(void* user_data); static void packAgentIDAndSessionAndAttachment(void*); static void packAgentGroupAndCatID(void*); static void packDeleteHeader(void* userdata); static void packDeRezHeader(void* user_data); static void packObjectID( LLSelectNode* node, void *); static void packObjectIDAsParam(LLSelectNode* node, void *); static void packObjectIDAndRotation(LLSelectNode* node, void *); static void packObjectLocalID(LLSelectNode* node, void *); static void packObjectClickAction(LLSelectNode* node, void* data); static void packObjectIncludeInSearch(LLSelectNode* node, void* data); static void packObjectName(LLSelectNode* node, void* user_data); static void packObjectDescription(LLSelectNode* node, void* user_data); static void packObjectCategory(LLSelectNode* node, void* user_data); static void packObjectSaleInfo(LLSelectNode* node, void* user_data); static void packBuyObjectIDs(LLSelectNode* node, void* user_data); static void packDuplicate( LLSelectNode* node, void *duplicate_data); static void packDuplicateHeader(void*); static void packDuplicateOnRayHead(void *user_data); static void packPermissions(LLSelectNode* node, void *user_data); static void packDeselect( LLSelectNode* node, void *user_data); static void packMultipleUpdate(LLSelectNode* node, void *user_data); static void packPhysics(LLSelectNode* node, void *user_data); static void packShape(LLSelectNode* node, void *user_data); static void packOwnerHead(void *user_data); static void packHingeHead(void *user_data); static void packPermissionsHead(void* user_data); static void packGodlikeHead(void* user_data); static void logNoOp(LLSelectNode* node, void *user_data); static void logAttachmentRequest(LLSelectNode* node, void *user_data); static void logDetachRequest(LLSelectNode* node, void *user_data); static bool confirmDelete(const LLSD& notification, const LLSD& response, LLObjectSelectionHandle handle); // Get the first ID that matches test and whether or not all ids are identical in selected objects. void getFirst(LLSelectGetFirstTest* test); public: // Observer/callback support for when object selection changes or // properties are received/updated typedef boost::signals2::signal< void ()> update_signal_t; update_signal_t mUpdateSignal; private: LLPointer<LLViewerTexture> mSilhouetteImagep; LLObjectSelectionHandle mSelectedObjects; LLObjectSelectionHandle mHoverObjects; LLObjectSelectionHandle mHighlightedObjects; std::set<LLPointer<LLViewerObject> > mRectSelectedObjects; LLObjectSelection mGridObjects; LLQuaternion mGridRotation; LLVector3 mGridOrigin; LLVector3 mGridScale; EGridMode mGridMode; BOOL mTEMode; // render te LLRender::eTexIndex mTextureChannel; // diff, norm, or spec, depending on UI editing mode LLVector3d mSelectionCenterGlobal; LLBBox mSelectionBBox; LLVector3d mLastSentSelectionCenterGlobal; BOOL mShowSelection; // do we send the selection center name value and do we animate this selection? LLVector3d mLastCameraPos; // camera position from last generation of selection silhouette BOOL mRenderSilhouettes; // do we render the silhouette LLBBox mSavedSelectionBBox; LLFrameTimer mEffectsTimer; BOOL mForceSelection; std::vector<LLAnimPauseRequest> mPauseRequests; // <FS:KC> show/hide build highlight EFSShowHideHighlight mFSShowHideHighlight; // </FS:KC> // <FS:Zi> Warning when trying to duplicate while in edit linked parts/select face mode public: // returns TRUE if current selection does not contain individual selections // (edit linked parts, select face) BOOL selectGetNoIndividual(); // </FS:Zi> }; // *DEPRECATED: For callbacks or observers, use // LLSelectMgr::getInstance()->mUpdateSignal.connect( callback ) // Update subscribers to the selection list void dialog_refresh_all(); // Templates //----------------------------------------------------------------------------- // getSelectedTEValue //----------------------------------------------------------------------------- template <typename T> bool LLObjectSelection::getSelectedTEValue(LLSelectedTEGetFunctor<T>* func, T& res, bool has_tolerance, T tolerance) { bool have_first = false; bool have_selected = false; T selected_value = T(); // Now iterate through all TEs to test for sameness bool identical = TRUE; for (iterator iter = begin(); iter != end(); iter++) { LLSelectNode* node = *iter; LLViewerObject* object = node->getObject(); S32 selected_te = -1; if (object == getPrimaryObject()) { selected_te = node->getLastSelectedTE(); } for (S32 te = 0; te < object->getNumTEs(); ++te) { if (!node->isTESelected(te)) { continue; } T value = func->get(object, te); if (!have_first) { have_first = true; if (!have_selected) { selected_value = value; } } else { if ( value != selected_value ) { if (!has_tolerance) { identical = false; } else if (!LLCheckIdenticalFunctor<T>::same(value, selected_value, tolerance)) { identical = false; } } if (te == selected_te) { selected_value = value; have_selected = true; } } } if (!identical && have_selected) { break; } } if (have_first || have_selected) { res = selected_value; } return identical; } // Templates //----------------------------------------------------------------------------- // isMultipleTEValue iterate through all TEs and test for uniqueness // with certain return value ignored when performing the test. // e.g. when testing if the selection has a unique non-empty homeurl : // you can set ignore_value = "" and it will only compare among the non-empty // homeUrls and ignore the empty ones. //----------------------------------------------------------------------------- template <typename T> bool LLObjectSelection::isMultipleTEValue(LLSelectedTEGetFunctor<T>* func, const T& ignore_value) { bool have_first = false; T selected_value = T(); // Now iterate through all TEs to test for sameness bool unique = TRUE; for (iterator iter = begin(); iter != end(); iter++) { LLSelectNode* node = *iter; LLViewerObject* object = node->getObject(); for (S32 te = 0; te < object->getNumTEs(); ++te) { if (!node->isTESelected(te)) { continue; } T value = func->get(object, te); if(value == ignore_value) { continue; } if (!have_first) { have_first = true; } else { if (value !=selected_value ) { unique = false; return !unique; } } } } return !unique; } #endif
35.175614
160
0.736018
[ "render", "object", "vector" ]
bb07cdcca08d9ef17dc126263505abd811d098fb
7,391
h
C
src/bpmat/GSEP.h
rsanfer/tacs
32cf876d60279d5a448f91ac9a0b35b056865e5d
[ "Apache-2.0" ]
1
2021-02-17T11:56:46.000Z
2021-02-17T11:56:46.000Z
src/bpmat/GSEP.h
rsanfer/tacs
32cf876d60279d5a448f91ac9a0b35b056865e5d
[ "Apache-2.0" ]
2
2020-06-29T12:42:37.000Z
2020-10-14T18:03:37.000Z
src/bpmat/GSEP.h
rsanfer/tacs
32cf876d60279d5a448f91ac9a0b35b056865e5d
[ "Apache-2.0" ]
5
2020-04-27T20:04:34.000Z
2021-07-15T13:04:15.000Z
/* This file is part of TACS: The Toolkit for the Analysis of Composite Structures, a parallel finite-element code for structural and multidisciplinary design optimization. Copyright (C) 2010 University of Toronto Copyright (C) 2012 University of Michigan Copyright (C) 2014 Georgia Tech Research Corporation Additional copyright (C) 2010 Graeme J. Kennedy and Joaquim R.R.A. Martins All rights reserved. TACS is licensed under the Apache License, Version 2.0 (the "License"); you may not use this software except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 */ #ifndef TACS_GSEP_H #define TACS_GSEP_H #include "KSM.h" /*! The following contains classes required for computation of general, symmetric eigenvalue problems (GSEP). The Lanczos method is used to construct an orthonormal basis of a Krylov subspace. This method produces a tri-diagonal Hessenberg matrix. Approximate eigenvalues of the full matrix may be found by discarding the last row of the rectangular - equivalent to projecting the matrix onto the orthonormal basis - and computing the eigenvalues of the much smaller system. The method is implemented in a block-form such that operations are performed with a block-size of P. Solve the eigenvalue problem: A x = lambda B x */ class EPOperator : public TACSObject { public: virtual ~EPOperator(){} // Create a vector associated with this operator // --------------------------------------------- virtual TACSVec *createVec() = 0; // Compute y = A *x // ----------------- virtual void mult( TACSVec *x, TACSVec *y ) = 0; // Compute the inner product <x,y> // ------------------------------- virtual TacsScalar dot( TACSVec *x, TACSVec *y ){ return x->dot(y); } // Compute || B *x || - this is used to compute the eigenvalue error // ------------------------------------------------------------------ virtual TacsScalar errorNorm( TACSVec *x ){ return 1.0; } // Convert the shifted spectrum back to the regular spectrum // --------------------------------------------------------- virtual TacsScalar convertEigenvalue( TacsScalar value ){ return value; } }; /*! Solve the regular eigenvalue problem without any shift/invert operations */ class EPRegular : public EPOperator { public: EPRegular( TACSMat *_mat ); ~EPRegular(); TACSVec *createVec(); void mult( TACSVec *x, TACSVec *y ); private: TACSMat *mat; }; /*! Shift and invert the spectrum */ class EPShiftInvert : public EPOperator { public: EPShiftInvert( TacsScalar _sigma, TACSKsm *_ksm ); ~EPShiftInvert(); TACSVec *createVec(); void mult( TACSVec *x, TACSVec *y ); // The eigenvalues are computed as mu = 1.0/( eig - sigma ) // eig = 1.0/mu + sigma TacsScalar convertEigenvalue( TacsScalar value ); private: TACSKsm *ksm; TacsScalar sigma; }; /*! Solve the generalized eigenvalue problem, A x = lambda B x Here B must be positive definite. The following shifted problem is solved, ( A - sigma B )^{-1} B x = 1.0/( lambda - sigma ) x In this case the B-inner products must be used so inner = B. */ class EPGeneralizedShiftInvert : public EPOperator { public: EPGeneralizedShiftInvert( TacsScalar _sigma, TACSKsm *_ksm, TACSMat *_inner ); ~EPGeneralizedShiftInvert(); void setSigma( TacsScalar _sigma ); TACSVec *createVec(); void mult( TACSVec *x, TACSVec *y ); // Compute y = (A - sigma B)^{-1}*inner*x TacsScalar dot( TACSVec *x, TACSVec *y ); // Compute <x,y> = x^{T}*inner*y TacsScalar errorNorm( TACSVec *x ); TacsScalar convertEigenvalue( TacsScalar value ); private: TacsScalar sigma; TACSKsm *ksm; TACSMat *inner; TACSVec *temp; }; /* Solve a generalized eigenvalue problem for a buckling problem, A x = - lambda B x (Note the sign!) Here A = K, must be positive definite, but B does not need to be. The shifted problem is, (A - sigma B)^{-1} A x = lambda/(lambda + sigma) x Here A-inner products are required, so inner = A. */ class EPBucklingShiftInvert : public EPOperator { public: EPBucklingShiftInvert( TacsScalar _sigma, TACSKsm *_ksm, TACSMat *_inner ); ~EPBucklingShiftInvert(); void setSigma( TacsScalar _sigma ); TACSVec *createVec(); void mult( TACSVec *x, TACSVec *y ); // Compute y = (A - sigma B)^{-1}*inner*x TacsScalar dot( TACSVec *x, TACSVec *y ); // Compute <x,y> = x^{T}*inner*y TacsScalar errorNorm( TACSVec *x ); TacsScalar convertEigenvalue( TacsScalar value ); private: TacsScalar sigma; TACSKsm *ksm; TACSMat *inner; TACSVec *temp; }; /* The symmetric eigenvalue solver. This eigensolver can be used to solve either simple or generalized eigenvalue problems depending on the definition of the operator. The operator may also use a shift and invert strategy to accelerate convergence of the Lanczos method. Note that the full orthogonalization is suggested (and is the default) since this has better numerical properties. The Lanczos vectors lose orthogonality as the eigenvalues converge. */ class SEP : public TACSObject { public: // Set the type of orthogonalization to use enum OrthoType { FULL, LOCAL }; enum EigenSpectrum { SMALLEST, LARGEST, SMALLEST_MAGNITUDE, LARGEST_MAGNITUDE }; SEP( EPOperator *_Op, int _max_iters, OrthoType _ortho_type=FULL, TACSBcMap *_bcs=NULL ); ~SEP(); // Set the orthogonalization strategy void setOrthoType( OrthoType _ortho_type ); // Set the solution tolerances, type of spectrum and number of eigenvalues void setTolerances( double _tol, EigenSpectrum _spectrum, int _neigvals ); // Reset the eigenproblem operator void setOperator( EPOperator *_Op ); // Solve the eigenproblem void solve( KSMPrint *ksm_print=NULL, KSMPrint *ksm_file=NULL ); // Extract the eigenvalues and eigenvectors from the solver TacsScalar extractEigenvalue( int n, TacsScalar *error ); TacsScalar extractEigenvector( int n, TACSVec *ans, TacsScalar *error ); // Check the orthogonality of the Lanczos subspace (expensive) TacsScalar checkOrthogonality(); void printOrthogonality(); private: // Sort the eigenvalues by the desired spectrum void sortEigenvalues( TacsScalar *values, int neigs, int *permutation ); // Check whether the right eigenvalues have converged int checkConverged( TacsScalar *A, TacsScalar *B, int n ); // Data used to determine which spectrum to use and when // enough eigenvalues are converged double tol; enum EigenSpectrum spectrum; int neigvals; // The eigenproblem operator object EPOperator *Op; // The number of iterations completed thus far int niters; // The coefficients of the symmetric tridiagonal matrix TacsScalar *Alpha, *Beta; // Eigenvalues/eigenvectors of the tridiagonal matrix TacsScalar *eigs, *eigvecs; // Permutation yielding an ascending ordering of the eigenvalues after // the shift has been applied int *perm; // The type of orthogonalization to use OrthoType ortho_type; int max_iters; TACSVec **Q; // The Vectors for the eigenvalue problem... // Boundary conditions that are applied TACSBcMap *bcs; }; #endif // TACS_GSEP_H
29.446215
80
0.685022
[ "object", "vector" ]
bb07eb82a26011cf33040b2bd669fbf36bb7162b
883
c
C
arrays/main.c
lucchmielowski/clang-practice
71eec60e2954756f2b304cd87ade16cfd67e3a4d
[ "MIT" ]
null
null
null
arrays/main.c
lucchmielowski/clang-practice
71eec60e2954756f2b304cd87ade16cfd67e3a4d
[ "MIT" ]
null
null
null
arrays/main.c
lucchmielowski/clang-practice
71eec60e2954756f2b304cd87ade16cfd67e3a4d
[ "MIT" ]
null
null
null
#include<stdio.h> #include<stdlib.h> #include "vector.c" void run_example(); int main() { //run_all_tests(); run_example(); return EXIT_SUCCESS; } void run_example() { int capacity = 0; printf("Enter how many numbers would you like to store : \n"); scanf("%d", &capacity); printf("You'll be storing %d elements\n", capacity); JArray* arrptr = jarray_new(capacity); for (int d = 1; d <= capacity; d++) { jarray_push(arrptr, d); } printf("Inserting value :\n"); jarray_insert(arrptr, 12, 3); printf("Prepend value\n"); jarray_prepend(arrptr, 444); int popped = jarray_pop(arrptr); printf("Popped value : %d\n", popped); jarray_delete(arrptr, 2); jarray_remove(arrptr, 12); printf("jarray_find(5) Result : %d\n", jarray_find(arrptr, 5)); jarray_print(arrptr); jarray_destroy(arrptr); }
22.075
67
0.626274
[ "vector" ]
bb08abc4215afce312f34c06118b2338126229b8
6,108
c
C
win/gnome/gnglyph.c
Bam4d/BrowserHack
1a7de3a7db8ff88aaeb4a8277739586251db04e5
[ "CC-BY-3.0" ]
318
2015-04-08T17:21:29.000Z
2022-03-24T21:16:43.000Z
win/gnome/gnglyph.c
schwabse/BrowserHack
1a7de3a7db8ff88aaeb4a8277739586251db04e5
[ "CC-BY-3.0" ]
21
2015-04-12T18:27:16.000Z
2021-11-15T07:02:27.000Z
win/gnome/gnglyph.c
schwabse/BrowserHack
1a7de3a7db8ff88aaeb4a8277739586251db04e5
[ "CC-BY-3.0" ]
51
2015-04-08T17:59:07.000Z
2022-02-24T10:10:30.000Z
/* SCCS Id: @(#)gnglyph.c 3.4 2000/07/16 */ /* Copyright (C) 1998 by Erik Andersen <andersee@debian.org> */ /* NetHack may be freely redistributed. See license for details. */ #include "gnglyph.h" #include "tile2x11.h" /* from tile.c */ extern int total_tiles_used; static GHackGlyphs ghack_glyphs; static GdkImlibImage** ghack_tiles = NULL; /* NAME: * ghack_init_glyphs(char* xpm_file) * * ARGUMENTS: * char *xpm_file -- The name of the image file. * May be any image format imlib recognizes. * Does not have to be XPM. * * RETURNS: * TRUE upon successful loading of the glyphs. * FALSE upon failure. * * PURPOSE: * Constructor for the Glyph object. Well, really each glyph * object is a collection of glyphs, or tiles. This constructor * takes a single argument: the name of the image file that contains * the tile images. * * NOTES: * The glyphs (tiles) must be in the image in a certain way: the * glyphs must be stacked such that the resultant image is * TILE_X * TILES_PER_ROW wide, and * TILE_Y * (number of glyphs) / TILES_PER_ROW high (rounded up). * In this sense, TILE_X == TILE_Y, and can be any reasonable integer * say, 16 <= TILE_X <= 64. Because the glyph number is tightly * coupled to the Nethack object it represents, the order of the * glyphs in the image is imporant: Glyph 1 is at the top of the * image, while Glyph N (the last glyph) is at the bottom. * * What's the difference between a glyph and a tile? Well, a * tile is just an image. A glyph is a tile that knows its * place in line. * * This initializer relies heavily on gdk_imlib. Thanks, Rasterman. */ int ghack_init_glyphs(const char *xpmFile) { ghack_glyphs.im = gdk_imlib_load_image((char *) xpmFile); if ( ! ghack_glyphs.im ) { g_error("Couldn't load required xpmFile!"); return -1; } gdk_imlib_render(ghack_glyphs.im, ghack_glyphs.im->rgb_width, ghack_glyphs.im->rgb_height); if ((ghack_glyphs.im->rgb_width % TILES_PER_ROW) != 0 || ghack_glyphs.im->rgb_width <= TILES_PER_ROW) { g_error("%s is not a multiple of %d (number of tiles/row) pixels wide", xpmFile, TILES_PER_ROW); return -1; } ghack_glyphs.count = total_tiles_used; if ((ghack_glyphs.count % TILES_PER_ROW) != 0) { ghack_glyphs.count += TILES_PER_ROW - (ghack_glyphs.count % TILES_PER_ROW); } ghack_glyphs.width = ghack_glyphs.im->rgb_width / TILES_PER_ROW; ghack_glyphs.height = ghack_glyphs.im->rgb_height / (ghack_glyphs.count / TILES_PER_ROW); /* Assume the tiles are organized in rows of TILES_PER_ROW */ ghack_tiles = g_new0( GdkImlibImage*, ghack_glyphs.count ); return (ghack_tiles == NULL) ? -1 : 0; } void ghack_free_glyphs( ) { int i; for ( i=0 ; i<ghack_glyphs.count ; i++) gdk_imlib_destroy_image(ghack_tiles[i]); g_free( ghack_tiles); gdk_imlib_destroy_image(ghack_glyphs.im); ghack_glyphs.im=NULL; } /* NAME: * ghack_glyph_count( ) * * ARGUMENTS: * None. * * RETURNS: * int -- The number of glyphs in this object. * * PURPOSE: * Simply reports the number of glyphs in this object. */ int ghack_glyph_count( ) { return ghack_glyphs.count; } /* NAME: * ghack_glyph_height() * * ARGUMENTS: * None * * RETURNS: * int -- The glyph height. * * PURPOSE: * Returns the standard glyph height. */ int ghack_glyph_height() { return ghack_glyphs.height; } /* NAME: * ghack_glyph_width() * * ARGUMENTS: * None * * RETURNS: * int -- The glyph width. * * PURPOSE: * Returns the standard glyph width. */ int ghack_glyph_width() { return ghack_glyphs.width; } /* NAME: * ghack_image_from_glyph( int glyph, gboolean force) * * ARGUMENTS: * int glyph -- The glyph number. * gboolean force -- force it to re-render. * * RETURNS: * GdkImlibImage* -- The glyph image, as a GdkImlibImage. * * PURPOSE: * Decodes the glyph into an image suitable for manipulation */ GdkImlibImage* ghack_image_from_glyph( int glyph, gboolean force ) { int tile = glyph2tile[glyph]; if ( tile >= ghack_glyphs.count || tile < 0 ) { g_warning("Aiiee! I've was asked for a tile outside the allowed range!\n" "Email this to other-gnomehack@lists.debian.org"); g_warning("Max tile: %d Tile asked for: %d", ghack_glyphs.count, tile); return NULL; } if (ghack_glyphs.im == NULL) { g_warning("Aiiee! I've been asked to clone from a null image.\n" "Email this to other-gnomehack@lists.debian.org"); g_warning( "making image from tile %d, force=%s\n", tile, (force==TRUE)? "TRUE": "FALSE"); } if (force == TRUE) { g_warning("Aiiee! I've been asked to force rendering.\n" "Email this to other-gnomehack@lists.debian.org"); g_warning( "making image from tile %d, force=%s\n", tile, (force==TRUE)? "TRUE" : "FALSE"); } if (!ghack_tiles[tile] || force) { int src_x, src_y; #if 0 fprintf( stderr, "crop_and_clone: glyph=%d, tile=%d, ptr=%p, x=%d, y=%d, w=%d, h=%d\n", glyph, tile, (void*)&(ghack_tiles[tile]), 0, tile * ghack_glyphs.width, ghack_glyphs.height, ghack_glyphs.width); #endif if (ghack_glyphs.im->pixmap == NULL) g_warning( "Aiiee! ghack_glyphs.im->pixmap==NULL!!!!\n"); src_x = (tile % TILES_PER_ROW) * ghack_glyphs.width; src_y = (tile / TILES_PER_ROW) * ghack_glyphs.height; ghack_tiles[tile] = gdk_imlib_crop_and_clone_image(ghack_glyphs.im, src_x, src_y, ghack_glyphs.width, ghack_glyphs.height); } if (ghack_tiles[tile] && (!ghack_tiles[tile]->pixmap || force)) { if ( gdk_imlib_render(ghack_tiles[tile], ghack_tiles[tile]->rgb_width, ghack_tiles[tile]->rgb_height) == 0) { g_error("GLYPH: couldn't create tile # %d", tile); } if ( !ghack_tiles[tile]->pixmap ) g_error("Strange, tile # %d didn't get rendered???", tile); } return ghack_tiles[tile]; }
26.441558
106
0.646202
[ "render", "object" ]
bb0a2f157bd0c05f0b5a806924c5ff503b556af8
996
h
C
src/collection/smalldoublelinkedlist.h
thm-mni-ii/sea
3d3f63c3d17ab91f0aaada3c4315ba98367a3460
[ "MIT" ]
17
2019-01-03T11:17:31.000Z
2021-10-31T19:19:41.000Z
src/collection/smalldoublelinkedlist.h
thm-mni-ii/sea
3d3f63c3d17ab91f0aaada3c4315ba98367a3460
[ "MIT" ]
106
2018-03-03T16:37:17.000Z
2020-08-31T09:24:52.000Z
src/collection/smalldoublelinkedlist.h
thm-mni-ii/sea
3d3f63c3d17ab91f0aaada3c4315ba98367a3460
[ "MIT" ]
4
2018-05-21T13:30:01.000Z
2019-06-12T07:43:43.000Z
#ifndef SRC_COLLECTION_SMALLDOUBLELINKEDLIST_H_ #define SRC_COLLECTION_SMALLDOUBLELINKEDLIST_H_ #include "doublelinkedlist.h" #include <vector> #include <ostream> namespace Sealib { /** * Implementation of the interface provided by DoubleLinkedList for words of size 8bits. */ class SmallDoubleLinkedList : public DoubleLinkedList { private: std::vector<uint8_t> links; uint8_t current; public: explicit SmallDoubleLinkedList(uint8_t size); ~SmallDoubleLinkedList() override = default; /** * @return the currently pointed to value and removes it, or (uint8_t)-1 if empty. */ uint64_t get() override; /** * @param idx element to be removed * @return the removed element, or (uint8_t)-1 if the element was not present. */ uint64_t remove(uint64_t idx) override; /** * @return - true if empty, false otherwise */ bool isEmpty() override; }; } // namespace Sealib #endif // SRC_COLLECTION_SMALLDOUBLELINKEDLIST_H_
26.918919
88
0.709839
[ "vector" ]
bb0f3a2a8c6607f593417f9f316b84976340ca15
8,388
c
C
matmul-iree/src/matmul_generator.c
chudur-budur/mmperf
c82e64e29104c10a85cbb5f1f759387f72283701
[ "Apache-2.0" ]
45
2021-01-27T10:37:51.000Z
2022-03-27T06:30:27.000Z
matmul-iree/src/matmul_generator.c
chudur-budur/mmperf
c82e64e29104c10a85cbb5f1f759387f72283701
[ "Apache-2.0" ]
13
2021-08-18T14:53:43.000Z
2022-03-26T18:47:32.000Z
matmul-iree/src/matmul_generator.c
chudur-budur/mmperf
c82e64e29104c10a85cbb5f1f759387f72283701
[ "Apache-2.0" ]
21
2021-01-21T18:31:19.000Z
2022-03-15T20:14:56.000Z
// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // Forked from IREE (with modified includes). // A example of setting up the HAL module to run simple pointwise array // multiplication with the device implemented by different backends via // create_sample_driver(). #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <unistd.h> #include <math.h> #include "iree/base/api.h" #include "iree/hal/api.h" #include "iree/modules/hal/module.h" #include "iree/vm/api.h" #include "iree/vm/bytecode_module.h" #include MATMUL_HEADER #define STRING(s) #s #define TO_STRING(x) STRING(x) double rtclock() { struct timezone Tzp; struct timeval Tp; int stat = gettimeofday(&Tp, &Tzp); if (stat != 0) printf("Error return from gettimeofday: %d", stat); return (Tp.tv_sec + Tp.tv_usec * 1.0e-6); } void init_matrix(float *a, int nrows, int ncols) { for (int j = 0; j < ncols; j++) { for (int i = 0; i < nrows; i++) { a[i + j * nrows] = ((float) rand() / (float) RAND_MAX); } } } void naive_matmul(const float *a, const float *b, float *c, size_t m, size_t k, size_t n) { // correctness check for (size_t i = 0; i < m; i++) { for (size_t j = 0; j < n; j++) { size_t ci = i*n + j; c[ci] = 0.0f; for (size_t p = 0; p < k; p++) { c[ci] += a[i*k + p] * b[p*n + j]; } } } } // A function to create the HAL device from the different backend targets. // The HAL device is returned based on the implementation, and it must be // released by the caller. extern iree_status_t create_sample_device(iree_hal_device_t** device); iree_status_t Run() { double t_start, t_end; // TODO(benvanik): move to instance-based registration. IREE_RETURN_IF_ERROR(iree_hal_module_register_types()); iree_vm_instance_t* instance = NULL; IREE_RETURN_IF_ERROR( iree_vm_instance_create(iree_allocator_system(), &instance)); iree_hal_device_t* device = NULL; IREE_RETURN_IF_ERROR(create_sample_device(&device), "create device"); iree_vm_module_t* hal_module = NULL; IREE_RETURN_IF_ERROR( iree_hal_module_create(device, iree_allocator_system(), &hal_module)); // Note the setup here only supports native build. The bytecode is not built // for the cross-compile execution. The code can be compiled but it will // hit runtime error in a cross-compile environment. const struct iree_file_toc_t* module_file_toc = matmul_create(); iree_vm_module_t* bytecode_module = NULL; iree_const_byte_span_t module_data = iree_make_const_byte_span(module_file_toc->data, module_file_toc->size); IREE_RETURN_IF_ERROR(iree_vm_bytecode_module_create( module_data, iree_allocator_null(), iree_allocator_system(), &bytecode_module)); // Allocate a context that will hold the module state across invocations. iree_vm_context_t* context = NULL; iree_vm_module_t* modules[] = {hal_module, bytecode_module}; IREE_RETURN_IF_ERROR(iree_vm_context_create_with_modules( instance, &modules[0], IREE_ARRAYSIZE(modules), iree_allocator_system(), &context)); iree_vm_module_release(hal_module); iree_vm_module_release(bytecode_module); // Lookup the entry point function. // Note that we use the synchronous variant which operates on pure type/shape // erased buffers. const char kMainFunctionName[] = "module.matmul"; iree_vm_function_t main_function; IREE_RETURN_IF_ERROR(iree_vm_context_resolve_function( context, iree_make_cstring_view(kMainFunctionName), &main_function)); // Allocate memory for input static iree_hal_dim_t arg0_shape[] = {MDIM, KDIM}; static iree_hal_dim_t arg1_shape[] = {KDIM, NDIM}; float *arg0 = (float *) malloc(MDIM * KDIM * sizeof(float)); float *arg1 = (float *) malloc(KDIM * NDIM * sizeof(float)); init_matrix(arg0, MDIM, KDIM); init_matrix(arg1, KDIM, NDIM); iree_hal_buffer_view_t* arg0_buffer_view = NULL; iree_hal_buffer_view_t* arg1_buffer_view = NULL; IREE_RETURN_IF_ERROR(iree_hal_buffer_view_wrap_or_clone_heap_buffer( iree_hal_device_allocator(device), arg0_shape, IREE_ARRAYSIZE(arg0_shape), IREE_HAL_ELEMENT_TYPE_FLOAT_32, IREE_HAL_ENCODING_TYPE_DENSE_ROW_MAJOR, IREE_HAL_MEMORY_TYPE_HOST_VISIBLE | IREE_HAL_MEMORY_TYPE_DEVICE_LOCAL, IREE_HAL_MEMORY_ACCESS_ALL, IREE_HAL_BUFFER_USAGE_ALL, iree_make_byte_span((void*)arg0, MDIM * KDIM * sizeof(float)), iree_allocator_null(), &arg0_buffer_view)); IREE_RETURN_IF_ERROR(iree_hal_buffer_view_wrap_or_clone_heap_buffer( iree_hal_device_allocator(device), arg1_shape, IREE_ARRAYSIZE(arg1_shape), IREE_HAL_ELEMENT_TYPE_FLOAT_32, IREE_HAL_ENCODING_TYPE_DENSE_ROW_MAJOR, IREE_HAL_MEMORY_TYPE_HOST_VISIBLE | IREE_HAL_MEMORY_TYPE_DEVICE_LOCAL, IREE_HAL_MEMORY_ACCESS_ALL, IREE_HAL_BUFFER_USAGE_ALL, iree_make_byte_span((void*)arg1, KDIM * NDIM * sizeof(float)), iree_allocator_null(), &arg1_buffer_view)); // Pass in the tensor as an expanded HAL buffer. iree_vm_list_t* inputs = NULL; IREE_RETURN_IF_ERROR(iree_vm_list_create( /*element_type=*/NULL, /*capacity=*/2, iree_allocator_system(), &inputs), "can't allocate input vm list"); iree_vm_ref_t arg0_input_buffer_view_ref = iree_hal_buffer_view_move_ref(arg0_buffer_view); IREE_RETURN_IF_ERROR( iree_vm_list_push_ref_move(inputs, &arg0_input_buffer_view_ref)); iree_vm_ref_t arg1_input_buffer_view_ref = iree_hal_buffer_view_move_ref(arg1_buffer_view); IREE_RETURN_IF_ERROR( iree_vm_list_push_ref_move(inputs, &arg1_input_buffer_view_ref)); iree_vm_list_t* outputs = NULL; IREE_RETURN_IF_ERROR(iree_vm_list_create( /*element_type=*/NULL, /*capacity=*/1, iree_allocator_system(), &outputs), "can't allocate output vm list"); t_start = rtclock(); for (int t = 0; t < NUM_REPS; ++t) { // Synchronously invoke the function. IREE_RETURN_IF_ERROR(iree_vm_invoke(context, main_function, /*policy=*/NULL, inputs, outputs, iree_allocator_system())); } // Get the result buffers from the invocation. iree_hal_buffer_view_t* ret_buffer_view = (iree_hal_buffer_view_t*)iree_vm_list_get_ref_deref( outputs, 0, iree_hal_buffer_view_get_descriptor()); if (ret_buffer_view == NULL) { return iree_make_status(IREE_STATUS_NOT_FOUND, "can't find return buffer view"); } t_end = rtclock(); // Read back the results and ensure we got the right values. iree_hal_buffer_mapping_t mapped_memory; float *C = (float *) malloc(MDIM * NDIM * sizeof(float)); IREE_RETURN_IF_ERROR(iree_hal_buffer_map_range( iree_hal_buffer_view_buffer(ret_buffer_view), IREE_HAL_MEMORY_ACCESS_READ, 0, IREE_WHOLE_BUFFER, &mapped_memory)); for (int i = 0; i < mapped_memory.contents.data_length / sizeof(float); ++i) { // Accessing the output elements C[i] = ((const float*)mapped_memory.contents.data)[i]; } const char *filename = TO_STRING(FILE_NAME); FILE *file = fopen(filename, "w"); fprintf(file, "%0.5lf GFLOPS\n", 2.0 * NUM_REPS * MDIM * NDIM * KDIM / (t_end - t_start) / 1E9); fclose(file); #ifdef ENABLE_CHECK float *C2 = (float *) malloc(MDIM * NDIM * sizeof(float)); size_t errors = 0; naive_matmul(arg0,arg1,C2,MDIM,KDIM,NDIM); for (size_t i = 0; i < MDIM; i++) { for (size_t j = 0; j < NDIM; j++) { size_t ci = i + j*MDIM; if (fabs(C[ci] - C2[ci]) > 0.01f) { errors++; } } } printf("Detected %ld errors.\n", errors); #endif iree_hal_buffer_unmap_range(&mapped_memory); free(arg0); free(arg1); iree_vm_list_release(inputs); iree_vm_list_release(outputs); iree_hal_device_release(device); iree_vm_context_release(context); iree_vm_instance_release(instance); return iree_ok_status(); } int main() { const iree_status_t result = Run(); if (!iree_status_is_ok(result)) { iree_status_fprint(stderr, result); iree_status_free(result); } printf("matmul execution succeeded\n"); return 0; }
35.846154
98
0.70267
[ "shape" ]
bb11176dc93559c420e26f8ce6efadc4681fbe9e
3,388
c
C
coreapi/help/helloworld.c
ameeno/linphone.git.clone
7c03fefec58c2bbef0015eeb59e5a28fee2e752d
[ "BSD-2-Clause" ]
null
null
null
coreapi/help/helloworld.c
ameeno/linphone.git.clone
7c03fefec58c2bbef0015eeb59e5a28fee2e752d
[ "BSD-2-Clause" ]
null
null
null
coreapi/help/helloworld.c
ameeno/linphone.git.clone
7c03fefec58c2bbef0015eeb59e5a28fee2e752d
[ "BSD-2-Clause" ]
null
null
null
/* linphone Copyright (C) 2010 Belledonne Communications SARL (simon.morlat@linphone.org) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @defgroup basic_call_tutorials Basic call * @ingroup tutorials This program is a _very_ simple usage example of liblinphone. It just takes a sip-uri as first argument and attempts to call it @include helloworld.c */ #ifdef IN_LINPHONE #include "linphonecore.h" #else #include "linphone/linphonecore.h" #endif #include <signal.h> static bool_t running=TRUE; static void stop(int signum){ running=FALSE; } /* * Call state notification callback */ static void call_state_changed(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState cstate, const char *msg){ switch(cstate){ case LinphoneCallOutgoingRinging: printf("It is now ringing remotely !\n"); break; case LinphoneCallOutgoingEarlyMedia: printf("Receiving some early media\n"); break; case LinphoneCallConnected: printf("We are connected !\n"); break; case LinphoneCallStreamsRunning: printf("Media streams established !\n"); break; case LinphoneCallEnd: printf("Call is terminated.\n"); break; case LinphoneCallError: printf("Call failure !"); break; default: printf("Unhandled notification %i\n",cstate); } } int main(int argc, char *argv[]){ LinphoneCoreVTable vtable={0}; LinphoneCore *lc; LinphoneCall *call=NULL; const char *dest=NULL; /* take the destination sip uri from the command line arguments */ if (argc>1){ dest=argv[1]; } signal(SIGINT,stop); #ifdef DEBUG linphone_core_enable_logs(NULL); /*enable liblinphone logs.*/ #endif /* Fill the LinphoneCoreVTable with application callbacks. All are optional. Here we only use the call_state_changed callbacks in order to get notifications about the progress of the call. */ vtable.call_state_changed=call_state_changed; /* Instanciate a LinphoneCore object given the LinphoneCoreVTable */ lc=linphone_core_new(&vtable,NULL,NULL,NULL); if (dest){ /* Place an outgoing call */ call=linphone_core_invite(lc,dest); if (call==NULL){ printf("Could not place call to %s\n",dest); goto end; }else printf("Call to %s is in progress...",dest); linphone_call_ref(call); } /* main loop for receiving notifications and doing background linphonecore work: */ while(running){ linphone_core_iterate(lc); ms_usleep(50000); } if (call && linphone_call_get_state(call)!=LinphoneCallEnd){ /* terminate the call */ printf("Terminating the call...\n"); linphone_core_terminate_call(lc,call); /*at this stage we don't need the call object */ linphone_call_unref(call); } end: printf("Shutting down...\n"); linphone_core_destroy(lc); printf("Exited\n"); return 0; }
25.862595
112
0.739374
[ "object" ]
bb1321caf27459185c2f2e2579476935d2f56fd7
3,719
h
C
lib/src/main/jni/ndk-modules/proj.4/proj-4.8.0/proj/src/org_proj4_PJ.h
tellandev/android-spatialite
33337fb01316ed3d491dae4b5e32208327890cfa
[ "Apache-1.1" ]
94
2016-12-08T20:37:12.000Z
2022-03-18T08:33:50.000Z
lib/src/main/jni/ndk-modules/proj.4/proj-4.8.0/proj/src/org_proj4_PJ.h
tellandev/android-spatialite
33337fb01316ed3d491dae4b5e32208327890cfa
[ "Apache-1.1" ]
15
2017-06-30T19:46:08.000Z
2021-11-09T19:07:36.000Z
lib/src/main/jni/ndk-modules/proj.4/proj-4.8.0/proj/src/org_proj4_PJ.h
tellandev/android-spatialite
33337fb01316ed3d491dae4b5e32208327890cfa
[ "Apache-1.1" ]
37
2016-12-13T03:53:32.000Z
2022-02-01T14:50:05.000Z
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class org_proj4_PJ */ #ifndef _Included_org_proj4_PJ #define _Included_org_proj4_PJ #ifdef __cplusplus extern "C" { #endif #undef org_proj4_PJ_DIMENSION_MAX #define org_proj4_PJ_DIMENSION_MAX 100L /* * Class: org_proj4_PJ * Method: setDataPath * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_org_proj4_PJ_setDataPath (JNIEnv *, jclass, jstring); /* * Class: org_proj4_PJ * Method: setSearchPaths * Signature: ([Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_org_proj4_PJ_setSearchPaths (JNIEnv *, jclass, jobjectArray); /* * Class: org_proj4_PJ * Method: readGridInfo * Signature: (Ljava/lang/String;)Lorg/proj4/GridInfo; */ JNIEXPORT jobject JNICALL Java_org_proj4_PJ_readGridInfo (JNIEnv *, jclass, jstring); JNIEXPORT jint JNICALL Java_org_proj4_PJ_getGlobalLastErrorCode (JNIEnv *, jclass); JNIEXPORT jstring JNICALL Java_org_proj4_PJ_getGlobalLastErrorString (JNIEnv *, jclass); /* * Class: org_proj4_PJ * Method: allocatePJ * Signature: (Ljava/lang/String;)J */ JNIEXPORT jlong JNICALL Java_org_proj4_PJ_allocatePJ (JNIEnv *, jclass, jstring); /* * Class: org_proj4_PJ * Method: allocateGeoPJ * Signature: (Lorg/proj4/PJ;)J */ JNIEXPORT jlong JNICALL Java_org_proj4_PJ_allocateGeoPJ (JNIEnv *, jclass, jobject); /* * Class: org_proj4_PJ * Method: getVersion * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_org_proj4_PJ_getVersion (JNIEnv *, jclass); /* * Class: org_proj4_PJ * Method: getDefinition * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_org_proj4_PJ_getDefinition (JNIEnv *, jobject); /* * Class: org_proj4_PJ * Method: getType * Signature: ()Lorg/proj4/PJ/Type; */ JNIEXPORT jobject JNICALL Java_org_proj4_PJ_getType (JNIEnv *, jobject); /* * Class: org_proj4_PJ * Method: getSemiMajorAxis * Signature: ()D */ JNIEXPORT jdouble JNICALL Java_org_proj4_PJ_getSemiMajorAxis (JNIEnv *, jobject); /* * Class: org_proj4_PJ * Method: getSemiMinorAxis * Signature: ()D */ JNIEXPORT jdouble JNICALL Java_org_proj4_PJ_getSemiMinorAxis (JNIEnv *, jobject); /* * Class: org_proj4_PJ * Method: getEccentricitySquared * Signature: ()D */ JNIEXPORT jdouble JNICALL Java_org_proj4_PJ_getEccentricitySquared (JNIEnv *, jobject); /* * Class: org_proj4_PJ * Method: getAxisDirections * Signature: ()[C */ JNIEXPORT jcharArray JNICALL Java_org_proj4_PJ_getAxisDirections (JNIEnv *, jobject); /* * Class: org_proj4_PJ * Method: getGreenwichLongitude * Signature: ()D */ JNIEXPORT jdouble JNICALL Java_org_proj4_PJ_getGreenwichLongitude (JNIEnv *, jobject); /* * Class: org_proj4_PJ * Method: getLinearUnitToMetre * Signature: (Z)D */ JNIEXPORT jdouble JNICALL Java_org_proj4_PJ_getLinearUnitToMetre (JNIEnv *, jobject, jboolean); /* * Class: org_proj4_PJ * Method: transform * Signature: (Lorg/proj4/PJ;I[DII)V */ JNIEXPORT void JNICALL Java_org_proj4_PJ_transform (JNIEnv *, jobject, jobject, jint, jdoubleArray, jint, jint); /* * Class: org_proj4_PJ * Method: getLastError * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_org_proj4_PJ_getLastError (JNIEnv *, jobject); /* * Class: org_proj4_PJ * Method: toString * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_org_proj4_PJ_toString (JNIEnv *, jobject); /* * Class: org_proj4_PJ * Method: finalize * Signature: ()V */ JNIEXPORT void JNICALL Java_org_proj4_PJ_finalize (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif
22.269461
68
0.719817
[ "transform" ]
bb14f3922c5324b915737086a5d41d2779f63717
2,687
h
C
match.h
jonathanrlemos/ffind
41822efaeabd0630ba9a2de164552672b7c60430
[ "MIT" ]
null
null
null
match.h
jonathanrlemos/ffind
41822efaeabd0630ba9a2de164552672b7c60430
[ "MIT" ]
null
null
null
match.h
jonathanrlemos/ffind
41822efaeabd0630ba9a2de164552672b7c60430
[ "MIT" ]
null
null
null
/** @file match.h * @brief Pattern matching backend. * @copyright Copyright (c) 2018 Jonathan Lemos * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #ifndef __MATCH_H #define __MATCH_H #include "attribute.h" #include <regex.h> #include <pcre.h> #include <stdint.h> /** * @brief The type of pattern to use. */ enum pattern_type{ TYPE_FNMATCH = 0, /**< The default. Match using the fnmatch(3) function. */ TYPE_FNMATCH_ESCAPE = (1 << 0), /**< Match using a similar function to fnmatch(3) that supports escaping special characters. */ TYPE_FNMATCH_LITERAL = (1 << 1), /**< Match using strstr(3). */ TYPE_REGEX_POSIX = (1 << 2), /**< Match using POSIX basic regular expressions. */ TYPE_REGEX_POSIX_EX = (1 << 3), /**< Match using POSIX extended regular expressions. */ TYPE_REGEX_PCRE = (1 << 4), /**< Match using Perl-compatible regular expressions (PCRE). */ TYPE_REGEX_JAVASCRIPT = (1 << 5) /**< Match using Javascript regular expressions. */ }; #define PFLAG_NORMAL (0) /**< No special flags. Only valid by itself. */ #define PFLAG_ICASE (1 << 0) /**< Ignore case when searching. */ /** * @brief A pattern to match. */ struct pattern{ enum pattern_type p_type; /**< The type of pattern to use. */ union pat{ /**< A pattern object corresponding to the p_type. */ const char* fnmatch; regex_t* regex; pcre* pcre; pcre* javascript; }p; }; /** * @brief Checks to see if the needle is within the haystack. * * @param haystack A string to search within. * * @param needle A pattern to search the haystack for.<br> * Use pat_init() to create a pattern. * * @return True for a match, false for no match. */ int match(const char* haystack, const struct pattern* needle) FF_HOT FF_INLINE; /** * @brief Initializes a pattern structure. * * @param pattern The text to create the pattern out of. * * @param in_out The pattern object to fill.<br> * in_out->p_type should be filled in with the type of pattern to create before this function is called.<br> * in_out->p will be filled with the generated pattern.<br> * This pattern must be freed when no longer in use with pat_free() * @see pat_free() * * @param flags Special flags to use.<br> * These can be combined with the '|' operator. * @see PFLAG_ICASE * * @return 0 on success, negative on failure. */ int pat_init(const char* pattern, struct pattern* in_out, unsigned flags); /** * @brief Frees the pattern within a pattern structure. * * @param pat The pattern structure to free. */ void pat_free(struct pattern* pat); #endif
31.611765
130
0.674358
[ "object" ]
bb18ed53c8f8cd134b1c897739f34dc8b3ea288c
65,850
c
C
Digiplay/Digiplay copy 3/Digiplay/compiler.c
mozsakalli/GamaVM
50732c192e352efbe5e944877fa030e8beecd0f2
[ "Apache-2.0" ]
null
null
null
Digiplay/Digiplay copy 3/Digiplay/compiler.c
mozsakalli/GamaVM
50732c192e352efbe5e944877fa030e8beecd0f2
[ "Apache-2.0" ]
null
null
null
Digiplay/Digiplay copy 3/Digiplay/compiler.c
mozsakalli/GamaVM
50732c192e352efbe5e944877fa030e8beecd0f2
[ "Apache-2.0" ]
null
null
null
// // compiler.c // Digiplay // // Created by mustafa on 19.05.2020. // Copyright © 2020 mustafa. All rights reserved. // #include <stdio.h> #include "jvm.h" /* extern char *string2c(String *str); void print_stack_trace(VM *vm) { for(int i=vm->exceptionFP; i>=0; i--) { Frame *f = &vm->frames[i]; if(f->method) { printf("at %s:", string2c(f->method->declaringClass->name)); printf(":%s", string2c(f->method->name)); printf(":%s line=%d pc=%d\n", string2c(f->method->signature), get_line_number(f->method, f->pc), f->pc); } } } */ enum { OP_UNIMPLEMENTED, //0 OP_NOP, //1 OP_CONST, //2 OP_CONST_CLS, //3 OP_LOADLOCAL, //4 OP_STORELOCAL, //5 OP_GOTO, //6 OP_IF0, //7 OP_IF, //8 OP_RETURN, //9 OP_BINARY, //10 OP_CONVERT, //11 OP_IINC, //12 OP_STACK, //13 OP_INVOKE, //14 OP_INVOKEDIRECT, //15 OP_INVOKEINTERFACE, //16 OP_INVOKEVIRTUAL, //17 OP_GETFIELD, //18 OP_PUTFIELD, //19 OP_IFEQ, //20 OP_IFNE, //21 OP_IFLT, //22 OP_IFGE, //23 OP_IFGT, //24 OP_IFLE, //25 OP_IFICMPEQ, //26 OP_IFICMPNE, //27 OP_IFICMPLT, //28 OP_IFICMPGE, //29 OP_IFICMPGT, //30 OP_IFICMPLE, //31 OP_IFACMPEQ, //32 OP_IFACMPNE, //33 OP_NEWARRAY, //34 OP_NEWARRAYRESOLVED, //35 OP_NEW, //36 OP_NEWRESOLVED, //37 OP_ANEWARRAY, //38 OP_ANEWARRAYRESOLVED, //39 OP_POP, //40 OP_POP2, //41 OP_DUP, //42 OP_DUPX1, //43 OP_GETSTATIC_B, //44 OP_GETSTATIC_Z, //45 OP_GETSTATIC_C, //46 OP_GETSTATIC_S, //47 OP_GETSTATIC_I, //48 OP_GETSTATIC_F, //49 OP_GETSTATIC_J, //50 OP_GETSTATIC_D, //51 OP_GETSTATIC_O, //52 OP_PUTSTATIC_B, //53 OP_PUTSTATIC_Z, //54 OP_PUTSTATIC_C, //55 OP_PUTSTATIC_S, //56 OP_PUTSTATIC_I, //57 OP_PUTSTATIC_F, //58 OP_PUTSTATIC_J, //59 OP_PUTSTATIC_D, //60 OP_PUTSTATIC_O, //61 OP_GETFIELD_B, //62 OP_GETFIELD_Z, //63 OP_GETFIELD_C, //64 OP_GETFIELD_S, //65 OP_GETFIELD_I, //66 OP_GETFIELD_F, //67 OP_GETFIELD_J, //68 OP_GETFIELD_D, //69 OP_GETFIELD_O, //70 OP_PUTFIELD_B, //71 OP_PUTFIELD_Z, //72 OP_PUTFIELD_C, //73 OP_PUTFIELD_S, //74 OP_PUTFIELD_I, //75 OP_PUTFIELD_F, //76 OP_PUTFIELD_J, //77 OP_PUTFIELD_D, //78 OP_PUTFIELD_O, //79 OP_I2L, //80 OP_I2F, //81 OP_I2D, //82 OP_L2I, //83 OP_L2F, //84 OP_L2D, //85 OP_F2I, //86 OP_F2L, //87 OP_F2D, //88 OP_D2I, //89 OP_D2L, //90 OP_D2F, //91 OP_I2B, //92 OP_I2C, //93 OP_I2S, //94 OP_LCMP, //95 OP_FCMPL, //96 OP_FCMPG, //97 OP_DCMPL, //98 OP_DCMPG, //99 OP_IADD, //100 OP_LADD, //101 OP_FADD, //102 OP_DADD, //103 OP_ISUB, //104 OP_LSUB, //105 OP_FSUB, //106 OP_DSUB, //107 OP_IMUL, //108 OP_LMUL, //109 OP_FMUL, //110 OP_DMUL, //111 OP_IDIV, //112 OP_LDIV, //113 OP_FDIV, //114 OP_DDIV, //115 OP_IREM, //116 OP_LREM, //117 OP_FREM, //118 OP_DREM, //119 OP_INEG, //120 OP_LNEG, //121 OP_FNEG, //122 OP_DNEG, //123 OP_ISHL, //124 OP_LSHL, //125 OP_ISHR, //126 OP_LSHR, //127 OP_IUSHR, //128 OP_LUSHR, //129 OP_IAND, //130 OP_LAND, //131 OP_IOR, //132 OP_LOR, //133 OP_IXOR, //134 OP_LXOR, //135 OP_THROW, //136 OP_CHECKCAST, //137 OP_CHECKCASTRESOLVED, //138 OP_LOADARRAY_I, //139 OP_LOADARRAY_J, //140 OP_LOADARRAY_F, //141 OP_LOADARRAY_D, //142 OP_LOADARRAY_O, //143 OP_LOADARRAY_B, //144 OP_LOADARRAY_C, //145 OP_LOADARRAY_S, //146 OP_STOREARRAY_I, //147 OP_STOREARRAY_J, //148 OP_STOREARRAY_F, //149 OP_STOREARRAY_D, //150 OP_STOREARRAY_O, //151 OP_STOREARRAY_B, //152 OP_STOREARRAY_C, //153 OP_STOREARRAY_S, //154 OP_ARRAYLENGTH, //155 OP_IFNULL, //156 OP_IFNOTNULL, //157 OP_MONITORENTER, OP_MONITOREXIT, OP_TABLE, OP_LOOKUP, }; typedef struct OP { int pc; char type; int bc; int code; int index; VAR var; void *handler; } OP; typedef struct BB { int id; OP *ops; int opCount; char stack[16]; int sp; struct BB *src[16]; int srcCount; int processed; int isCatchHandler; } BB; typedef struct COMPILERCTX { MethodFields *method; int opCount; int opCapacity; OP *ops; } COMPILERCTX; unsigned char* vm_compiler_readu2(unsigned char *bc, jint *target) { Short2Char sc; sc.c1 = (unsigned)*bc++; sc.c0 = (unsigned)*bc++; *target = sc.us; return bc; } unsigned char* vm_compiler_reads2(unsigned char *bc, jint *target) { Short2Char sc; sc.c1 = (unsigned)*bc++; sc.c0 = (unsigned)*bc++; *target = sc.s; return bc; } unsigned char* vm_compiler_reads4(unsigned char *bc, jint *target) { Int2Float i2f; i2f.c3 = (unsigned char)*bc++; i2f.c2 = (unsigned char)*bc++; i2f.c1 = (unsigned char)*bc++; i2f.c0 = (unsigned char)*bc++; *target = i2f.i; return bc; } int vm_compiler_cp_type(int type) { switch(type) { case 3: return 'I'; case 4: return 'F'; case 5: return 'J'; case 6: return 'D'; } return 'O'; } int vm_compiler_method_type(CPItem *cp, int index) { StringFields *str = (StringFields*)cp[cp[cp[index].index2].index2].value.O->instance; char type = ARRAY_DATA_C(str->chars)[str->length-1]; if(type == ';') return 'O'; return type; } int vm_compiler_field_type(CPItem *cp, int index) { StringFields *str = (StringFields*)cp[cp[cp[index].index2].index2].value.O->instance; char type = ARRAY_DATA_C(str->chars)[0]; if(type == '[' || type == 'L') return 'O'; return type; } void vm_compiler_build_ops(COMPILERCTX *ctx) { MethodFields *method = ctx->method; unsigned char *bc = (unsigned char *)method->code; unsigned char *end = bc + method->codeSize; int wide = 0; const char* TYPE0 = "IJFDOBCS"; CPItem *item; CPItem *cp = CLS_FIELD(method->declaringClass,cp); //String *str; while(bc < end) { if(ctx->opCount == ctx->opCapacity) { int len = (ctx->opCapacity == 0 ? 16 : ctx->opCapacity * 2); OP* tmp = malloc(sizeof(OP) * len); memset(tmp, 0, sizeof(OP) * len); if(ctx->ops) { memcpy(tmp, ctx->ops, sizeof(OP) * ctx->opCount); free(ctx->ops); } ctx->ops = tmp;//(OP*)realloc(ctx->ops, sizeof(OP) * len); ctx->opCapacity = len; } OP* op = &ctx->ops[ctx->opCount++]; int pc = op->pc = (int)((void*)bc - method->code); unsigned char opcode = *bc++; //printf(" pc: %d op:0x%x\n", pc,opcode ); op->bc = opcode; switch(opcode) { case op_nop: op->code = OP_NOP; break; case op_aconst_null: op->code = OP_CONST; op->type = 'O'; op->var.O = NULL; break; case op_iconst_m1: case op_iconst_0: case op_iconst_1: case op_iconst_2: case op_iconst_3: case op_iconst_4: case op_iconst_5: op->code = OP_CONST; op->type = 'I'; op->var.I = opcode - op_iconst_0; break; case op_lconst_0: case op_lconst_1: op->code = OP_CONST; op->type = 'J'; op->var.J = opcode - op_lconst_0; break; case op_fconst_0: case op_fconst_1: case op_fconst_2: op->code = OP_CONST; op->type = 'F'; op->var.F = opcode - op_fconst_0; break; case op_dconst_0: case op_dconst_1: op->code = OP_CONST; op->type = 'D'; op->var.D = opcode - op_dconst_0; break; case op_bipush: op->code = OP_CONST; op->type = 'I'; op->var.I = (char)*bc++; break; case op_sipush: op->code = OP_CONST; op->type = 'I'; bc = vm_compiler_reads2(bc, &op->var.I); break; case op_ldc: op->index = *bc++; item = &cp[op->index]; switch(item->type) { case 7: //class constant op->code = OP_CONST_CLS; break; case 8: //string constant op->code = OP_CONST; op->var.O = cp[item->index1].value.O; break; default: op->code = OP_CONST; op->var = item->value; break; } /*op->code = item->type == 7 ? OP_CONST_CLS : OP_CONST; op->var = item->value; op->type = vm_compiler_cp_type(item->type);*/ break; case op_ldc_w: case op_ldc2_w: bc = vm_compiler_readu2(bc, &op->index); item = &cp[op->index]; op->code = item->type == 7 ? OP_CONST_CLS : OP_CONST; op->var = item->value; op->type = vm_compiler_cp_type(item->type); break; case op_iload_0: case op_iload_1: case op_iload_2: case op_iload_3: op->code = OP_LOADLOCAL; op->type = 'I'; op->index = opcode - op_iload_0; break; case op_lload_0: case op_lload_1: case op_lload_2: case op_lload_3: op->code = OP_LOADLOCAL; op->type = 'J'; op->index = opcode - op_lload_0; break; case op_dload_0: case op_dload_1: case op_dload_2: case op_dload_3: op->code = OP_LOADLOCAL; op->type = 'D'; op->index = opcode - op_dload_0; break; case op_fload_0: case op_fload_1: case op_fload_2: case op_fload_3: op->code = OP_LOADLOCAL; op->type = 'F'; op->index = opcode - op_fload_0; break; case op_aload_0: case op_aload_1: case op_aload_2: case op_aload_3: op->code = OP_LOADLOCAL; op->type = 'O'; op->index = opcode - op_aload_0; break; case op_iload: case op_lload: case op_fload: case op_dload: case op_aload: if(wide) bc = vm_compiler_readu2(bc, &op->index); else op->index = *bc++; op->code = OP_LOADLOCAL; op->type = TYPE0[opcode - op_istore]; break; case op_istore_0: case op_istore_1: case op_istore_2: case op_istore_3: op->code = OP_STORELOCAL; op->type = 'I'; op->index = opcode - op_istore_0; break; case op_fstore_0: case op_fstore_1: case op_fstore_2: case op_fstore_3: op->code = OP_STORELOCAL; op->type = 'F'; op->index = opcode - op_fstore_0; break; case op_dstore_0: case op_dstore_1: case op_dstore_2: case op_dstore_3: op->code = OP_STORELOCAL; op->type = 'D'; op->index = opcode - op_dstore_0; break; case op_lstore_0: case op_lstore_1: case op_lstore_2: case op_lstore_3: op->code = OP_STORELOCAL; op->type = 'J'; op->index = opcode - op_lstore_0; break; case op_astore_0: case op_astore_1: case op_astore_2: case op_astore_3: op->code = OP_STORELOCAL; op->type = 'O'; op->index = opcode - op_astore_0; break; case op_istore: case op_lstore: case op_fstore: case op_dstore: case op_astore: if(wide) bc = vm_compiler_readu2(bc, &op->index); else op->index = *bc++; op->code = OP_STORELOCAL; op->type = TYPE0[opcode - op_istore]; break; case op_ireturn: case op_lreturn: case op_freturn: case op_dreturn: case op_areturn: op->code = OP_RETURN; op->type = TYPE0[opcode - op_ireturn]; break; case op_return: op->code = OP_RETURN; op->type = 'V'; break; case op_pop: case op_pop2: case op_dup: case op_dup_x1: case op_dup_x2: case op_dup2: case op_dup2_x1: case op_dup2_x2: op->code = OP_STACK; break; case op_iadd: case op_ladd: case op_fadd: case op_dadd: op->code = OP_BINARY; op->type = TYPE0[opcode - op_iadd]; break; case op_isub: case op_lsub: case op_fsub: case op_dsub: op->code = OP_BINARY; op->type = TYPE0[opcode - op_isub]; break; case op_idiv: case op_ldiv: case op_fdiv: case op_ddiv: op->code = OP_BINARY; op->type = TYPE0[opcode - op_idiv]; break; case op_irem: case op_lrem: case op_frem: case op_drem: op->code = OP_BINARY; op->type = TYPE0[opcode - op_irem]; break; case op_imul: case op_lmul: case op_fmul: case op_dmul: op->code = OP_BINARY; op->type = TYPE0[opcode - op_imul]; break; case op_ineg: case op_lneg: case op_fneg: case op_dneg: op->code = OP_BINARY; op->type = TYPE0[opcode - op_ineg]; break; case op_ishl: case op_lshl: case op_ishr: case op_lshr: case op_iushr: case op_lushr: case op_iand: case op_land: case op_ior: case op_lor: case op_ixor: case op_lxor: op->code = OP_BINARY; op->type = TYPE0[(opcode - op_ishl) % 2]; break; case op_iinc: if(wide) printf("!!!!!!!!!!!!!!!!!!! Wide iinc not supported\n"); else { op->code = OP_IINC; op->type = 'I'; op->index = (unsigned char)*bc++; op->var.I = (char)*bc++; } break; case op_l2i: case op_f2i: case op_d2i: case op_i2b: case op_i2c: case op_i2s: op->type = 'I'; op->code = OP_CONVERT; break; case op_i2l: case op_f2l: case op_d2l: op->type = 'J'; op->code = OP_CONVERT; break; case op_i2f: case op_l2f: case op_d2f: op->type = 'F'; op->code = OP_CONVERT; break; case op_i2d: case op_l2d: case op_f2d: op->type = 'D'; op->code = OP_CONVERT; break; case op_lcmp: case op_fcmpl: case op_fcmpg: case op_dcmpl: case op_dcmpg: op->type = 'I'; op->code = OP_LCMP + opcode - op_lcmp; break; case op_ifeq: case op_ifne: case op_iflt: case op_ifge: case op_ifgt: case op_ifle: op->code = OP_IF0; op->type = 'I'; bc = vm_compiler_reads2(bc, &op->index); break; case op_if_icmpeq: case op_if_icmpne: case op_if_icmplt: case op_if_icmpge: case op_if_icmpgt: case op_if_icmple: case op_if_acmpeq: case op_if_acmpne: op->code = OP_IF; op->type = opcode == op_if_acmpeq || opcode == op_if_acmpne ? 'O' : 'I'; bc = vm_compiler_reads2(bc, &op->index); break; case op_ifnull: case op_ifnonnull: op->code = OP_IF0; op->type = 'O'; bc = vm_compiler_reads2(bc, &op->index); break; case op_getstatic: case op_getfield: op->code = OP_GETFIELD; bc = vm_compiler_readu2(bc, &op->index); op->type = vm_compiler_field_type(cp, op->index); break; case op_putstatic: case op_putfield: op->code = OP_PUTFIELD; bc = vm_compiler_readu2(bc, &op->index); op->type = vm_compiler_field_type(cp, op->index); break; case op_new: op->code = OP_NEW; op->type = 'O'; bc = vm_compiler_readu2(bc, &op->index); break; case op_anewarray: op->code = OP_ANEWARRAY; op->type = 'O'; bc = vm_compiler_readu2(bc, &op->index); break; case op_checkcast: op->code = OP_CHECKCAST; op->type = 'O'; bc = vm_compiler_readu2(bc, &op->index); break; case op_newarray: op->code = OP_NEWARRAY; op->type = 'O'; op->index = *bc++; break; case op_invokevirtual: case op_invokespecial: case op_invokestatic: case op_invokeinterface: case op_invokedynamic: op->code = OP_INVOKE; bc = vm_compiler_readu2(bc, &op->index); op->type = vm_compiler_method_type(cp, op->index); if(opcode == op_invokeinterface) bc += 2; break; case op_goto: op->code = OP_GOTO; bc = vm_compiler_reads2(bc, &op->index); break; case op_athrow: op->code = OP_THROW; op->type = 'O'; break; case op_iaload: case op_laload: case op_faload: case op_daload: case op_aaload: case op_baload: case op_caload: case op_saload: op->code = OP_LOADARRAY_I + opcode - op_iaload; op->type = TYPE0[opcode - op_iaload]; break; case op_iastore: case op_lastore: case op_fastore: case op_dastore: case op_aastore: case op_bastore: case op_castore: case op_sastore: op->code = OP_STOREARRAY_I + opcode - op_iastore; op->type = TYPE0[opcode - op_iastore]; break; case op_arraylength: op->code = OP_ARRAYLENGTH; op->type = 'I'; break; case op_monitorenter: case op_monitorexit: op->code = opcode - op_monitorenter + OP_MONITORENTER; op->type = 'O'; break; case op_lookupswitch: { int padding = 4 - ((pc + 1) % 4); if(padding > 0) bc += padding; bc = vm_compiler_reads4(bc, &op->index); int count; bc = vm_compiler_reads4(bc, &count); op->code = OP_LOOKUP; OP *keys = (OP*)malloc(sizeof(OP) * (count + 1)); for(int i=0; i<count; i++) { bc = vm_compiler_reads4(bc, &keys[i].index); //key bc = vm_compiler_reads4(bc, &keys[i].pc); //offset } keys[count].pc = 0xFFFFFFFF; op->var.O = (Object*)keys; } break; default: printf("UNKNOWN op:0x%x / %d\n", opcode, opcode); return; } } } int vm_compile_count_args_by_index(Object *cls, int index, int isStatic) { CPItem *cp = CLS_FIELD(cls,cp); StringFields *signature = (StringFields*)cp[cp[cp[index].index2].index2].value.O->instance; jchar *ch = (jchar*)signature->chars->instance; ch++; //( int count = 0; if(!isStatic) { count++; } while(1) { if(*ch == ')') break; count++; while(*ch == '[') ch++; if(*ch == 'L') { while(*ch != ';') ch++; } ch++; } //printf(" --arg-count %s = %d\n", string2c(signature), count); return count; } void vm_process_bb(MethodFields *method, BB *bb, void **handlers) { if(bb->processed) return; bb->processed = 1; if(bb->srcCount > 0) { for(int i=0; i<bb->srcCount; i++) vm_process_bb(method, bb->src[i], handlers); BB *src = bb->src[0]; for(int i=0; i<src->sp; i++) { bb->stack[bb->sp++] = src->stack[i]; } } if(bb->isCatchHandler) bb->stack[bb->sp++] = 'O'; int check = bb->opCount; for(int i=0; i<bb->opCount; i++) { if(bb->sp < 0) { printf("!!!!!!!!!!!!Stack Invalid!!!!!!\n"); return; } OP *op = &bb->ops[i]; op->handler = handlers[OP_UNIMPLEMENTED]; //printf(" %d:%d OP: 0x%x\n", i, op->pc, op->bc); switch(op->code) { case OP_NOP: op->handler = handlers[OP_NOP]; break; case OP_CONST: case OP_CONST_CLS: case OP_LOADLOCAL: bb->stack[bb->sp++] = op->type; op->handler = handlers[op->code]; break; case OP_STORELOCAL: bb->sp--; op->handler = handlers[op->code]; break; case OP_RETURN: if(op->type != 'V') bb->sp--; op->handler = handlers[OP_RETURN]; break; case OP_NEW: bb->stack[bb->sp++] = 'O'; op->handler = handlers[op->code]; break; case OP_NEWARRAY: case OP_ANEWARRAY: bb->stack[bb->sp-1] = 'O'; op->handler = handlers[op->code]; break; case OP_IF0: bb->sp--; op->handler = handlers[op->bc >= op_ifnull ? op->bc - op_ifnull + OP_IFNULL : op->bc - op_ifeq + OP_IFEQ]; break; case OP_IF: bb->sp -= 2; op->handler = handlers[op->bc - op_ifeq + OP_IFEQ]; break; case OP_INVOKE: { int argCount = vm_compile_count_args_by_index(method->declaringClass,op->index,op->bc == op_invokestatic); bb->sp -= argCount; if(op->type != 'V') bb->stack[bb->sp++] = op->type; op->handler = handlers[OP_INVOKE]; } break; case OP_BINARY: if(op->bc < OP_INEG || op->bc > OP_DNEG) bb->stack[--bb->sp] = op->type; op->handler = handlers[op->bc - op_iadd + OP_IADD]; break; case OP_IINC: case OP_GOTO: op->handler = handlers[op->code]; break; case OP_STACK: switch(op->bc) { case op_pop: op->handler = handlers[OP_POP]; bb->sp--; break; case op_dup: op->handler = handlers[OP_DUP]; bb->stack[bb->sp] = bb->stack[bb->sp-1]; bb->sp++; break; case op_dup_x1: { int v1 = bb->stack[--bb->sp]; int v2 = bb->stack[--bb->sp]; bb->stack[bb->sp++] = v1; bb->stack[bb->sp++] = v2; bb->stack[bb->sp++] = v1; op->handler = handlers[OP_DUPX1]; } break; default: printf("Unknown stack operation 0x%x\n", op->bc); return; } break; case OP_CONVERT: bb->stack[bb->sp-1] = op->type; op->handler = handlers[OP_I2L + op->bc - op_i2l]; break; case OP_LCMP: case OP_FCMPL: case OP_FCMPG: case OP_DCMPL: case OP_DCMPG: bb->sp--; bb->stack[bb->sp - 1] = 'I'; op->handler = handlers[op->code]; break; case OP_PUTFIELD: bb->sp--; if(op->bc == op_putfield) bb->sp--; op->handler = handlers[OP_PUTFIELD]; break; case OP_GETFIELD: if(op->bc == op_getfield) bb->sp--; bb->stack[bb->sp++] = op->type; op->handler = handlers[OP_GETFIELD]; break; case OP_THROW: bb->sp--; op->handler = handlers[OP_THROW]; break; case OP_CHECKCAST: op->handler = handlers[OP_CHECKCAST]; break; case OP_LOADARRAY_I: case OP_LOADARRAY_J: case OP_LOADARRAY_F: case OP_LOADARRAY_D: case OP_LOADARRAY_O: case OP_LOADARRAY_B: case OP_LOADARRAY_C: case OP_LOADARRAY_S: op->handler = handlers[op->code]; bb->sp--; bb->stack[bb->sp-1] = op->code >= OP_LOADARRAY_B ? 'I' : op->type; break; case OP_STOREARRAY_I: case OP_STOREARRAY_J: case OP_STOREARRAY_F: case OP_STOREARRAY_D: case OP_STOREARRAY_O: case OP_STOREARRAY_B: case OP_STOREARRAY_C: case OP_STOREARRAY_S: op->handler = handlers[op->code]; bb->sp -= 3; break; case OP_ARRAYLENGTH: op->handler = handlers[OP_ARRAYLENGTH]; bb->stack[bb->sp - 1] = 'I'; break; case OP_MONITORENTER: case OP_MONITOREXIT: bb->sp--; op->handler = handlers[op->code]; break; case OP_LOOKUP: bb->sp--; op->handler = handlers[OP_LOOKUP]; break; default: printf("UNKNOWN CODE: %d bc:0x%x", op->code, op->bc); printf(" %s",string2c(CLS_FIELD(method->declaringClass,name))); printf(":%s",string2c(method->name)); printf(":%s",string2c(method->signature)); printf(" at line=%d pc=%d\n",get_line_number(method, op->pc), op->pc); return; } } } void pm(char *m, Object *omethod) { MethodFields *method = omethod->instance; printf("%s : %s", m, string2c(CLS_FIELD(method->declaringClass,name))); printf(":%s", string2c(method->name)); printf(":%s\n", string2c(method->signature)); } int vm_compile_find_op(COMPILERCTX *ctx, int pc, int *target) { for(int k=0; k<ctx->opCount; k++) { if(ctx->ops[k].pc == pc) { *target = k; return 1; } } return 0; } void vm_compile_method(VM *vm, MethodFields *method, void **handlers) { COMPILERCTX ctx; memset(&ctx, 0, sizeof(ctx)); ctx.method = method; //pm("Compiling", method); vm_compiler_build_ops(&ctx); //printf("OP-Count: %d\n", ctx.opCount); //fix jump targets for(int i=0; i<ctx.opCount; i++) { OP *op = &ctx.ops[i]; if(op->code == OP_GOTO || op->code == OP_IF || op->code == OP_IF0) { int pc = op->pc + op->index; int k; if(vm_compile_find_op(&ctx, pc, &k)) { op->index = k - i; } else printf("!!!!!! JUMPTARGET NOT FOUND pc=%d!!!!!!\n", pc); /* int found = 0; for(int k=0; k<ctx.opCount; k++) { if(ctx.ops[k].pc == pc) { op->index = k - i; found = 1; break; } } if(!found) printf("!!!!!! JUMPTARGET NOT FOUND pc=%d!!!!!!\n", pc); */ } else if(op->code == OP_LOOKUP) { int pc = op->pc + op->index; int k; if(vm_compile_find_op(&ctx, pc, &k)) { op->index = k - i; } else printf("!!!!!! JUMPTARGET NOT FOUND pc=%d!!!!!!\n", pc); int j=0; OP *keys = (OP*)op->var.O; while(1) { if(keys[j].pc == 0xFFFFFFFF) break; pc = keys[j].pc + op->pc; if(vm_compile_find_op(&ctx, pc, &k)) { keys[j].pc = k - i; } else printf("!!!!!! JUMPTARGET NOT FOUND pc=%d!!!!!!\n", pc); j++; } } } //build basic blocks char bb_targets[ctx.opCount]; memset(bb_targets, 0, sizeof(bb_targets)); for(int i=0; i<ctx.opCount; i++) { OP *op = &ctx.ops[i]; int target = -1; switch(op->code) { case OP_GOTO: bb_targets[i + op->index] = 1; break; case OP_IF: case OP_IF0: bb_targets[i + op->index] = 1; bb_targets[i+1] = 1; break; case OP_THROW: case OP_RETURN: if(i+1 < ctx.opCount) { bb_targets[i+1] = 1; } break; case OP_LOOKUP: { bb_targets[i + op->index] = 1; int j=0; OP *keys = (OP*)op->var.O; while(1) { if(keys[j].pc == 0xFFFFFFFF) break; bb_targets[keys[j].pc + i] = 1; j++; } } break; } } for(int i=0; i<method->catchTableSize; i++) { CatchInfo *c = &method->catchTable[i]; //printf("Catch: %d %d %d\n", c->start, c->end, c->pc); for(int k=0; k<ctx.opCount; k++) { if(ctx.ops[k].pc == c->pc) { bb_targets[k] = 2; break; } } } int bb_count = 1; for(int i=0; i<ctx.opCount; i++) if(bb_targets[i]) bb_count++; BB bb[bb_count]; memset(bb, 0, sizeof(bb)); bb_count = 1; bb[0].id = 0; bb[0].ops = &ctx.ops[0]; for(int i=0; i<ctx.opCount; i++) { OP *op = &ctx.ops[i]; if(bb_targets[i]) { bb_count++; bb[bb_count-1].id = op->pc; bb[bb_count-1].ops = op; bb[bb_count-1].isCatchHandler = bb_targets[i] == 2; } bb[bb_count-1].opCount++; } //find source bb int opndx = 0; for(int i=0; i<bb_count-1; i++) { int targets[] = {-1, -1}; int targetCount = 0; if(bb[i].opCount > 0) { OP *last = &bb[i].ops[bb[i].opCount - 1]; switch(last->code) { case OP_GOTO: targets[0] = opndx + bb[i].opCount - 1 + last->index; targetCount = 1; break; case OP_IF: case OP_IF0: targets[0] = opndx + bb[i].opCount - 1 + last->index; targets[1] = opndx + bb[i].opCount; targetCount = 1; break; case OP_RETURN: case OP_THROW: targetCount = -1; break; } } opndx += bb[i].opCount; if(targetCount == -1) continue; if(targetCount == 1) { for(int k=0; k<2; k++) { if(targets[k] == -1) continue; int pc = ctx.ops[targets[k]].pc; int found = 0; for(int j=0; j<bb_count; j++) if(j!=i && bb[j].id == pc) { bb[j].src[bb[j].srcCount++] = &bb[i]; found = 1; break; } if(!found) printf("!!!! target %d not found\n", pc); } } else { bb[i+1].src[bb[i+1].srcCount++] = &bb[i]; } } /* for(int k=0; k<bb_count; k++) { BB *b = &bb[k]; printf("BB %d count:%d\n", b->id, b->opCount); if(b->srcCount > 0) { for(int i=0; i<b->srcCount; i++) { printf(" src:%d ",b->src[i]->id, b->src[i]->sp); } printf("\n"); } }*/ for(int i=0; i<bb_count; i++) vm_process_bb(method, &bb[i], handlers); //setup catch handlers for(int i=0; i<method->catchTableSize; i++) { CatchInfo *c = &method->catchTable[i]; int found = 0; for(int k=0; k<ctx.opCount; k++) { if(ctx.ops[k].pc == c->pc) { c->label = &ctx.ops[k]; found = 1; break; } } if(!found) printf("!!!! CATCH HANDLER NOT FOUND !!!!\n"); } method->compiled = ctx.ops; } void vm_interpret_method(VM *vm, Object *omethod, VAR *args) { static void* handlers[] = { &&OP_UNIMPLEMENTED, &&OP_NOP, &&OP_CONST, &&OP_CONST_CLS, &&OP_LOADLOCAL, &&OP_STORELOCAL, &&OP_GOTO, &&OP_IF0, &&OP_IF, &&OP_RETURN, &&OP_BINARY, &&OP_CONVERT, &&OP_IINC, &&OP_STACK, &&OP_INVOKE, &&OP_INVOKEDIRECT, &&OP_INVOKEINTERFACE, &&OP_INVOKEVIRTUAL, &&OP_GETFIELD, &&OP_PUTFIELD, &&OP_IFEQ, &&OP_IFNE, &&OP_IFLT, &&OP_IFGE, &&OP_IFGT, &&OP_IFLE, &&OP_IFICMPEQ, &&OP_IFICMPNE, &&OP_IFICMPLT, &&OP_IFICMPGE, &&OP_IFICMPGT, &&OP_IFICMPLE, &&OP_IFACMPEQ, &&OP_IFACMPNE, &&OP_NEWARRAY, &&OP_NEWARRAYRESOLVED, &&OP_NEW, &&OP_NEWRESOLVED, &&OP_ANEWARRAY, &&OP_ANEWARRAYRESOLVED, &&OP_POP, &&OP_POP2, &&OP_DUP, &&OP_DUPX1, &&OP_GETSTATIC_B, &&OP_GETSTATIC_Z, &&OP_GETSTATIC_C, &&OP_GETSTATIC_S, &&OP_GETSTATIC_I, &&OP_GETSTATIC_F, &&OP_GETSTATIC_J, &&OP_GETSTATIC_D, &&OP_GETSTATIC_O, &&OP_PUTSTATIC_B, &&OP_PUTSTATIC_Z, &&OP_PUTSTATIC_C, &&OP_PUTSTATIC_S, &&OP_PUTSTATIC_I, &&OP_PUTSTATIC_F, &&OP_PUTSTATIC_J, &&OP_PUTSTATIC_D, &&OP_PUTSTATIC_O, &&OP_GETFIELD_B, &&OP_GETFIELD_Z, &&OP_GETFIELD_C, &&OP_GETFIELD_S, &&OP_GETFIELD_I, &&OP_GETFIELD_F, &&OP_GETFIELD_J, &&OP_GETFIELD_D, &&OP_GETFIELD_O, &&OP_PUTFIELD_B, &&OP_PUTFIELD_Z, &&OP_PUTFIELD_C, &&OP_PUTFIELD_S, &&OP_PUTFIELD_I, &&OP_PUTFIELD_F, &&OP_PUTFIELD_J, &&OP_PUTFIELD_D, &&OP_PUTFIELD_O, &&OP_I2L, &&OP_I2F, &&OP_I2D, &&OP_L2I, &&OP_L2F, &&OP_L2D, &&OP_F2I, &&OP_F2L, &&OP_F2D, &&OP_D2I, &&OP_D2L, &&OP_D2F, &&OP_I2B, &&OP_I2C, &&OP_I2S, &&OP_LCMP, &&OP_FCMPL, &&OP_FCMPG, &&OP_DCMPL, &&OP_DCMPG, &&OP_IADD, &&OP_LADD, &&OP_FADD, &&OP_DADD, &&OP_ISUB, &&OP_LSUB, &&OP_FSUB, &&OP_DSUB, &&OP_IMUL, &&OP_LMUL, &&OP_FMUL, &&OP_DMUL, &&OP_IDIV, &&OP_LDIV, &&OP_FDIV, &&OP_DDIV, &&OP_IREM, &&OP_LREM, &&OP_FREM, &&OP_DREM, &&OP_INEG, &&OP_LNEG, &&OP_FNEG, &&OP_DNEG, &&OP_ISHL, &&OP_LSHL, &&OP_ISHR, &&OP_LSHR, &&OP_IUSHR, &&OP_LUSHR, &&OP_IAND, &&OP_LAND, &&OP_IOR, &&OP_LOR, &&OP_IXOR, &&OP_LXOR, &&OP_THROW, &&OP_CHECKCAST, &&OP_CHECKCASTRESOLVED, &&OP_LOADARRAY_I, &&OP_LOADARRAY_J, &&OP_LOADARRAY_F, &&OP_LOADARRAY_D, &&OP_LOADARRAY_O, &&OP_LOADARRAY_B, &&OP_LOADARRAY_C, &&OP_LOADARRAY_S, &&OP_STOREARRAY_I, &&OP_STOREARRAY_J, &&OP_STOREARRAY_F, &&OP_STOREARRAY_D, &&OP_STOREARRAY_O, &&OP_STOREARRAY_B, &&OP_STOREARRAY_C, &&OP_STOREARRAY_S, &&OP_ARRAYLENGTH, &&OP_IFNULL, &&OP_IFNOTNULL, &&OP_MONITORENTER, &&OP_MONITOREXIT, &&OP_TABLE, &&OP_LOOKUP, }; MethodFields *method = omethod->instance; //VAR stack[method->maxStack]; //VAR local[method->maxLocals]; VAR* local = &vm->stack[vm->SP]; VAR* stack = local + method->maxLocals; vm->SP += method->maxStack + method->maxLocals; jint sp = 0; //if(!strcmp(string2c(method->name),"main")) // printf("..."); //pm("Executing", method); //printf("SP=%d\n", vm->SP); if(!method->compiled) { //printf("Compiling...\n"); vm_compile_method(vm, method, &handlers[0]); } //printf("Started...\n"); int argCount = method->argCount; if(argCount > 0) { jint *map = method->argMap; for(int i=0; i<argCount; i++) { //printf("arg%d = %d %p %d\n", map[i], args->I, args->O); local[map[i]] = *args; args++; } } Object *field; jint fp = ++vm->FP; vm->frames[fp].method = omethod; //Frame *frame = &vm->frames[++vm->fp]; OP* op = &((OP*)method->compiled)[0]; #define NEXT(d) /*printf("%d: OP=0x%x CODE=%d\n",op->pc, op->bc, op->code); */op += d; goto *op->handler; #define NULL_CHECK(o) \ if(!o) { \ vm->frames[fp].pc = op->pc; \ throw_nullpointerexception(vm); \ goto __EXCEPTION; \ } #define SAVE_PC vm->frames[fp].pc = op->pc; NEXT(0); OP_NOP: NEXT(1); OP_UNIMPLEMENTED: //0 printf("UNIMPLEMENTED OP = %d : 0x%x code=%d\n", op->bc, op->bc, op->code); return; OP_CONST: //1 stack[sp++] = op->var; NEXT(1) OP_CONST_CLS: { Object *cls = resolve_class_by_index(vm, method->declaringClass, op->index); if(vm->exception) goto __EXCEPTION; op->var.O = cls; op->handler = handlers[OP_CONST]; NEXT(0); } OP_LOADLOCAL: //2 stack[sp++] = local[op->index]; NEXT(1) OP_STORELOCAL: //3 local[op->index] = stack[--sp]; NEXT(1) OP_GOTO: //4 NEXT(op->index); OP_IF0: //5 printf("OP_IF0 CALLED!\n"); return; OP_IF: //5 printf("OP_IF CALLED!\n"); return; OP_RETURN: //6 vm->FP--; if(op->type != 'V') vm->frames[vm->FP].retVal = stack[--sp]; vm->SP -= method->maxStack + method->maxLocals; //pm("Finished", method); return; OP_BINARY: //7 printf("OP_BINARY CALLED!\n"); return; OP_CONVERT: //8 printf("OP_CONVERT CALLED!\n"); return; OP_IINC: //9 local[op->index].I += op->var.I; NEXT(1); OP_STACK: //11 printf("OP_STACK CALLED!\n"); return; OP_INVOKE: //12 { Object *m = resolve_method_by_index(vm, method->declaringClass, op->index); if(vm->exception) goto __EXCEPTION; NULL_CHECK(m); op->var.O = (Object*)m; switch(op->bc) { case op_invokestatic: case op_invokespecial: op->handler = handlers[OP_INVOKEDIRECT]; break; case op_invokeinterface: op->handler = handlers[OP_INVOKEINTERFACE]; break; case op_invokevirtual: op->handler = handlers[OP_INVOKEVIRTUAL]; break; default: printf("Unknown Invoke type: %d\n", op->bc); return; } NEXT(0) } OP_GETFIELD: //13 field = resolve_field_by_index(vm, method->declaringClass, op->index); if(vm->exception) goto __EXCEPTION; //printf("GetField: %s",string2c(field->declaringClass->name)); //printf(":%s\n", string2c(field->name)); op->index = FLD_FIELD(field,offset); op->var.O = (Object*)(CLS_FIELD(FLD_FIELD(field,declaringClass),globals) + op->index); //static access switch(op->type) { case 'B': op->handler = handlers[op->bc == op_getstatic ? OP_GETSTATIC_B : OP_GETFIELD_B]; break; case 'Z': op->handler = handlers[op->bc == op_getstatic ? OP_GETSTATIC_Z : OP_GETFIELD_Z]; break; case 'C': op->handler = handlers[op->bc == op_getstatic ? OP_GETSTATIC_C : OP_GETFIELD_C]; break; case 'S': op->handler = handlers[op->bc == op_getstatic ? OP_GETSTATIC_S : OP_GETFIELD_S]; break; case 'I': op->handler = handlers[op->bc == op_getstatic ? OP_GETSTATIC_I : OP_GETFIELD_I]; break; case 'O': op->handler = handlers[op->bc == op_getstatic ? OP_GETSTATIC_O : OP_GETFIELD_O]; break; case 'J': op->handler = handlers[op->bc == op_getstatic ? OP_GETSTATIC_J : OP_GETFIELD_J]; break; case 'D': op->handler = handlers[op->bc == op_getstatic ? OP_GETSTATIC_D : OP_GETFIELD_D]; break; case 'F': op->handler = handlers[op->bc == op_getstatic ? OP_GETSTATIC_F : OP_GETFIELD_F]; break; default: printf("Unknown getfield type: %c\n", op->type); return; } //op->handler = handlers[op->bc == op_getstatic ? OP_GETSTATICRESOLVED : OP_GETFIELDRESOLVED]; NEXT(0); OP_PUTFIELD: //14 field = resolve_field_by_index(vm, method->declaringClass, op->index); if(vm->exception) goto __EXCEPTION; op->index = FLD_FIELD(field, offset); op->var.O = (Object*)(CLS_FIELD(FLD_FIELD(field,declaringClass),globals) + op->index); //static access switch(op->type) { case 'B': op->handler = handlers[op->bc == op_putstatic ? OP_PUTSTATIC_B : OP_PUTFIELD_B]; break; case 'Z': op->handler = handlers[op->bc == op_putstatic ? OP_PUTSTATIC_Z : OP_PUTFIELD_Z]; break; case 'C': op->handler = handlers[op->bc == op_putstatic ? OP_PUTSTATIC_C : OP_PUTFIELD_C]; break; case 'S': op->handler = handlers[op->bc == op_putstatic ? OP_PUTSTATIC_S : OP_PUTFIELD_S]; break; case 'I': op->handler = handlers[op->bc == op_putstatic ? OP_PUTSTATIC_I : OP_PUTFIELD_I]; break; case 'O': op->handler = handlers[op->bc == op_putstatic ? OP_PUTSTATIC_O : OP_PUTFIELD_O]; break; case 'J': op->handler = handlers[op->bc == op_putstatic ? OP_PUTSTATIC_J : OP_PUTFIELD_J]; break; case 'D': op->handler = handlers[op->bc == op_putstatic ? OP_PUTSTATIC_D : OP_PUTFIELD_D]; break; case 'F': op->handler = handlers[op->bc == op_putstatic ? OP_PUTSTATIC_F : OP_PUTFIELD_F]; break; default: printf("Unknown putfield type: %c\n", op->type); return; } //op->handler = handlers[op->bc == op_putstatic ? OP_PUTSTATICRESOLVED : OP_PUTFIELDRESOLVED]; NEXT(0); OP_IFEQ: //15 sp--; if(stack[sp].I == 0) { NEXT(op->index); } else NEXT(1); OP_IFNE: //16 sp--; if(stack[sp].I != 0) { NEXT(op->index); } else NEXT(1); OP_IFLT: //17 sp--; if(stack[sp].I < 0) { NEXT(op->index); } else NEXT(1); OP_IFGE: //18 sp--; if(stack[sp].I >= 0) { NEXT(op->index); } else NEXT(1); OP_IFGT: //19 sp--; if(stack[sp].I > 0) { NEXT(op->index); } else NEXT(1); OP_IFLE: //20 sp--; if(stack[sp].I <= 0) { NEXT(op->index); } else NEXT(1); OP_IFICMPEQ: //21 sp -= 2; if(stack[sp].I == stack[sp+1].I) { NEXT(op->index); } else NEXT(1); OP_IFICMPNE: //22 sp -= 2; if(stack[sp].I != stack[sp+1].I) { NEXT(op->index); } else NEXT(1); OP_IFICMPLT: //23 sp -= 2; if(stack[sp].I < stack[sp+1].I) { NEXT(op->index); } else NEXT(1); OP_IFICMPGE: //24 sp -= 2; if(stack[sp].I >= stack[sp+1].I) { NEXT(op->index); } else NEXT(1); OP_IFICMPGT: //25 sp -= 2; if(stack[sp].I > stack[sp+1].I) { NEXT(op->index); } else NEXT(1); OP_IFICMPLE: //26 sp -= 2; if(stack[sp].I <= stack[sp+1].I) { NEXT(op->index); } else NEXT(1); OP_IFACMPEQ: //27 sp -= 2; if(stack[sp].O == stack[sp+1].O) { NEXT(op->index); } else NEXT(1); OP_IFACMPNE: //28 sp -= 2; if(stack[sp].O != stack[sp+1].O) { NEXT(op->index); } else NEXT(1); OP_NEWARRAY: { switch(op->index) { case 4: op->var.O = (Object*)resolve_class(vm, "[Z", 0); break; case 5: op->var.O = (Object*)resolve_class(vm, "[C", 0); break; case 8: op->var.O = (Object*)resolve_class(vm, "[B", 0); break; case 10: op->var.O = (Object*)resolve_class(vm, "[I", 0); break; default: printf("Unknown new array type: %d\n", op->index); return; } if(vm->exception) goto __EXCEPTION; op->handler = handlers[OP_NEWARRAYRESOLVED]; NEXT(0); } OP_NEWARRAYRESOLVED: stack[sp-1].O = alloc_prim_array(vm, op->var.O, stack[sp-1].I); NEXT(1); OP_NEW: //10 op->var.O = (Object*)resolve_class_by_index(vm,method->declaringClass,op->index); if(vm->exception) goto __EXCEPTION; op->handler = handlers[OP_NEWRESOLVED]; NEXT(0); OP_NEWRESOLVED: stack[sp].O = alloc_object(vm, op->var.O); sp++; NEXT(1) OP_ANEWARRAY: { op->var.O = (Object*)resolve_array_class_by_index(vm, method->declaringClass, op->index); if(vm->exception) goto __EXCEPTION; op->handler = handlers[OP_ANEWARRAYRESOLVED]; NEXT(0); } OP_ANEWARRAYRESOLVED: stack[sp-1].O = alloc_object_array(vm, op->var.O, stack[sp-1].I); NEXT(1); OP_POP: sp--; NEXT(1); OP_POP2: sp-=2; NEXT(1); OP_DUP: stack[sp] = stack[sp-1]; sp++; NEXT(1) OP_DUPX1: { VAR v1 = stack[--sp]; VAR v2 = stack[--sp]; stack[sp++] = v1; stack[sp++] = v2; stack[sp++] = v1; NEXT(1) } OP_GETSTATIC_B: stack[sp++].I = *((jbyte*)op->var.O); NEXT(1); OP_GETSTATIC_Z: stack[sp++].I = *((jbool*)op->var.O); NEXT(1); OP_GETSTATIC_C: stack[sp++].I = *((jchar*)op->var.O); NEXT(1); OP_GETSTATIC_S: stack[sp++].I = *((jshort*)op->var.O); NEXT(1); OP_GETSTATIC_I: stack[sp++].I = *((jint*)op->var.O); NEXT(1); OP_GETSTATIC_F: stack[sp++].F = *((jfloat*)op->var.O); NEXT(1); OP_GETSTATIC_J: stack[sp++].J = *((jlong*)op->var.O); NEXT(1); OP_GETSTATIC_D: stack[sp++].D = *((jdouble*)op->var.O); NEXT(1); OP_GETSTATIC_O: stack[sp++].O = *((ObjectPtr*)op->var.O); NEXT(1); OP_PUTSTATIC_B: *((jbyte*)op->var.O) = stack[--sp].I; NEXT(1); OP_PUTSTATIC_Z: *((jbool*)op->var.O) = stack[--sp].I; NEXT(1); OP_PUTSTATIC_C: *((jchar*)op->var.O) = stack[--sp].I; NEXT(1); OP_PUTSTATIC_S: *((jshort*)op->var.O) = stack[--sp].I; NEXT(1); OP_PUTSTATIC_I: *((jint*)op->var.O) = stack[--sp].I; NEXT(1); OP_PUTSTATIC_F: *((jfloat*)op->var.O) = stack[--sp].F; NEXT(1); OP_PUTSTATIC_J: *((jlong*)op->var.O) = stack[--sp].J; NEXT(1); OP_PUTSTATIC_D: *((jdouble*)op->var.O) = stack[--sp].D; NEXT(1); OP_PUTSTATIC_O: *((ObjectPtr*)op->var.O) = stack[--sp].O; NEXT(1); OP_GETFIELD_B: { Object *object = stack[sp-1].O; NULL_CHECK(object); stack[sp-1].I = *FIELD_PTR_B(object, op->index); NEXT(1); } OP_GETFIELD_Z: { Object *object = stack[sp-1].O; NULL_CHECK(object); stack[sp-1].I = *FIELD_PTR_Z(object, op->index); NEXT(1); } OP_GETFIELD_C: { Object *object = stack[sp-1].O; NULL_CHECK(object); stack[sp-1].I = *FIELD_PTR_C(object, op->index); NEXT(1); } OP_GETFIELD_S: { Object *object = stack[sp-1].O; NULL_CHECK(object); stack[sp-1].I = *FIELD_PTR_S(object, op->index); NEXT(1); } OP_GETFIELD_I: { Object *object = stack[sp-1].O; NULL_CHECK(object); //printf("GetField_I => %d %p + %d\n",*((jint*)(object+sizeof(Object)+op->index)), object, op->index); stack[sp-1].I = *FIELD_PTR_I(object, op->index); NEXT(1); } OP_GETFIELD_F: { Object *object = stack[sp-1].O; NULL_CHECK(object); stack[sp-1].F = *FIELD_PTR_F(object, op->index); NEXT(1); } OP_GETFIELD_J: { Object *object = stack[sp-1].O; NULL_CHECK(object); stack[sp-1].J = *FIELD_PTR_J(object, op->index); NEXT(1); } OP_GETFIELD_D: { Object *object = stack[sp-1].O; NULL_CHECK(object); stack[sp-1].D = *FIELD_PTR_D(object, op->index); NEXT(1); } OP_GETFIELD_O: { Object *object = stack[sp-1].O; NULL_CHECK(object); stack[sp-1].O = *FIELD_PTR_O(object, op->index); NEXT(1); } OP_PUTFIELD_B: { Object *object = stack[sp-2].O; NULL_CHECK(object); *FIELD_PTR_B(object, op->index) = (jbyte)stack[sp-1].I; sp -= 2; NEXT(1); } OP_PUTFIELD_Z: { Object *object = stack[sp-2].O; NULL_CHECK(object); *FIELD_PTR_Z(object, op->index) = (jbool)stack[sp-1].I; sp -= 2; NEXT(1); } OP_PUTFIELD_C: { Object *object = stack[sp-2].O; NULL_CHECK(object); *FIELD_PTR_C(object, op->index) = (jshort)stack[sp-1].I; sp -= 2; NEXT(1); } OP_PUTFIELD_S: { Object *object = stack[sp-2].O; NULL_CHECK(object); *FIELD_PTR_S(object, op->index) = stack[sp-1].I; sp -= 2; NEXT(1); } OP_PUTFIELD_I: { Object *object = stack[sp-2].O; NULL_CHECK(object); //printf("PutField_I => %d for %p at %d\n",stack[sp-1].I, object, op->index); *FIELD_PTR_I(object, op->index) = stack[sp-1].I; sp -= 2; NEXT(1); } OP_PUTFIELD_F: { Object *object = stack[sp-2].O; NULL_CHECK(object); *FIELD_PTR_F(object, op->index) = stack[sp-1].F; sp -= 2; NEXT(1); } OP_PUTFIELD_J: { Object *object = stack[sp-2].O; NULL_CHECK(object); *FIELD_PTR_J(object, op->index) = stack[sp-1].J; sp -= 2; NEXT(1); } OP_PUTFIELD_D: { Object *object = stack[sp-2].O; NULL_CHECK(object); *FIELD_PTR_D(object, op->index) = stack[sp-1].D; sp -= 2; NEXT(1); } OP_PUTFIELD_O: { Object *object = stack[sp-2].O; NULL_CHECK(object); *FIELD_PTR_O(object, op->index) = stack[sp-1].O; sp -= 2; NEXT(1); } OP_INVOKEDIRECT: //35 { Object *om = op->var.O; MethodFields *m = om->instance; int call_sp = sp - m->argCount; SAVE_PC; ((JVM_CALL)m->entry)(vm, om, &stack[call_sp]); sp = call_sp; if(vm->exception) goto __EXCEPTION; if(op->type != 'V') { stack[sp++] = vm->frames[fp].retVal; } NEXT(1); } OP_INVOKEINTERFACE: { Object *om = op->var.O; MethodFields *m = om->instance; int call_sp = sp - m->argCount; SAVE_PC; Object *object = stack[call_sp].O; NULL_CHECK(object); Object *imethod = CLS_FIELD(object->cls,itable)[m->iTableIndex]; if(!imethod) { printf("Invalid interface call!!!\n"); return; } ((JVM_CALL)((MethodFields*)imethod->instance)->entry)(vm, imethod, &stack[call_sp]); sp = call_sp; if(vm->exception) goto __EXCEPTION; if(op->type != 'V') { stack[sp++] = vm->frames[fp].retVal; } NEXT(1); } OP_INVOKEVIRTUAL: { Object *om = op->var.O; MethodFields *m = om->instance; //printf("--- invoke-virtual: %s", string2c(CLS_FIELD(m->declaringClass,name))); //printf(":%s",string2c(m->name)); //printf(":%s\n",string2c(m->signature)); int call_sp = sp - m->argCount; SAVE_PC; Object *object = stack[call_sp].O; NULL_CHECK(object); //printf(" ---- %s\n", string2c(CLS_FIELD(object->cls,name))); Object *vmethod = CLS_FIELD(object->cls,vtable)[m->vTableIndex]; if(!vmethod) { printf("Invalid virtual call!!! for %s\n", string2c(CLS_FIELD(object->cls,name))); return; } ((JVM_CALL)((MethodFields*)vmethod->instance)->entry)(vm, vmethod, &stack[call_sp]); sp = call_sp; if(vm->exception) goto __EXCEPTION; if(op->type != 'V') { stack[sp++] = vm->frames[fp].retVal; } NEXT(1); } OP_I2L: //36 stack[sp-1].J = stack[sp-1].I; NEXT(1) OP_I2F: //37 stack[sp-1].F = stack[sp-1].I; NEXT(1) OP_I2D: //38 stack[sp-1].D = stack[sp-1].I; NEXT(1) OP_L2I: //39 stack[sp-1].I = (jint)stack[sp-1].J; NEXT(1) OP_L2F: //40 stack[sp-1].F = (jfloat)stack[sp-1].J; NEXT(1) OP_L2D: //41 stack[sp-1].D = (jdouble)stack[sp-1].J; NEXT(1) OP_F2I: //42 stack[sp-1].I = (jint)stack[sp-1].F; NEXT(1) OP_F2L: //43 stack[sp-1].J = (jlong)stack[sp-1].F; NEXT(1) OP_F2D: //44 stack[sp-1].D = stack[sp-1].F; NEXT(1) OP_D2I: //45 stack[sp-1].I = (jint)stack[sp-1].D; NEXT(1) OP_D2L: //46 stack[sp-1].J = (jlong)stack[sp-1].D; NEXT(1) OP_D2F: //47 stack[sp-1].F = (jfloat)stack[sp-1].D; NEXT(1) OP_I2B: //48 stack[sp-1].I = (jbyte)stack[sp-1].I; NEXT(1) OP_I2C: //49 stack[sp-1].I = (jchar)stack[sp-1].I; NEXT(1) OP_I2S: //50 stack[sp-1].I = (jshort)stack[sp-1].I; NEXT(1) OP_LCMP: { jlong v2 = stack[sp-1].J; jlong v1 = stack[sp-2].J; stack[sp-2].I = v1 == v2 ? 0 : (v1 < v2 ? -1 : 1); sp--; NEXT(1) } #define FCMP(TYPE, SIGN, isNan) \ int res; \ TYPE v2 = stack[sp-1].SIGN; \ TYPE v1 = stack[sp-2].SIGN; \ if(v1 == v2) \ res = 0; \ else if(v1 < v2) \ res = -1; \ else if(v1 > v2) \ res = 1; \ else \ res = isNan; \ stack[sp-2].I = res; \ sp--; OP_FCMPL: { FCMP(jfloat, F, -1); NEXT(1) } OP_FCMPG: { FCMP(jfloat, F, 1); NEXT(1) } OP_DCMPL: { FCMP(jdouble, D, -1); NEXT(1) } OP_DCMPG: { FCMP(jdouble, D, 1); NEXT(1) } OP_IADD: //51 stack[sp-2].I += stack[sp-1].I; sp--; NEXT(1); OP_LADD: //52 stack[sp-2].J += stack[sp-1].J; sp--; NEXT(1); OP_FADD: //53 stack[sp-2].F += stack[sp-1].F; sp--; NEXT(1); OP_DADD: //54 stack[sp-2].D += stack[sp-1].D; sp--; NEXT(1); OP_ISUB: //55 stack[sp-2].I -= stack[sp-1].I; sp--; NEXT(1); OP_LSUB: //56 stack[sp-2].J -= stack[sp-1].J; sp--; NEXT(1); OP_FSUB: //57 stack[sp-2].F -= stack[sp-1].F; sp--; NEXT(1); OP_DSUB: //58 stack[sp-2].D -= stack[sp-1].D; sp--; NEXT(1); OP_IMUL: //59 stack[sp-2].I *= stack[sp-1].I; sp--; NEXT(1); OP_LMUL: //60 stack[sp-2].J *= stack[sp-1].J; sp--; NEXT(1); OP_FMUL: //61 stack[sp-2].F *= stack[sp-1].F; sp--; NEXT(1); OP_DMUL: //62 stack[sp-2].D *= stack[sp-1].D; sp--; NEXT(1); OP_IDIV: //63 { jint divisor = stack[sp-1].I; stack[sp-2].I /= divisor; sp--; NEXT(1); } OP_LDIV: //64 { jlong divisor = stack[sp-1].J; stack[sp-2].J /= divisor; sp--; NEXT(1); } OP_FDIV: //65 { jfloat divisor = stack[sp-1].F; stack[sp-2].F /= divisor; sp--; NEXT(1); } OP_DDIV: //66 { jdouble divisor = stack[sp-1].D; stack[sp-2].D /= divisor; sp--; NEXT(1); } OP_IREM: //67 stack[sp-2].I %= stack[sp-1].I; sp--; NEXT(1); OP_LREM: //68 stack[sp-2].J %= stack[sp-1].J; sp--; NEXT(1); OP_FREM: //69 printf("Missing op: 0x%x\n", op->bc); return; OP_DREM: //70 printf("Missing op: 0x%x\n", op->bc); return; OP_INEG: //71 stack[sp-1].I = -stack[sp-1].I; NEXT(1); OP_LNEG: //72 stack[sp-1].J = -stack[sp-1].J; NEXT(1); OP_FNEG: //73 stack[sp-1].F = -stack[sp-1].F; NEXT(1); OP_DNEG: //74 stack[sp-1].D = -stack[sp-1].D; NEXT(1); OP_ISHL: //75 stack[sp-2].I <<= stack[sp-1].I; sp--; NEXT(1); OP_LSHL: //76 stack[sp-2].J <<= stack[sp-1].I; sp--; NEXT(1); OP_ISHR: //77 stack[sp-2].I >>= stack[sp-1].I; sp--; NEXT(1); OP_LSHR: //78 stack[sp-2].J >>= stack[sp-1].I; sp--; NEXT(1); OP_IUSHR: //79 printf("Missing op: 0x%x\n", op->bc); return; OP_LUSHR: //80 printf("Missing op: 0x%x\n", op->bc); return; OP_IAND: //81 stack[sp-2].I &= stack[sp-1].I; sp--; NEXT(1); OP_LAND: //82 stack[sp-2].J &= stack[sp-1].J; sp--; NEXT(1); OP_IOR: //83 stack[sp-2].I |= stack[sp-1].I; sp--; NEXT(1); OP_LOR: //84 stack[sp-2].J |= stack[sp-1].J; sp--; NEXT(1); OP_IXOR: //85 stack[sp-2].I ^= stack[sp-1].I; sp--; NEXT(1); OP_LXOR: //86 stack[sp-2].J ^= stack[sp-1].J; sp--; NEXT(1); OP_THROW: vm->frames[fp].pc = op->pc; throw_exception(vm, stack[--sp].O); goto __EXCEPTION; OP_CHECKCAST: op->var.O = (Object*)resolve_class_by_index(vm, method->declaringClass, op->index); if(vm->exception) goto __EXCEPTION; op->handler = handlers[OP_CHECKCASTRESOLVED]; NEXT(0); OP_CHECKCASTRESOLVED: if(!check_cast(vm, stack[sp-1].O, op->var.O)) { vm->frames[fp].pc = op->pc; throw_castexception(vm, NULL, NULL); goto __EXCEPTION; } NEXT(1); #define ARRAY_CHECK \ if(!object) { \ vm->frames[fp].pc = op->pc; \ throw_nullpointerexception(vm); \ goto __EXCEPTION; \ } \ if(index < 0 || index >= object->length) { \ vm->frames[fp].pc = op->pc; \ throw_arrayboundsexception(vm, index, object->length); \ goto __EXCEPTION; \ } OP_LOADARRAY_I: { int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; stack[sp++].I = ARRAY_DATA_I(object)[index]; NEXT(1); } OP_LOADARRAY_J: { int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; stack[sp++].J = ARRAY_DATA_J(object)[index]; NEXT(1); } OP_LOADARRAY_F: { int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; stack[sp++].F = ARRAY_DATA_F(object)[index]; NEXT(1); } OP_LOADARRAY_D: { int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; stack[sp++].D = ARRAY_DATA_D(object)[index]; NEXT(1); } OP_LOADARRAY_O: { int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; stack[sp++].O = ARRAY_DATA_O(object)[index]; NEXT(1); } OP_LOADARRAY_B: { int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; stack[sp++].I = ARRAY_DATA_B(object)[index]; NEXT(1); } OP_LOADARRAY_C: { int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; stack[sp++].I = ARRAY_DATA_C(object)[index]; NEXT(1); } OP_LOADARRAY_S: { int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; stack[sp++].I = ARRAY_DATA_S(object)[index]; NEXT(1); } OP_STOREARRAY_I: { jint val = stack[--sp].I; int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; ARRAY_DATA_I(object)[index] = val; NEXT(1); } OP_STOREARRAY_J: { jlong val = stack[--sp].J; int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; ARRAY_DATA_J(object)[index] = val; NEXT(1); } OP_STOREARRAY_F: { jfloat val = stack[--sp].F; int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; ARRAY_DATA_F(object)[index] = val; NEXT(1); } OP_STOREARRAY_D: { jdouble val = stack[--sp].D; int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; ARRAY_DATA_D(object)[index] = val; NEXT(1); } OP_STOREARRAY_O: { ObjectPtr val = stack[--sp].O; int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; ARRAY_DATA_O(object)[index] = val; NEXT(1); } OP_STOREARRAY_B: { int val = stack[--sp].I; int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; ARRAY_DATA_B(object)[index] = (jbyte)val; NEXT(1); } OP_STOREARRAY_C: { int val = stack[--sp].I; int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; ARRAY_DATA_C(object)[index] = (jchar)val; NEXT(1); } OP_STOREARRAY_S: { int val = stack[--sp].I; int index = stack[--sp].I; Object *object = stack[--sp].O; ARRAY_CHECK; ARRAY_DATA_S(object)[index] = (jchar)val; NEXT(1); } OP_ARRAYLENGTH: { Object *array = stack[sp-1].O; NULL_CHECK(array); stack[sp-1].I = array->length; NEXT(1); } OP_IFNULL: sp--; if(stack[sp].O == NULL) { NEXT(op->index); } else NEXT(1); OP_IFNOTNULL: sp--; if(stack[sp].O != NULL) { NEXT(op->index); } else NEXT(1); OP_MONITORENTER: sp--; NEXT(1) OP_MONITOREXIT: sp--; NEXT(1) OP_TABLE: printf("!!!!!!!!!!!!!!!! OP_TABLE NOT IMPLEMENTED\n"); return; OP_LOOKUP: { int key = stack[--sp].I; OP *keys = (OP*)op->var.O; int j = 0; while(1) { int kpc = keys[j].pc; if(kpc == 0xFFFFFFFF) break; if(keys[j].index == key) {NEXT(kpc);} j++; } NEXT(op->index); } __EXCEPTION: { Object *exception = vm->exception; vm->exception = NULL; vm->frames[fp].pc = op->pc; CatchInfo *caught = find_catch_block(vm, omethod, exception, op->pc); if(!caught) { vm->exception = exception; vm->FP--; vm->SP -= method->maxStack + method->maxLocals; return; } stack[sp++].O = exception; op = (OP*)caught->label; NEXT(0); } }
27.702987
122
0.470418
[ "object" ]
bb1b404b2f5042ad6714e06a732c9fbfd22f0612
4,524
h
C
fboss/lib/LogThriftCall.h
nathanawmk/fboss
9f36dbaaae47202f9131598560c65715334a9a83
[ "BSD-3-Clause" ]
834
2015-03-10T18:12:28.000Z
2022-03-31T20:16:17.000Z
fboss/lib/LogThriftCall.h
nathanawmk/fboss
9f36dbaaae47202f9131598560c65715334a9a83
[ "BSD-3-Clause" ]
82
2015-04-07T08:48:29.000Z
2022-03-11T21:56:58.000Z
fboss/lib/LogThriftCall.h
nathanawmk/fboss
9f36dbaaae47202f9131598560c65715334a9a83
[ "BSD-3-Clause" ]
296
2015-03-11T03:45:37.000Z
2022-03-14T22:54:22.000Z
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include <folly/Conv.h> #include <folly/DynamicConverter.h> #include <folly/Range.h> #include <folly/futures/Future.h> #include <folly/json.h> #include <folly/logging/LogLevel.h> #include <folly/logging/Logger.h> #include <folly/logging/xlog.h> #include <thrift/lib/cpp2/server/Cpp2ConnContext.h> #include <sstream> #include <string> #define _LOGTHRIFTCALL_APPEND_PARAM(a) \ ss << #a "=" << folly::toJson(folly::toDynamic(a)) << ","; /* * This macro returns a LogThriftCall object that prints request * context info and also times the function. * * ex: auto log = LOG_THRIFT_CALL(DBG1); * * Also supports printing a few parameters: * * void dummyThrift( * std::unique_ptr<std::string> a, std::vector<int> b, int c) { * auto log = LOG_THRIFT_CALL(DBG1, *a, b, c); * ... * * This will print a line like: * "received thrift call from x ... params: *a="hello",b=[1,2,3],c=99, * * Only supports parameters that can be converted in to folly dynamic * with folly/DynamicConverter.h. It should be possible to extend to * add serialization implementation for custom types. We should look in * to adding support for arbitrary thrift (may require reflection). */ #define LOG_THRIFT_CALL(level, ...) \ ([&](folly::StringPiece func, \ folly::StringPiece file, \ uint32_t line, \ apache::thrift::Cpp2RequestContext* ctx) \ -> std::unique_ptr<::facebook::fboss::LogThriftCall> { \ if (!XLOG_IS_ON(level)) { \ /* short circuit case to avoid unnecessary work */ \ return nullptr; \ } \ static folly::Logger logger(XLOG_GET_CATEGORY_NAME()); \ std::stringstream ss; \ FOLLY_PP_FOR_EACH(_LOGTHRIFTCALL_APPEND_PARAM, ##__VA_ARGS__) \ return std::make_unique<::facebook::fboss::LogThriftCall>( \ logger, folly::LogLevel::level, func, file, line, ctx, ss.str()); \ }(__func__, __FILE__, __LINE__, getRequestContext())) #define FB_LOG_RAW_WITH_CONTEXT(...) \ FB_LOG_RAW(__VA_ARGS__) << "[" << folly::RequestContext::get() << "] " namespace facebook::fboss { class LogThriftCall { public: explicit LogThriftCall( const folly::Logger& logger, folly::LogLevel level, folly::StringPiece func, folly::StringPiece file, uint32_t line, apache::thrift::Cpp2RequestContext* ctx, std::string paramsStr); ~LogThriftCall(); // useful for wrap(Semi)?Future void markFailed() { failed_ = true; } private: LogThriftCall(LogThriftCall const&) = delete; LogThriftCall& operator=(LogThriftCall const&) = delete; folly::Logger logger_; folly::LogLevel level_; folly::StringPiece func_; folly::StringPiece file_; uint32_t line_; std::chrono::time_point<std::chrono::steady_clock> start_; bool failed_{false}; }; // inspiration for this is INSTRUMENT_THRIFT_CALL in EdenServiceHandler. // // TODO: add version for Coro once coro based thrift server is standardized template <typename RT> folly::Future<RT> wrapFuture( std::unique_ptr<LogThriftCall> logObject, folly::Future<RT>&& f) { return std::move(f).thenTry( [logger = std::move(logObject)](folly::Try<RT>&& ret) mutable { if (logger && ret.hasException()) { logger->markFailed(); } return std::forward<folly::Try<RT>>(ret); }); } template <typename RT> folly::SemiFuture<RT> wrapSemiFuture( std::unique_ptr<LogThriftCall> logObject, folly::SemiFuture<RT>&& f) { return std::move(f).defer( [logger = std::move(logObject)](folly::Try<RT>&& ret) mutable { if (logger && ret.hasException()) { logger->markFailed(); } return std::forward<folly::Try<RT>>(ret); }); } } // namespace facebook::fboss
34.8
79
0.601017
[ "object", "vector" ]
bb1be295218b5d4385f1ee00f3525304aed02646
1,029
h
C
RTCSDK/video_room_client_interface.h
ouxianghui/janus-client
7b8f9cef0f6488f09cd59046dda40cb22eb7b5a0
[ "MIT" ]
110
2020-10-27T02:15:35.000Z
2022-03-30T10:24:52.000Z
RTCSDK/video_room_client_interface.h
ouxianghui/janus-client
7b8f9cef0f6488f09cd59046dda40cb22eb7b5a0
[ "MIT" ]
13
2021-02-02T05:32:42.000Z
2022-03-13T15:03:26.000Z
RTCSDK/video_room_client_interface.h
ouxianghui/janus-client
7b8f9cef0f6488f09cd59046dda40cb22eb7b5a0
[ "MIT" ]
37
2020-11-13T15:44:23.000Z
2022-03-25T09:08:22.000Z
#pragma once #include <memory> #include <string> #include <vector> #include "video_room_models.h" namespace vi { class Participant; class IVideoRoomEventHandler; class ParticipantsContrllerInterface; class MediaControllerInterface; class VideoRoomClientInterface { public: virtual ~VideoRoomClientInterface() = default; virtual void init() = 0; virtual void destroy() = 0; virtual void registerEventHandler(std::shared_ptr<IVideoRoomEventHandler> handler) = 0; virtual void unregisterEventHandler(std::shared_ptr<IVideoRoomEventHandler> handler) = 0; virtual void attach() = 0; virtual void detach() = 0; virtual void create(std::shared_ptr<vr::CreateRoomRequest> request) = 0; virtual void join(std::shared_ptr<vr::PublisherJoinRequest> request) = 0; virtual void leave(std::shared_ptr<vr::LeaveRequest> request) = 0; virtual std::shared_ptr<ParticipantsContrllerInterface> participantsController() = 0; virtual std::shared_ptr<MediaControllerInterface> mediaContrller() = 0; }; }
23.930233
91
0.761905
[ "vector" ]
bb1f371959a37888aea3a9332cf1b443042528e0
23,943
c
C
apps/wifi_easy_config/firmware/src/config/pic32mz_w1_curiosity_freertos/library/tcpip/src/common/sys_fs_shell.c
ninode/wireless
2d0ecb13fd346758a3793008e0d2664298119fb3
[ "0BSD" ]
9
2020-01-30T14:55:29.000Z
2021-03-18T07:44:49.000Z
apps/wifi_easy_config/firmware/src/config/pic32mz_w1_curiosity_freertos/library/tcpip/src/common/sys_fs_shell.c
ninode/wireless
2d0ecb13fd346758a3793008e0d2664298119fb3
[ "0BSD" ]
10
2019-12-22T07:19:29.000Z
2021-08-12T08:37:21.000Z
apps/wifi_easy_config/firmware/src/config/pic32mz_w1_curiosity_freertos/library/tcpip/src/common/sys_fs_shell.c
ninode/wireless
2d0ecb13fd346758a3793008e0d2664298119fb3
[ "0BSD" ]
6
2020-10-05T15:36:10.000Z
2021-08-31T09:24:32.000Z
/******************************************************************************* Harmony File System Shell for TCPIP File Name: sys_fs_shell.c Summary: This file provides shell functions for Harmony SYS_FS calls Description: This file provides shell functions for Harmony SYS_FS calls *******************************************************************************/ // DOM-IGNORE-BEGIN /***************************************************************************** Copyright (C) 2012-2019 Microchip Technology Inc. and its subsidiaries. Microchip Technology Inc. and its subsidiaries. Subject to your compliance with these terms, you may use Microchip software and any derivatives exclusively with Microchip products. It is your responsibility to comply with third party license terms applicable to your use of third party software (including open source software) that may accompany Microchip software. THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. *****************************************************************************/ //#define SYS_FS_SHELL_MTHREAD_PROTECTION 0 //#define SYS_FS_SHELL_MALLOC malloc //#define SYS_FS_SHELL_FREE free #define SYS_FS_SHELL_DEBUG 0 // SYS_FS workaround // SYS_FS functions like SYS_FS_DirOpen() won't properly open a directory // if the directory name ends in '/'. // This workaround removes the trailing '/' from the path! // Should be fixed in the SYS_FS! #define SYS_FS_TRAIL_SLASH_WORKAROUND 1 // DOM-IGNORE-END // ***************************************************************************** // ***************************************************************************** // Section: Included Files // ***************************************************************************** // ***************************************************************************** #include <string.h> #include <stdlib.h> #include "./sys_fs_shell.h" #include "configuration.h" #if defined(SYS_FS_SHELL_MTHREAD_PROTECTION) && (SYS_FS_SHELL_MTHREAD_PROTECTION != 0) #define _SYS_FS_SHELL_MTHREAD_PROTECTION 1 #include "osal/osal.h" #else #define _SYS_FS_SHELL_MTHREAD_PROTECTION 0 #endif // (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) // local prototypes static SYS_FS_HANDLE Shell_FileOpen(const SYS_FS_SHELL_OBJ* pObj, const char *fname, SYS_FS_FILE_OPEN_ATTRIBUTES attributes); static SYS_FS_RESULT Shell_FileStat(const SYS_FS_SHELL_OBJ* pObj, const char *fname, SYS_FS_FSTAT *buf); static SYS_FS_RESULT Shell_FileDelete(const SYS_FS_SHELL_OBJ* pObj, const char *fname); static SYS_FS_HANDLE Shell_DirOpen(const SYS_FS_SHELL_OBJ* pObj, const char *fname); static SYS_FS_HANDLE Shell_DirMake(const SYS_FS_SHELL_OBJ* pObj, const char *fname); static SYS_FS_SHELL_RES Shell_Cwd(const SYS_FS_SHELL_OBJ* pObj, const char *cwd); static SYS_FS_SHELL_RES Shell_LastError(const SYS_FS_SHELL_OBJ* pObj); static SYS_FS_SHELL_RES Shell_Delete(const SYS_FS_SHELL_OBJ* pObj); static SYS_FS_RESULT Shell_FileClose(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle); static SYS_FS_RESULT Shell_DirClose(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle); static int32_t Shell_FileSize(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle); static int32_t Shell_FileSeek(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle, int32_t offset, SYS_FS_FILE_SEEK_CONTROL whence); static int32_t Shell_FileTell(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle); static bool Shell_FileEof(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle); static size_t Shell_FileRead(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle, void *buf, size_t nbyte); static size_t Shell_FileWrite(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle, const void *buf, size_t nbyte); static SYS_FS_SHELL_RES Shell_GetRoot(const SYS_FS_SHELL_OBJ* pObj, char* rootBuff, size_t rootBuffSize); static SYS_FS_SHELL_RES Shell_GetCwd(const SYS_FS_SHELL_OBJ* pObj, char* cwdBuff, size_t cwdBuffSize); struct _tag_SHELL_OBJ_INSTANCE; static SYS_FS_SHELL_RES Shell_FileAbsPath(struct _tag_SHELL_OBJ_INSTANCE *pShell, const char* fname, char* absBuff, size_t absBuffSize); // the constant shell object functions static const SYS_FS_SHELL_OBJ default_shell_obj = { .fileOpen = Shell_FileOpen, .fileStat = Shell_FileStat, .fileDelete = Shell_FileDelete, .dirOpen = Shell_DirOpen, .dirMake = Shell_DirMake, .fileClose = Shell_FileClose, .dirClose = Shell_DirClose, .fileSize = Shell_FileSize, .fileSeek = Shell_FileSeek, .fileTell = Shell_FileTell, .fileEof = Shell_FileEof, .fileRead = Shell_FileRead, .fileWrite = Shell_FileWrite, // .cwdSet = Shell_Cwd, .cwdGet = Shell_GetCwd, .rootGet = Shell_GetRoot, // .delete = Shell_Delete, .lastError = Shell_LastError, // }; // default shell object, containing the data typedef struct _tag_SHELL_OBJ_INSTANCE { SYS_FS_SHELL_OBJ obj; // private data const struct _tag_SHELL_OBJ_INSTANCE* self; // self reference; quick protection/check void (*freeFnc)(void*); // free function to use SYS_FS_SHELL_RES opError; uint16_t rootLen; // length of the root path uint16_t cwdLen; // length of the cwd #if (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) OSAL_SEM_HANDLE_TYPE mtSem; #endif // (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) uint8_t createFlags; // SYS_FS_SHELL_CREATE_FLAGS // root path; can never go higher than this char root[SYS_FS_FILE_NAME_LEN + 1]; // formatted as "/srv/ftp", or "" : no trailing / // current working directory char cwd[SYS_FS_FILE_NAME_LEN + 1]; // formatted as "/dir/", or "/", or "/dir/dir/dir/"; // leading /, trailing / // abs path is always: (root + cwd) // // whatever other data is needed here }SHELL_OBJ_INSTANCE; // inlines // protection #if (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) static __inline__ bool __attribute__((always_inline)) _InstanceLockCreate(OSAL_SEM_HANDLE_TYPE* pSem) { // create the shell Lock return OSAL_SEM_Create(pSem, OSAL_SEM_TYPE_BINARY, 1, 0) == OSAL_RESULT_TRUE; } static __inline__ void __attribute__((always_inline)) _InstanceLockDelete(OSAL_SEM_HANDLE_TYPE* pSem) { OSAL_SEM_Delete(pSem); } // locks access to shared shell resources static __inline__ void __attribute__((always_inline)) _InstanceLock(SHELL_OBJ_INSTANCE* pShell) { // Shared Data Lock OSAL_SEM_Pend(&pShell->mtSem, OSAL_WAIT_FOREVER); } // unlocks access to shared shell resources static __inline__ void __attribute__((always_inline)) _InstanceUnlock(SHELL_OBJ_INSTANCE* pShell) { // Shared Data unlock OSAL_SEM_Post(&pShell->mtSem); } #endif // (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) // locks a shell for usage // all (mutable) operations should happen on a locked object // returns the locked object if success, 0 otherwise static SHELL_OBJ_INSTANCE* _Shell_ObjectLock(const SYS_FS_SHELL_OBJ* pObj) { SHELL_OBJ_INSTANCE *pShell = (SHELL_OBJ_INSTANCE*)pObj; if(pShell != 0 && pShell->self == pShell) { #if (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) if((pShell->createFlags & SYS_FS_SHELL_FLAG_MTHREAD) != 0) { _InstanceLock(pShell); } #endif // (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) return pShell; } return 0; } // unlocks the shell object // additionally sets the last operation error is error != SYS_FS_SHELL_RES_OK // returns the passed in error code static SYS_FS_SHELL_RES _Shell_ObjectUnlock(SHELL_OBJ_INSTANCE* pShell, SYS_FS_SHELL_RES error) { if(error != SYS_FS_SHELL_RES_OK) { pShell->opError = error; } #if (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) if((pShell->createFlags & SYS_FS_SHELL_FLAG_MTHREAD) != 0) { _InstanceUnlock(pShell); } #endif // (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) return error; } // API // const SYS_FS_SHELL_OBJ* SYS_FS_Shell_Create(const char* rootDir, SYS_FS_SHELL_CREATE_FLAGS flags, void*(*shell_malloc_fnc)(size_t), void(*shell_free_fnc)(void*), SYS_FS_SHELL_RES* pRes) { int rootLen; bool needsRoot = false; SYS_FS_SHELL_RES res = SYS_FS_SHELL_RES_OK; SHELL_OBJ_INSTANCE* newObj = 0; #if (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) OSAL_SEM_HANDLE_TYPE shellSem = 0; #endif // (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) while(true) { if(rootDir == 0 || (rootLen = strlen(rootDir)) == 0) { res = SYS_FS_SHELL_RES_BAD_ARG; break; } if(rootDir[0] != '/') { // need to add it rootLen++; needsRoot = true; } if(rootLen > sizeof(newObj->root) - 1) { res = SYS_FS_SHELL_RES_LENGTH_ERROR; break; } // create the synchronization object #if (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) if((flags & SYS_FS_SHELL_FLAG_MTHREAD) != 0) { if(!_InstanceLockCreate(&shellSem)) { res = SYS_FS_SHELL_RES_LOCK_ERROR; break; } } #endif // (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) // create the object if(shell_malloc_fnc == 0) { #if defined(SYS_FS_SHELL_MALLOC) shell_malloc_fnc = SYS_FS_SHELL_MALLOC; #else shell_malloc_fnc = malloc; #endif // defined(SYS_FS_SHELL_MALLOC) } newObj = (SHELL_OBJ_INSTANCE*)(*shell_malloc_fnc)(sizeof(*newObj)); if(newObj == 0) { res = SYS_FS_SHELL_RES_MEM_ERROR; break; } // init the object memset(newObj, 0, sizeof(*newObj)); newObj->obj = default_shell_obj; newObj->self = newObj; char* pRoot = newObj->root; if(needsRoot) { *pRoot++ = '/'; } strncpy(pRoot, rootDir, sizeof(newObj->root) - 1); if(rootDir[rootLen - 1] == '/') { // remove the ending '/' newObj->root[rootLen - 1] = 0; rootLen--; } newObj->rootLen = rootLen; newObj->cwd[0] = '/'; newObj->cwdLen = 1; #if (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) newObj->mtSem = shellSem; #endif // (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) newObj->createFlags = flags; if(shell_free_fnc == 0) { #if defined(SYS_FS_SHELL_FREE) shell_free_fnc = SYS_FS_SHELL_FREE; #else shell_free_fnc = free; #endif // defined(SYS_FS_SHELL_FREE) } newObj->freeFnc = shell_free_fnc; res = SYS_FS_SHELL_RES_OK; break; } if(pRes) { *pRes = res; } return newObj ? &newObj->obj : 0; } // local object functions implementation // static SYS_FS_SHELL_RES Shell_Cwd(const SYS_FS_SHELL_OBJ* pObj, const char *path) { SYS_FS_HANDLE fsHandle = SYS_FS_HANDLE_INVALID; SHELL_OBJ_INSTANCE *pShell = _Shell_ObjectLock(pObj); if(!pShell) { return SYS_FS_SHELL_RES_NO_OBJECT; } int len_path; if(path == 0 || (len_path = strlen(path)) == 0) { return _Shell_ObjectUnlock(pShell, SYS_FS_SHELL_RES_BAD_ARG); } bool need_end = false; char path_buff[SYS_FS_FILE_NAME_LEN + 1]; char abs_buff[SYS_FS_FILE_NAME_LEN + 1]; if(path[len_path - 1] != '/') { // we need to add this need_end = true; len_path++; } if(len_path > sizeof(path_buff) - 1) { return _Shell_ObjectUnlock(pShell, SYS_FS_SHELL_RES_LENGTH_ERROR); } strcpy(path_buff, path); if(need_end) { path_buff[len_path - 1] = '/'; path_buff[len_path] = 0; } SYS_FS_SHELL_RES absRes = Shell_FileAbsPath(pShell, path_buff, abs_buff, sizeof(abs_buff)); if(absRes != SYS_FS_SHELL_RES_OK) { // failed return _Shell_ObjectUnlock(pShell, absRes); } // do not allow an invalid directory as the cwd // check if the new cwd is a valid directory. fsHandle = SYS_FS_DirOpen(abs_buff); if(fsHandle == SYS_FS_HANDLE_INVALID) { return _Shell_ObjectUnlock(pShell, SYS_FS_SHELL_RES_DIR_ERROR); } // OK, close the directory SYS_FS_DirClose(fsHandle); strcpy(pShell->cwd, abs_buff + pShell->rootLen); int len_cwd = strlen(pShell->cwd); char* end_cwd = pShell->cwd + len_cwd - 1; if(*end_cwd != '/') { *++end_cwd = '/'; *++end_cwd = 0; len_cwd++; } pShell->cwdLen = len_cwd; return _Shell_ObjectUnlock(pShell, SYS_FS_SHELL_RES_OK); } static SYS_FS_HANDLE Shell_FileOpen(const SYS_FS_SHELL_OBJ* pObj, const char *fname, SYS_FS_FILE_OPEN_ATTRIBUTES attributes) { SYS_FS_HANDLE fsHandle = SYS_FS_HANDLE_INVALID; SHELL_OBJ_INSTANCE *pShell = _Shell_ObjectLock(pObj); if(pShell) { char absBuff[SYS_FS_FILE_NAME_LEN + 1]; SYS_FS_SHELL_RES absRes = Shell_FileAbsPath(pShell, fname, absBuff, sizeof(absBuff)); _Shell_ObjectUnlock(pShell, absRes); if(absRes == SYS_FS_SHELL_RES_OK) { fsHandle = SYS_FS_FileOpen(absBuff, attributes); } } return fsHandle; } static SYS_FS_RESULT Shell_FileStat(const SYS_FS_SHELL_OBJ* pObj, const char *fname, SYS_FS_FSTAT* statBuff) { SYS_FS_RESULT fsRes = SYS_FS_RES_FAILURE; SHELL_OBJ_INSTANCE *pShell = _Shell_ObjectLock(pObj); if(pShell) { char absBuff[SYS_FS_FILE_NAME_LEN + 1]; SYS_FS_SHELL_RES absRes = Shell_FileAbsPath(pShell, fname, absBuff, sizeof(absBuff)); _Shell_ObjectUnlock(pShell, absRes); if(absRes == SYS_FS_SHELL_RES_OK) { fsRes = SYS_FS_FileStat(absBuff, statBuff); } } return fsRes; } static SYS_FS_RESULT Shell_FileDelete(const SYS_FS_SHELL_OBJ* pObj, const char *fname) { SYS_FS_RESULT fsRes = SYS_FS_RES_FAILURE; SHELL_OBJ_INSTANCE *pShell = _Shell_ObjectLock(pObj); if(pShell) { char absBuff[SYS_FS_FILE_NAME_LEN + 1]; SYS_FS_SHELL_RES absRes = Shell_FileAbsPath(pShell, fname, absBuff, sizeof(absBuff)); _Shell_ObjectUnlock(pShell, absRes); if(absRes == SYS_FS_SHELL_RES_OK) { fsRes = SYS_FS_FileDirectoryRemove(absBuff); } } return fsRes; } static SYS_FS_HANDLE Shell_DirMake(const SYS_FS_SHELL_OBJ* pObj, const char *fname) { SYS_FS_HANDLE fsHandle = SYS_FS_HANDLE_INVALID; SHELL_OBJ_INSTANCE *pShell = _Shell_ObjectLock(pObj); if(pShell) { char absBuff[SYS_FS_FILE_NAME_LEN + 1]; SYS_FS_SHELL_RES absRes = Shell_FileAbsPath(pShell, fname, absBuff, sizeof(absBuff)); _Shell_ObjectUnlock(pShell, absRes); if(absRes == SYS_FS_SHELL_RES_OK) { fsHandle = SYS_FS_DirectoryMake(absBuff); } } return fsHandle; } static SYS_FS_HANDLE Shell_DirOpen(const SYS_FS_SHELL_OBJ* pObj, const char *fname) { SYS_FS_HANDLE fsHandle = SYS_FS_HANDLE_INVALID; SHELL_OBJ_INSTANCE *pShell = _Shell_ObjectLock(pObj); if(pShell) { char absBuff[SYS_FS_FILE_NAME_LEN + 1]; SYS_FS_SHELL_RES absRes = Shell_FileAbsPath(pShell, fname, absBuff, sizeof(absBuff)); _Shell_ObjectUnlock(pShell, absRes); if(absRes == SYS_FS_SHELL_RES_OK) { fsHandle = SYS_FS_DirOpen(absBuff); } } return fsHandle; } static SYS_FS_SHELL_RES Shell_LastError(const SYS_FS_SHELL_OBJ* pObj) { SYS_FS_SHELL_RES res = SYS_FS_SHELL_RES_NO_OBJECT; SHELL_OBJ_INSTANCE *pShell = _Shell_ObjectLock(pObj); if(pShell) { res = pShell->opError; pShell->opError = 0; _Shell_ObjectUnlock(pShell, SYS_FS_SHELL_RES_OK); } return res; } static SYS_FS_SHELL_RES Shell_Delete(const SYS_FS_SHELL_OBJ* pObj) { SHELL_OBJ_INSTANCE *pShell = _Shell_ObjectLock(pObj); if(!pShell) { return SYS_FS_SHELL_RES_NO_OBJECT; } void(*shell_free_fnc)(void*) = pShell->freeFnc; #if (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) OSAL_SEM_HANDLE_TYPE sem = pShell->mtSem; uint8_t flags = pShell->createFlags; memset(pShell, 0, sizeof(*pShell)); if((flags & SYS_FS_SHELL_FLAG_MTHREAD) != 0) { _InstanceLockDelete(&sem); } #else memset(pShell, 0, sizeof(*pShell)); #endif // (_SYS_FS_SHELL_MTHREAD_PROTECTION != 0) (*shell_free_fnc)(pShell); return SYS_FS_SHELL_RES_OK; } static SYS_FS_RESULT Shell_FileClose(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle) { (void)pObj; return SYS_FS_FileClose(handle); } static SYS_FS_RESULT Shell_DirClose(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle) { (void)pObj; return SYS_FS_DirClose(handle); } static int32_t Shell_FileSize(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle) { (void)pObj; return SYS_FS_FileSize(handle); } static int32_t Shell_FileSeek(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle, int32_t offset, SYS_FS_FILE_SEEK_CONTROL whence) { (void)pObj; return SYS_FS_FileSeek(handle, offset, whence); } static int32_t Shell_FileTell(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle) { (void)pObj; return SYS_FS_FileTell(handle); } static bool Shell_FileEof(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle) { (void)pObj; return SYS_FS_FileEOF(handle); } static size_t Shell_FileRead(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle, void *buf, size_t nbyte) { (void)pObj; return SYS_FS_FileRead(handle, buf, nbyte); } static size_t Shell_FileWrite(const SYS_FS_SHELL_OBJ* pObj, SYS_FS_HANDLE handle, const void *buf, size_t nbyte) { (void)pObj; return SYS_FS_FileWrite(handle, buf, nbyte); } static SYS_FS_SHELL_RES Shell_GetRoot(const SYS_FS_SHELL_OBJ* pObj, char* rootBuff, size_t rootBuffSize) { if(rootBuff == 0 || rootBuffSize == 0) { return SYS_FS_SHELL_RES_BAD_ARG; } SHELL_OBJ_INSTANCE *pShell = _Shell_ObjectLock(pObj); if(!pShell) { return SYS_FS_SHELL_RES_NO_OBJECT; } SYS_FS_SHELL_RES res; if(pShell->rootLen > rootBuffSize - 1) { res = SYS_FS_SHELL_RES_LENGTH_ERROR; } else { res = SYS_FS_SHELL_RES_OK; } strncpy(rootBuff, pShell->root, rootBuffSize - 1); rootBuff[rootBuffSize - 1] = 0; _Shell_ObjectUnlock(pShell, SYS_FS_SHELL_RES_OK); return res; } static SYS_FS_SHELL_RES Shell_GetCwd(const SYS_FS_SHELL_OBJ* pObj, char* cwdBuff, size_t cwdBuffSize) { if(cwdBuff == 0 || cwdBuffSize == 0) { return SYS_FS_SHELL_RES_BAD_ARG; } SHELL_OBJ_INSTANCE *pShell = _Shell_ObjectLock(pObj); if(!pShell) { return SYS_FS_SHELL_RES_NO_OBJECT; } SYS_FS_SHELL_RES res; if(pShell->cwdLen > cwdBuffSize - 1) { res = SYS_FS_SHELL_RES_LENGTH_ERROR; } else { res = SYS_FS_SHELL_RES_OK; } strncpy(cwdBuff, pShell->cwd, cwdBuffSize - 1); cwdBuff[cwdBuffSize - 1] = 0; _Shell_ObjectUnlock(pShell, SYS_FS_SHELL_RES_OK); return res; } // local helpers // calculates the absolute path for the passed in fname into the supplied absBuff buffer // buffSize is the total buffer size, including the \0 // returns 0 (SYS_FS_SHELL_RES_OK) if success // otherwise an error code static SYS_FS_SHELL_RES Shell_FileAbsPath(SHELL_OBJ_INSTANCE *pShell, const char* fname, char* absBuff, size_t absBuffSize) { int f_len, cwd_len; char *end_cwd; if(fname == 0 || (f_len = strlen(fname)) == 0) { return SYS_FS_SHELL_RES_BAD_ARG; } cwd_len = pShell->cwdLen; end_cwd = pShell->cwd + cwd_len; if(fname[0] == '.') { // relative path if(fname[1] == '/') { // OK, starting with ./ start with the current cwd fname += 2; } else if(fname[1] == 0) { // OK, "." should still mean current directory fname += 1; } else if(fname[1] != '.' || fname[2] != '/') { return SYS_FS_SHELL_RES_BAD_ARG; } else { // ../ access while(strstr(fname, "../") == fname) { fname += 3; int up_lev = 0; while(true) { if(end_cwd <= pShell->cwd) { // cannot go up return SYS_FS_SHELL_RES_LEVEL_ERROR; } // skip 2 /'s; the 1st one is the current level if(*(end_cwd - 1) == '/') { if(++up_lev == 2) { break; } } end_cwd--; } } cwd_len = end_cwd - pShell->cwd; } } else { // ok, regular file name; just append whatever to the cwd // except if the full path is given if(fname[0] == '/') { if((pShell->createFlags & SYS_FS_SHELL_FLAG_ABS_ROOT) != 0) { // check that it's under our root so we allow access strcpy(absBuff, pShell->root); strcat(absBuff, "/"); // root doesn't have trailing / if(strstr(fname, absBuff) != fname) { return SYS_FS_SHELL_RES_DIR_ERROR; } // ok, it's under our root; remove the root part fname += strlen(absBuff); } else { // skip the shell->cwd cwd_len = 0; } } } // regular checks f_len = strlen(fname); if(pShell->rootLen + cwd_len + f_len > absBuffSize - 1) { // too long return SYS_FS_SHELL_RES_LENGTH_ERROR; } // start with root strcpy(absBuff, pShell->root); if(cwd_len != 0) { // add cwd strncpy(absBuff + pShell->rootLen, pShell->cwd, cwd_len + 1); } // add the file name strcpy(absBuff + pShell->rootLen + cwd_len, fname); absBuff[absBuffSize - 1] = 0; #if (SYS_FS_TRAIL_SLASH_WORKAROUND != 0) int absLen = strlen(absBuff); char* pEnd = absBuff + absLen - 1; if(*pEnd == '/') { *pEnd = 0; } #endif // (SYS_FS_TRAIL_SLASH_WORKAROUND != 0) return SYS_FS_SHELL_RES_OK; } #if (SYS_FS_SHELL_DEBUG != 0) SYS_FS_SHELL_RES SYS_FS_Shell_GetPath(const struct _tag_SYS_FS_SHELL_OBJ* pObj, const char *fname, char* resBuff, size_t resBuffSize) { if(fname == 0 || resBuff == 0 || resBuffSize == 0) { return SYS_FS_SHELL_RES_BAD_ARG; } SHELL_OBJ_INSTANCE *pShell = _Shell_ObjectLock(pObj); if(pShell) { SYS_FS_SHELL_RES absRes = Shell_FileAbsPath(pShell, fname, resBuff, resBuffSize); _Shell_ObjectUnlock(pShell, absRes); return absRes; } return SYS_FS_SHELL_RES_NO_OBJECT; } #endif // (SYS_FS_SHELL_DEBUG != 0)
30.696154
185
0.634799
[ "object" ]
bb1f52b2c5ea24a226922eae9dee6474e8213bc3
14,890
h
C
third_party/virtualbox/src/VBox/Additions/x11/x11include/xorg-server-1.1.0/Pcl.h
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
521
2019-03-29T15:44:08.000Z
2022-03-22T09:46:19.000Z
third_party/virtualbox/src/VBox/Additions/x11/x11include/xorg-server-1.1.0/Pcl.h
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
30
2019-06-04T17:00:49.000Z
2021-09-08T20:44:19.000Z
third_party/virtualbox/src/VBox/Additions/x11/x11include/xorg-server-1.1.0/Pcl.h
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
99
2019-03-29T16:04:13.000Z
2022-03-28T16:59:34.000Z
/* $Xorg: Pcl.h,v 1.3 2000/08/17 19:48:07 cpqbld Exp $ */ /******************************************************************* ** ** ********************************************************* ** * ** * File: Pcl.h ** * ** * Contents: defines and includes for the Pcl driver ** * for a printing X server. ** * ** * Created: 1/30/95 ** * ** ********************************************************* ** ********************************************************************/ /* (c) Copyright 1996 Hewlett-Packard Company (c) Copyright 1996 International Business Machines Corp. (c) Copyright 1996 Sun Microsystems, Inc. (c) Copyright 1996 Novell, Inc. (c) Copyright 1996 Digital Equipment Corp. (c) Copyright 1996 Fujitsu Limited (c) Copyright 1996 Hitachi, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the names of the copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from said copyright holders. */ /* $XFree86: xc/programs/Xserver/Xprint/pcl/Pcl.h,v 1.12 2001/12/21 21:02:05 dawes Exp $ */ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> #endif #ifndef _PCL_H_ #define _PCL_H_ #include <stdio.h> #include "scrnintstr.h" #include "PclDef.h" #include "Pclmap.h" #include "PclSFonts.h" #include <X11/extensions/Print.h> #include <X11/extensions/Printstr.h> #include "regionstr.h" #include <X11/fonts/fontstruct.h> #include "dixfontstr.h" #include "gcstruct.h" /* * Some sleazes to force the XrmDB stuff into the server */ #ifndef HAVE_XPointer typedef char *XPointer; #endif #define Status int #define True 1 #define False 0 #include "misc.h" #include <X11/Xfuncproto.h> #include <X11/Xresource.h> #include "attributes.h" /****** * externally visible variables from PclInit.c ******/ extern int PclScreenPrivateIndex, PclWindowPrivateIndex; extern int PclContextPrivateIndex; extern int PclPixmapPrivateIndex; extern int PclGCPrivateIndex; /****** * externally visible variables from PclAttVal.c ******/ extern XpValidatePoolsRec PclValidatePoolsRec; /* * This structure defines a mapping from an X colormap ID to a list of * print contexts which use the colormap. */ typedef struct _pclcontextlist { XpContextPtr context; struct _pclcontextlist *next; } PclContextList, *PclContextListPtr; typedef struct _pclcmaptocontexts { long colormapId; PclContextListPtr contexts; struct _pclcmaptocontexts *next; } PclCmapToContexts; typedef struct { PclCmapToContexts *colormaps; CloseScreenProcPtr CloseScreen; } PclScreenPrivRec, *PclScreenPrivPtr; /* * This structure defines a mapping from an X colormap ID to a PCL * palette ID. */ typedef struct _palettemap { long colormapId; int paletteId; int downloaded; struct _palettemap *next; } PclPaletteMap, *PclPaletteMapPtr; typedef struct { char *jobFileName; FILE *pJobFile; char *pageFileName; FILE *pPageFile; GC lastGC; unsigned char *dash; int validGC; ClientPtr getDocClient; int getDocBufSize; PclSoftFontInfoPtr pSoftFontInfo; PclPaletteMapPtr palettes; int currentPalette; int nextPaletteId; PclPaletteMap staticGrayPalette; PclPaletteMap trueColorPalette; PclPaletteMap specialTrueColorPalette; unsigned char *ctbl; int ctbldim; int isRaw; #ifdef XP_PCL_LJ3 unsigned int fcount; unsigned int fcount_max; char *figures; #endif /* XP_PCL_LJ3 */ } PclContextPrivRec, *PclContextPrivPtr; typedef struct { int validContext; XpContextPtr context; } PclWindowPrivRec, *PclWindowPrivPtr; typedef struct { unsigned long stippleFg, stippleBg; } PclGCPrivRec, *PclGCPrivPtr; typedef struct { XpContextPtr context; char *tempFileName; FILE *tempFile; GC lastGC; int validGC; } PclPixmapPrivRec, *PclPixmapPrivPtr; /****** * Defined functions ******/ #define SEND_PCL(f,c) fwrite( c, sizeof( char ), strlen( c ), f ) #define SEND_PCL_COUNT(f,c,n) fwrite( c, sizeof( char ), n, f ) #ifndef XP_PCL_LJ3 #define SAVE_PCL(f,p,c) SEND_PCL(f,c) #define SAVE_PCL_COUNT(f,p,c,n) SEND_PCL_COUNT(f,c,n) #define MACRO_START(f,p) SEND_PCL(f, "\033&f1Y\033&f0X") #define MACRO_END(f) SEND_PCL(f, "\033&f1X") #else #define SAVE_PCL(f,p,c) PclSpoolFigs(p, c, strlen(c)) #define SAVE_PCL_COUNT(f,p,c,n) PclSpoolFigs(p, c, n) #define MACRO_START(f,p) p->fcount = 0 #define MACRO_END(f) /* do nothing */ #endif /* XP_PCL_LJ3 */ #define MIN(a,b) (((a)<(b))?(a):(b)) #ifndef MAX #define MAX(a,b) (((a)>(b))?(a):(b)) #endif /****** * Functions in PclArc.c ******/ extern void PclPolyArc( DrawablePtr pDrawable, GCPtr pGC, int nArcs, xArc *pArcs); extern void PclPolyFillArc( DrawablePtr pDrawable, GCPtr pGC, int nArcs, xArc *pArcs); /****** * Functions in PclArea.c ******/ extern void PclPutImage( DrawablePtr pDrawable, GCPtr pGC, int depth, int x, int y, int w, int h, int leftPad, int format, char *pImage); extern RegionPtr PclCopyArea( DrawablePtr pSrc, DrawablePtr pDst, GCPtr pGC, int srcx, int srcy, int width, int height, int dstx, int dsty); RegionPtr PclCopyPlane( DrawablePtr pSrc, DrawablePtr pDst, GCPtr pGC, int srcx, int srcy, int width, int height, int dstx, int dsty, unsigned long plane); /****** * Functions in PclAttr.c ******/ extern char *PclGetAttributes( XpContextPtr pCon, XPAttributes pool ); extern char *PclGetOneAttribute( XpContextPtr pCon, XPAttributes pool, char *attr ); extern int PclAugmentAttributes( XpContextPtr pCon, XPAttributes pool, char *attrs ); extern int PclSetAttributes( XpContextPtr pCon, XPAttributes pool, char *attrs ); /****** * Functions in PclColor.c ******/ extern Bool PclCreateDefColormap(ScreenPtr pScreen); extern Bool PclCreateColormap(ColormapPtr pColor); extern void PclDestroyColormap(ColormapPtr pColor); extern void PclInstallColormap(ColormapPtr pColor); extern void PclUninstallColormap(ColormapPtr pColor); extern int PclListInstalledColormaps(ScreenPtr pScreen, XID *pCmapList); extern void PclStoreColors(ColormapPtr pColor, int ndef, xColorItem *pdefs); extern void PclResolveColor(unsigned short *pRed, unsigned short *pGreen, unsigned short *pBlue, VisualPtr pVisual); extern int PclUpdateColormap(DrawablePtr pDrawable, XpContextPtr pCon, GCPtr gc, FILE *outFile); extern void PclLookUp(ColormapPtr cmap, PclContextPrivPtr cPriv, unsigned short *r, unsigned short *g, unsigned short *b); extern PclPaletteMapPtr PclFindPaletteMap(PclContextPrivPtr cPriv, ColormapPtr cmap, GCPtr gc); extern unsigned char *PclReadMap(char *, int *); /****** * Functions in PclCursor.c ******/ extern void PclConstrainCursor( ScreenPtr pScreen, BoxPtr pBox); extern void PclCursorLimits( ScreenPtr pScreen, CursorPtr pCursor, BoxPtr pHotBox, BoxPtr pTopLeftbox); extern Bool PclDisplayCursor( ScreenPtr pScreen, CursorPtr pCursor); extern Bool PclRealizeCursor( ScreenPtr pScreen, CursorPtr pCursor); extern Bool PclUnrealizeCursor( ScreenPtr pScreen, CursorPtr pCursor); extern void PclRecolorCursor( ScreenPtr pScreen, CursorPtr pCursor, Bool displayed); extern Bool PclSetCursorPosition( ScreenPtr pScreen, int x, int y, Bool generateEvent); /****** * Functions in PclSFonts.c ******/ extern void PclDownloadSoftFont8( FILE *fp, PclSoftFontInfoPtr pSoftFontInfo, PclFontHead8Ptr pfh, PclCharDataPtr pcd, unsigned char *code); extern void PclDownloadSoftFont16( FILE *fp, PclSoftFontInfoPtr pSoftFontInfo, PclFontHead16Ptr pfh, PclCharDataPtr pcd, unsigned char row, unsigned char col); extern PclSoftFontInfoPtr PclCreateSoftFontInfo(void); extern void PclDestroySoftFontInfo( PclSoftFontInfoPtr pSoftFontInfo ); /****** * Functions in PclGC.c ******/ extern Bool PclCreateGC(GCPtr pGC); extern void PclDestroyGC(GCPtr pGC); extern int PclUpdateDrawableGC( GCPtr pGC, DrawablePtr pDrawable, FILE **outFile); extern void PclValidateGC( GCPtr pGC, unsigned long changes, DrawablePtr pDrawable); extern void PclSetDrawablePrivateStuff( DrawablePtr pDrawable, GC gc ); extern int PclGetDrawablePrivateStuff( DrawablePtr pDrawable, GC *gc, unsigned long *valid, FILE **file ); extern void PclSetDrawablePrivateGC( DrawablePtr pDrawable, GC gc); extern void PclComputeCompositeClip( GCPtr pGC, DrawablePtr pDrawable); /****** * Functions in PclInit.c ******/ extern Bool PclCloseScreen( int index, ScreenPtr pScreen); extern Bool InitializeColorPclDriver( int ndx, ScreenPtr pScreen, int argc, char **argv); extern Bool InitializeMonoPclDriver( int ndx, ScreenPtr pScreen, int argc, char **argv); extern Bool InitializeLj3PclDriver( int ndx, ScreenPtr pScreen, int argc, char **argv); extern XpContextPtr PclGetContextFromWindow( WindowPtr win ); /****** * Functions in PclLine.c ******/ extern void PclPolyLine( DrawablePtr pDrawable, GCPtr pGC, int mode, int nPoints, xPoint *pPoints); extern void PclPolySegment( DrawablePtr pDrawable, GCPtr pGC, int nSegments, xSegment *pSegments); /****** * Functions in PclMisc.c ******/ extern void PclQueryBestSize( int class, short *pwidth, short *pheight, ScreenPtr pScreen); extern char *GetPropString(WindowPtr pWin, char *propName); extern int SystemCmd(char *cmdStr); extern int PclGetMediumDimensions( XpContextPtr pCon, CARD16 *pWidth, CARD16 *pHeight); extern int PclGetReproducibleArea( XpContextPtr pCon, xRectangle *pRect); extern void PclSendData( FILE *outFile, PclContextPrivPtr pConPriv, BoxPtr pbox, int nbox, double ratio); /****** * Functions in PclPixel.c ******/ extern void PclPolyPoint( DrawablePtr pDrawable, GCPtr pGC, int mode, int nPoints, xPoint *pPoints); extern void PclPushPixels( GCPtr pGC, PixmapPtr pBitmap, DrawablePtr pDrawable, int width, int height, int x, int y); /****** * Functions in PclPixmap.c ******/ extern PixmapPtr PclCreatePixmap( ScreenPtr pScreen, int width, int height, int depth); extern Bool PclDestroyPixmap(PixmapPtr pPixmap); /****** * Functions in PclPolygon.c ******/ extern void PclPolyRectangle( DrawablePtr pDrawable, GCPtr pGC, int nRects, xRectangle *pRects); extern void PclFillPolygon( DrawablePtr pDrawable, GCPtr pGC, int shape, int mode, int nPoints, DDXPointPtr pPoints); extern void PclPolyFillRect( DrawablePtr pDrawable, GCPtr pGC, int nRects, xRectangle *pRects); /****** * Functions in PclSpans.c ******/ extern void PclFillSpans( DrawablePtr pDrawable, GCPtr pGC, int nSpans, DDXPointPtr pPoints, int *pWidths, int fSorted); extern void PclSetSpans( DrawablePtr pDrawable, GCPtr pGC, char *pSrc, DDXPointPtr pPoints, int *pWidths, int nSpans, int fSorted); /****** * Functions in PclText.c ******/ extern int PclPolyText8( DrawablePtr pDrawable, GCPtr pGC, int x, int y, int count, char *string); extern int PclPolyText16( DrawablePtr pDrawable, GCPtr pGC, int x, int y, int count, unsigned short *string); extern void PclImageText8( DrawablePtr pDrawable, GCPtr pGC, int x, int y, int count, char *string); extern void PclImageText16( DrawablePtr pDrawable, GCPtr pGC, int x, int y, int count, unsigned short *string); extern void PclImageGlyphBlt( DrawablePtr pDrawable, GCPtr pGC, int x, int y, unsigned int nGlyphs, CharInfoPtr *pCharInfo, pointer pGlyphBase); extern void PclPolyGlyphBlt( DrawablePtr pDrawable, GCPtr pGC, int x, int y, unsigned int nGlyphs, CharInfoPtr *pCharInfo, pointer pGlyphBase); /****** * Functions in PclWindow.c ******/ extern Bool PclCreateWindow(register WindowPtr pWin); extern Bool PclDestroyWindow(WindowPtr pWin); extern Bool PclMapWindow(WindowPtr pWindow); extern Bool PclPositionWindow( register WindowPtr pWin, int x, int y); extern Bool PclUnmapWindow(WindowPtr pWindow); extern void PclCopyWindow( WindowPtr pWin, DDXPointRec ptOldOrg, RegionPtr prgnSrc); extern Bool PclChangeWindowAttributes( register WindowPtr pWin, register unsigned long mask); extern void PclPaintWindow( WindowPtr pWin, RegionPtr pRegion, int what); /****** * Functions in PclFonts.c ******/ extern Bool PclRealizeFont( ScreenPtr pscr, FontPtr pFont); extern Bool PclUnrealizeFont( ScreenPtr pscr, FontPtr pFont); /****** * Functions in PclPrint.c ******/ extern int PclStartJob( XpContextPtr pCon, Bool sendClientData, ClientPtr client); extern int PclEndJob( XpContextPtr pCon, Bool cancel); extern int PclStartPage( XpContextPtr pCon, WindowPtr pWin); extern int PclEndPage( XpContextPtr pCon, WindowPtr pWin); extern int PclStartDoc(XpContextPtr pCon, XPDocumentType type); extern int PclEndDoc( XpContextPtr pCon, Bool cancel); extern int PclDocumentData( XpContextPtr pCon, DrawablePtr pDraw, char *pData, int len_data, char *pFmt, int len_fmt, char *pOpt, int len_opt, ClientPtr client); extern int PclGetDocumentData( XpContextPtr pCon, ClientPtr client, int maxBufferSize); #endif /* _PCL_H_ */
23.785942
91
0.684486
[ "shape" ]
bb219c32d210b72f6ae9f41b196ac372b11398f7
7,557
h
C
build/gcc-2.6.3/loop.h
VivekMaran27/How-to-install-SimpleScalar-on-Ubuntu
2c0d4f4d41087508b304664fe1a6da6f86fb830b
[ "MIT" ]
null
null
null
build/gcc-2.6.3/loop.h
VivekMaran27/How-to-install-SimpleScalar-on-Ubuntu
2c0d4f4d41087508b304664fe1a6da6f86fb830b
[ "MIT" ]
null
null
null
build/gcc-2.6.3/loop.h
VivekMaran27/How-to-install-SimpleScalar-on-Ubuntu
2c0d4f4d41087508b304664fe1a6da6f86fb830b
[ "MIT" ]
null
null
null
/* Loop optimization definitions for GNU C-Compiler Copyright (C) 1991 Free Software Foundation, Inc. This file is part of GNU CC. GNU CC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU CC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU CC; see the file COPYING. If not, write to the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Get the luid of an insn. Catch the error of trying to reference the LUID of an insn added during loop, since these don't have LUIDs. */ #define INSN_LUID(INSN) \ (INSN_UID (INSN) < max_uid_for_loop ? uid_luid[INSN_UID (INSN)] \ : (abort (), -1)) /* A "basic induction variable" or biv is a pseudo reg that is set (within this loop) only by incrementing or decrementing it. */ /* A "general induction variable" or giv is a pseudo reg whose value is a linear function of a biv. */ /* Bivs are recognized by `basic_induction_var'; Givs by `general_induct_var'. */ /* An enum for the two different types of givs, those that are used as memory addresses and those that are calculated into registers. */ enum g_types { DEST_ADDR, DEST_REG }; /* A `struct induction' is created for every instruction that sets an induction variable (either a biv or a giv). */ struct induction { rtx insn; /* The insn that sets a biv or giv */ rtx new_reg; /* New register, containing strength reduced version of this giv. */ rtx src_reg; /* Biv from which this giv is computed. (If this is a biv, then this is the biv.) */ enum g_types giv_type; /* Indicate whether DEST_ADDR or DEST_REG */ rtx dest_reg; /* Destination register for insn: this is the register which was the biv or giv. For a biv, this equals src_reg. For a DEST_ADDR type giv, this is 0. */ rtx *location; /* Place in the insn where this giv occurs. If GIV_TYPE is DEST_REG, this is 0. */ enum machine_mode mode; /* The mode of this biv or giv */ enum machine_mode mem_mode; /* For DEST_ADDR, mode of the memory object. */ rtx mult_val; /* Multiplicative factor for src_reg. */ rtx add_val; /* Additive constant for that product. */ int benefit; /* Gain from eliminating this insn. */ rtx final_value; /* If the giv is used outside the loop, and its final value could be calculated, it is put here, and the giv is made replaceable. Set the giv to this value before the loop. */ unsigned replaceable : 1; /* 1 if we can substitute the strength-reduced variable for the original variable. 0 means they must be kept separate and the new one must be copied into the old pseudo reg each time the old one is set. */ unsigned not_replaceable : 1; /* Used to prevent duplicating work. This is 1 if we know that the giv definitely can not be made replaceable, in which case we don't bother checking the variable again even if further info is available. Both this and the above can be zero. */ unsigned ignore : 1; /* 1 prohibits further processing of giv */ unsigned always_computable : 1;/* 1 if this set occurs each iteration */ unsigned maybe_multiple : 1; /* Only used for a biv and 1 if this biv update may be done multiple times per iteration. */ unsigned cant_derive : 1; /* For giv's, 1 if this giv cannot derive another giv. This occurs in many cases where a giv's lifetime spans an update to a biv. */ unsigned combined_with : 1; /* 1 if this giv has been combined with. It then cannot combine with any other giv. */ unsigned maybe_dead : 1; /* 1 if this giv might be dead. In that case, we won't use it to eliminate a biv, it would probably lose. */ int lifetime; /* Length of life of this giv */ int times_used; /* # times this giv is used. */ rtx derive_adjustment; /* If nonzero, is an adjustment to be subtracted from add_val when this giv derives another. This occurs when the giv spans a biv update by incrementation. */ struct induction *next_iv; /* For givs, links together all givs that are based on the same biv. For bivs, links together all biv entries that refer to the same biv register. */ struct induction *same; /* If this giv has been combined with another giv, this points to the base giv. The base giv will have COMBINED_WITH non-zero. */ HOST_WIDE_INT const_adjust; /* Used by loop unrolling, when an address giv is split, and a constant is eliminated from the address, the -constant is stored here for later use. */ }; /* A `struct iv_class' is created for each biv. */ struct iv_class { int regno; /* Pseudo reg which is the biv. */ int biv_count; /* Number of insns setting this reg. */ struct induction *biv; /* List of all insns that set this reg. */ int giv_count; /* Number of DEST_REG givs computed from this biv. The resulting count is only used in check_dbra_loop. */ struct induction *giv; /* List of all insns that compute a giv from this reg. */ int total_benefit; /* Sum of BENEFITs of all those givs */ rtx initial_value; /* Value of reg at loop start */ rtx initial_test; /* Test performed on BIV before loop */ struct iv_class *next; /* Links all class structures together */ rtx init_insn; /* insn which initializes biv, 0 if none. */ rtx init_set; /* SET of INIT_INSN, if any. */ unsigned incremented : 1; /* 1 if somewhere incremented/decremented */ unsigned eliminable : 1; /* 1 if plausible candidate for elimination. */ unsigned nonneg : 1; /* 1 if we added a REG_NONNEG note for this. */ unsigned reversed : 1; /* 1 if we reversed the loop that this biv controls. */ }; /* Definitions used by the basic induction variable discovery code. */ enum iv_mode { UNKNOWN_INDUCT, BASIC_INDUCT, NOT_BASIC_INDUCT, GENERAL_INDUCT }; /* Variables declared in loop.c, but also needed in unroll.c. */ extern int *uid_luid; extern int max_uid_for_loop; extern int *uid_loop_num; extern int *loop_outer_loop; extern rtx *loop_number_exit_labels; extern unsigned HOST_WIDE_INT loop_n_iterations; extern int max_reg_before_loop; extern FILE *loop_dump_stream; extern enum iv_mode *reg_iv_type; extern struct induction **reg_iv_info; extern struct iv_class **reg_biv_class; extern struct iv_class *loop_iv_list; /* Forward declarations for non-static functions declared in loop.c and unroll.c. */ int invariant_p PROTO((rtx)); rtx get_condition_for_loop PROTO((rtx)); void emit_iv_add_mult PROTO((rtx, rtx, rtx, rtx, rtx)); /* Forward declarations for non-static functions declared in stmt.c. */ void find_loop_tree_blocks PROTO((void)); void unroll_block_trees PROTO((void)); void unroll_loop PROTO((rtx, int, rtx, rtx, int)); rtx biv_total_increment PROTO((struct iv_class *, rtx, rtx)); unsigned HOST_WIDE_INT loop_iterations PROTO((rtx, rtx)); rtx final_biv_value PROTO((struct iv_class *, rtx, rtx)); rtx final_giv_value PROTO((struct induction *, rtx, rtx)); void emit_unrolled_add PROTO((rtx, rtx, rtx));
44.452941
77
0.703718
[ "object" ]
bb226d182065e20805bae6d113c3cc8c27403a66
904
h
C
Osiris/Hacks/SkinChanger.h
aljawary/Osiris
a9e00e787de441d666cd90fabd78d997de591557
[ "MIT" ]
7
2020-10-17T15:35:09.000Z
2022-03-16T13:06:37.000Z
Osiris/Hacks/SkinChanger.h
aljawary/Osiris
a9e00e787de441d666cd90fabd78d997de591557
[ "MIT" ]
1
2020-05-09T10:57:22.000Z
2020-05-09T10:57:22.000Z
Osiris/Hacks/SkinChanger.h
aljawary/Osiris
a9e00e787de441d666cd90fabd78d997de591557
[ "MIT" ]
4
2020-05-03T18:14:37.000Z
2021-02-08T15:25:52.000Z
#pragma once #include <string> #include <vector> enum class FrameStage; class GameEvent; namespace SkinChanger { void initializeKits() noexcept; void run(FrameStage) noexcept; void scheduleHudUpdate() noexcept; void overrideHudIcon(GameEvent& event) noexcept; void updateStatTrak(GameEvent& event) noexcept; struct PaintKit { PaintKit(int id, const std::string& name, const std::wstring& nameUpperCase) noexcept : id(id), name(name), nameUpperCase(nameUpperCase) { } int id; std::string name; std::wstring nameUpperCase; auto operator<(const PaintKit& other) const noexcept { return nameUpperCase < other.nameUpperCase; } }; const std::vector<PaintKit>& getSkinKits() noexcept; const std::vector<PaintKit>& getGloveKits() noexcept; const std::vector<PaintKit>& getStickerKits() noexcept; }
27.393939
148
0.682522
[ "vector" ]
bb37eb87f143ad0c8006deaaed9dd94f03c20cf8
43,461
c
C
src/emu/sound/discrete.c
seleuco/MAME4droid_Native
b6adcf8ba8ac602d93d28ec4e6f7346f92c84363
[ "Unlicense" ]
5
2020-09-09T09:24:59.000Z
2022-03-22T04:44:14.000Z
src/emu/sound/discrete.c
seleuco/MAME4droid_Native
b6adcf8ba8ac602d93d28ec4e6f7346f92c84363
[ "Unlicense" ]
null
null
null
src/emu/sound/discrete.c
seleuco/MAME4droid_Native
b6adcf8ba8ac602d93d28ec4e6f7346f92c84363
[ "Unlicense" ]
4
2021-02-04T13:26:39.000Z
2022-03-07T08:51:45.000Z
/************************************************************************ * * MAME - Discrete sound system emulation library * * Written by Keith Wilkins (mame@esplexo.co.uk) * * (c) K.Wilkins 2000 * * Coding started in November 2000 * KW - Added Sawtooth waveforms Feb2003 * *********************************************************************** * * SEE DISCRETE.H for documentation on usage * *********************************************************************** * * Each sound primative DSS_xxxx or DST_xxxx has its own implementation * file. All discrete sound primatives MUST implement the following * API: * * dsX_NAME_step(inputs, context, float timestep) - Perform time step * return output value * dsX_NAME_reset(context) - Reset to initial state * * Core software takes care of traversing the netlist in the correct * order * * DEVICE_START(discrete) - Read Node list, initialise & reset * DEVICE_STOP(discrete) - Shutdown discrete sound system * DEVICE_RESET(discrete) - Put sound system back to time 0 * discrete_stream_update() - This does the real update to the sim * ************************************************************************/ #include "emu.h" #include "streams.h" #include "wavwrite.h" #include "discrete.h" /************************************* * * Performance * *************************************/ /* * Normally, the discrete core processes 960 samples per update. * With the various buffers involved, this on a Core2 is not as * performant as processing 240 samples 4 times. * The setting most probably depends on CPU and which modules are * run and how many tasks are defined. * * Values < 32 exhibit poor performance (too much overhead) while * Values > 500 have a slightly worse performace (too much cache misses?). */ #define MAX_SAMPLES_PER_TASK_SLICE (240) /************************************* * * Debugging * *************************************/ #define DISCRETE_DEBUGLOG (0) /************************************* * * Profiling Nodes * *************************************/ #define DISCRETE_PROFILING (0) /************************************* * * Prototypes * *************************************/ static void init_nodes(discrete_info *info, const linked_list_entry *block_list, running_device *device); static void find_input_nodes(const discrete_info *info); static node_description *discrete_find_node(const discrete_info *info, int node); static DEVICE_RESET( discrete ); static STREAM_UPDATE( discrete_stream_update ); static STREAM_UPDATE( buffer_stream_update ); static int profiling = 0; /************************************* * * Debug logging * *************************************/ static void CLIB_DECL ATTR_PRINTF(2,3) discrete_log(const discrete_info *disc_info, const char *text, ...) { if (DISCRETE_DEBUGLOG) { va_list arg; va_start(arg, text); if(disc_info->disclogfile) { vfprintf(disc_info->disclogfile, text, arg); fprintf(disc_info->disclogfile, "\n"); fflush(disc_info->disclogfile); } va_end(arg); } } /************************************* * * INLINEs * *************************************/ INLINE int node_module_index(const node_description *node) { linked_list_entry *entry; int index = 0; for (entry = node->info->node_list; entry != NULL; entry = entry->next) { node_description *n = (node_description *) entry->ptr; if (n == node) return index; if (n->module->type == node->module->type) index++; } return -1; } INLINE void linked_list_tail_add(const discrete_info *info, linked_list_entry ***list_tail_ptr, const void *ptr) { **list_tail_ptr = auto_alloc(info->device->machine, linked_list_entry); (**list_tail_ptr)->ptr = ptr; (**list_tail_ptr)->next = NULL; *list_tail_ptr = &((**list_tail_ptr)->next); } INLINE int linked_list_count(const linked_list_entry *list) { int cnt = 0; const linked_list_entry *entry; for (entry = list; entry != NULL; entry = entry->next) cnt++; return cnt; } INLINE void linked_list_add(const discrete_info *info, linked_list_entry **list, const void *ptr) { linked_list_entry *entry; if (*list == NULL) { *list = auto_alloc(info->device->machine, linked_list_entry); (*list)->ptr = ptr; (*list)->next = NULL; } else { for (entry = *list; entry != NULL && entry->next != NULL; entry = entry->next) ; entry->next = auto_alloc(info->device->machine, linked_list_entry); entry->next->ptr = ptr; entry->next->next = NULL; } } /************************************* * * Included simulation objects * *************************************/ #include "disc_sys.c" /* discrete core modules and support functions */ #include "disc_wav.c" /* Wave sources - SINE/SQUARE/NOISE/etc */ #include "disc_mth.c" /* Math Devices - ADD/GAIN/etc */ #include "disc_inp.c" /* Input Devices - INPUT/CONST/etc */ #include "disc_flt.c" /* Filter Devices - RCF/HPF/LPF */ #include "disc_dev.c" /* Popular Devices - NE555/etc */ /************************************* * * Master module list * *************************************/ static const discrete_module module_list[] = { { DSO_OUTPUT ,"DSO_OUTPUT" , 0 ,0 ,dso_output_reset ,dso_output_step ,NULL ,NULL }, { DSO_CSVLOG ,"DSO_CSVLOG" , 0 ,sizeof(struct dso_csvlog_context) ,NULL ,dso_csvlog_step ,dso_csvlog_start ,dso_csvlog_stop }, { DSO_WAVELOG ,"DSO_WAVELOG" , 0 ,sizeof(struct dso_wavelog_context) ,NULL ,dso_wavelog_step ,dso_wavelog_start ,dso_wavelog_stop }, { DSO_IMPORT ,"DSO_IMPORT" , 0 ,0 ,NULL ,NULL ,NULL ,NULL }, /* parallel modules */ { DSO_TASK_START ,"DSO_TASK_START" , 0 ,0 ,dso_task_reset ,dso_task_start_step ,dso_task_start_start ,NULL }, { DSO_TASK_END ,"DSO_TASK_END" , 0 ,0 ,dso_task_reset ,dso_task_end_step ,NULL ,NULL }, { DSO_TASK_SYNC ,"DSO_TASK_SYNC" , 0 ,0 ,NULL ,NULL ,NULL ,NULL }, /* nop */ { DSS_NOP ,"DSS_NOP" , 0 ,0 ,NULL ,NULL ,NULL ,NULL }, /* from disc_inp.c */ { DSS_ADJUSTMENT ,"DSS_ADJUSTMENT" , 1 ,sizeof(struct dss_adjustment_context) ,dss_adjustment_reset ,dss_adjustment_step ,NULL ,NULL }, { DSS_CONSTANT ,"DSS_CONSTANT" , 1 ,0 ,dss_constant_reset ,NULL ,NULL ,NULL }, { DSS_INPUT_DATA ,"DSS_INPUT_DATA" , 1 ,sizeof(struct dss_input_context) ,dss_input_reset ,NULL ,NULL ,NULL }, { DSS_INPUT_LOGIC ,"DSS_INPUT_LOGIC" , 1 ,sizeof(struct dss_input_context) ,dss_input_reset ,NULL ,NULL ,NULL }, { DSS_INPUT_NOT ,"DSS_INPUT_NOT" , 1 ,sizeof(struct dss_input_context) ,dss_input_reset ,NULL ,NULL ,NULL }, { DSS_INPUT_PULSE ,"DSS_INPUT_PULSE" , 1 ,sizeof(struct dss_input_context) ,dss_input_reset ,dss_input_pulse_step ,NULL ,NULL }, { DSS_INPUT_STREAM,"DSS_INPUT_STREAM", 1 ,sizeof(struct dss_input_context) ,dss_input_stream_reset,dss_input_stream_step,dss_input_stream_start,NULL }, { DSS_INPUT_BUFFER,"DSS_INPUT_BUFFER", 1 ,sizeof(struct dss_input_context) ,dss_input_stream_reset,dss_input_stream_step,dss_input_stream_start,NULL }, /* from disc_wav.c */ /* Generic modules */ { DSS_COUNTER ,"DSS_COUNTER" , 1 ,sizeof(struct dss_counter_context) ,dss_counter_reset ,dss_counter_step ,NULL ,NULL }, { DSS_LFSR_NOISE ,"DSS_LFSR_NOISE" , 2 ,sizeof(struct dss_lfsr_context) ,dss_lfsr_reset ,dss_lfsr_step ,NULL ,NULL }, { DSS_NOISE ,"DSS_NOISE" , 1 ,sizeof(struct dss_noise_context) ,dss_noise_reset ,dss_noise_step ,NULL ,NULL }, { DSS_NOTE ,"DSS_NOTE" , 1 ,sizeof(struct dss_note_context) ,dss_note_reset ,dss_note_step ,NULL ,NULL }, { DSS_SAWTOOTHWAVE,"DSS_SAWTOOTHWAVE", 1 ,sizeof(struct dss_sawtoothwave_context),dss_sawtoothwave_reset,dss_sawtoothwave_step,NULL ,NULL }, { DSS_SINEWAVE ,"DSS_SINEWAVE" , 1 ,sizeof(struct dss_sinewave_context) ,dss_sinewave_reset ,dss_sinewave_step ,NULL ,NULL }, { DSS_SQUAREWAVE ,"DSS_SQUAREWAVE" , 1 ,sizeof(struct dss_squarewave_context) ,dss_squarewave_reset ,dss_squarewave_step ,NULL ,NULL }, { DSS_SQUAREWFIX ,"DSS_SQUAREWFIX" , 1 ,sizeof(struct dss_squarewfix_context) ,dss_squarewfix_reset ,dss_squarewfix_step ,NULL ,NULL }, { DSS_SQUAREWAVE2 ,"DSS_SQUAREWAVE2" , 1 ,sizeof(struct dss_squarewave_context) ,dss_squarewave2_reset ,dss_squarewave2_step ,NULL ,NULL }, { DSS_TRIANGLEWAVE,"DSS_TRIANGLEWAVE", 1 ,sizeof(struct dss_trianglewave_context),dss_trianglewave_reset,dss_trianglewave_step,NULL ,NULL }, /* Component specific modules */ { DSS_INVERTER_OSC ,"DSS_INVERTER_OSC" , 1 ,sizeof(struct dss_inverter_osc_context) ,dss_inverter_osc_reset ,dss_inverter_osc_step ,NULL ,NULL }, { DSS_OP_AMP_OSC ,"DSS_OP_AMP_OSC" , 1 ,sizeof(struct dss_op_amp_osc_context) ,dss_op_amp_osc_reset ,dss_op_amp_osc_step ,NULL ,NULL }, { DSS_SCHMITT_OSC ,"DSS_SCHMITT_OSC" , 1 ,sizeof(struct dss_schmitt_osc_context) ,dss_schmitt_osc_reset ,dss_schmitt_osc_step ,NULL ,NULL }, /* Not yet implemented */ { DSS_ADSR ,"DSS_ADSR" , 1 ,sizeof(struct dss_adsr_context) ,dss_adsrenv_reset ,dss_adsrenv_step ,NULL ,NULL }, /* from disc_mth.c */ /* Generic modules */ { DST_ADDER ,"DST_ADDER" , 1 ,0 ,NULL ,dst_adder_step ,NULL ,NULL }, { DST_CLAMP ,"DST_CLAMP" , 1 ,0 ,NULL ,dst_clamp_step ,NULL ,NULL }, { DST_DIVIDE ,"DST_DIVIDE" , 1 ,0 ,NULL ,dst_divide_step ,NULL ,NULL }, { DST_GAIN ,"DST_GAIN" , 1 ,0 ,NULL ,dst_gain_step ,NULL ,NULL }, { DST_LOGIC_INV ,"DST_LOGIC_INV" , 1 ,0 ,NULL ,dst_logic_inv_step ,NULL ,NULL }, { DST_BITS_DECODE ,"DST_BITS_DECODE" , 8 ,sizeof(struct dst_bits_decode_context) ,dst_bits_decode_reset ,dst_bits_decode_step ,NULL ,NULL }, { DST_LOGIC_AND ,"DST_LOGIC_AND" , 1 ,0 ,NULL ,dst_logic_and_step ,NULL ,NULL }, { DST_LOGIC_NAND ,"DST_LOGIC_NAND" , 1 ,0 ,NULL ,dst_logic_nand_step ,NULL ,NULL }, { DST_LOGIC_OR ,"DST_LOGIC_OR" , 1 ,0 ,NULL ,dst_logic_or_step ,NULL ,NULL }, { DST_LOGIC_NOR ,"DST_LOGIC_NOR" , 1 ,0 ,NULL ,dst_logic_nor_step ,NULL ,NULL }, { DST_LOGIC_XOR ,"DST_LOGIC_XOR" , 1 ,0 ,NULL ,dst_logic_xor_step ,NULL ,NULL }, { DST_LOGIC_NXOR ,"DST_LOGIC_NXOR" , 1 ,0 ,NULL ,dst_logic_nxor_step ,NULL ,NULL }, { DST_LOGIC_DFF ,"DST_LOGIC_DFF" , 1 ,sizeof(struct dst_flipflop_context) ,dst_logic_ff_reset ,dst_logic_dff_step ,NULL ,NULL }, { DST_LOGIC_JKFF ,"DST_LOGIC_JKFF" , 1 ,sizeof(struct dst_flipflop_context) ,dst_logic_ff_reset ,dst_logic_jkff_step ,NULL ,NULL }, { DST_LOGIC_SHIFT ,"DST_LOGIC_SHIFT" , 1 ,sizeof(struct dst_shift_context) ,dst_logic_shift_reset ,dst_logic_shift_step ,NULL ,NULL }, { DST_LOOKUP_TABLE,"DST_LOOKUP_TABLE", 1 ,0 ,NULL ,dst_lookup_table_step,NULL ,NULL }, { DST_MULTIPLEX ,"DST_MULTIPLEX" , 1 ,sizeof(struct dst_size_context) ,dst_multiplex_reset ,dst_multiplex_step ,NULL ,NULL }, { DST_ONESHOT ,"DST_ONESHOT" , 1 ,sizeof(struct dst_oneshot_context) ,dst_oneshot_reset ,dst_oneshot_step ,NULL ,NULL }, { DST_RAMP ,"DST_RAMP" , 1 ,sizeof(struct dss_ramp_context) ,dst_ramp_reset ,dst_ramp_step ,NULL ,NULL }, { DST_SAMPHOLD ,"DST_SAMPHOLD" , 1 ,sizeof(struct dst_samphold_context) ,dst_samphold_reset ,dst_samphold_step ,NULL ,NULL }, { DST_SWITCH ,"DST_SWITCH" , 1 ,0 ,NULL ,dst_switch_step ,NULL ,NULL }, { DST_ASWITCH ,"DST_ASWITCH" , 1 ,0 ,NULL ,dst_aswitch_step ,NULL ,NULL }, { DST_TRANSFORM ,"DST_TRANSFORM" , 1 ,0 ,NULL ,dst_transform_step ,NULL ,NULL }, /* Component specific */ { DST_COMP_ADDER ,"DST_COMP_ADDER" , 1 ,sizeof(struct dst_comp_adder_context) ,dst_comp_adder_reset ,dst_comp_adder_step ,NULL ,NULL }, { DST_DAC_R1 ,"DST_DAC_R1" , 1 ,sizeof(struct dst_dac_r1_context) ,dst_dac_r1_reset ,dst_dac_r1_step ,NULL ,NULL }, { DST_DIODE_MIX ,"DST_DIODE_MIX" , 1 ,sizeof(struct dst_diode_mix__context) ,dst_diode_mix_reset ,dst_diode_mix_step ,NULL ,NULL }, { DST_INTEGRATE ,"DST_INTEGRATE" , 1 ,sizeof(struct dst_integrate_context) ,dst_integrate_reset ,dst_integrate_step ,NULL ,NULL }, { DST_MIXER ,"DST_MIXER" , 1 ,sizeof(struct dst_mixer_context) ,dst_mixer_reset ,dst_mixer_step ,NULL ,NULL }, { DST_OP_AMP ,"DST_OP_AMP" , 1 ,sizeof(struct dst_op_amp_context) ,dst_op_amp_reset ,dst_op_amp_step ,NULL ,NULL }, { DST_OP_AMP_1SHT ,"DST_OP_AMP_1SHT" , 1 ,sizeof(struct dst_op_amp_1sht_context) ,dst_op_amp_1sht_reset ,dst_op_amp_1sht_step ,NULL ,NULL }, { DST_TVCA_OP_AMP ,"DST_TVCA_OP_AMP" , 1 ,sizeof(struct dst_tvca_op_amp_context) ,dst_tvca_op_amp_reset ,dst_tvca_op_amp_step ,NULL ,NULL }, { DST_VCA ,"DST_VCA" , 1 ,0 ,NULL ,NULL ,NULL ,NULL }, /* from disc_flt.c */ /* Generic modules */ { DST_FILTER1 ,"DST_FILTER1" , 1 ,sizeof(struct dss_filter1_context) ,dst_filter1_reset ,dst_filter1_step ,NULL ,NULL }, { DST_FILTER2 ,"DST_FILTER2" , 1 ,sizeof(struct dss_filter2_context) ,dst_filter2_reset ,dst_filter2_step ,NULL ,NULL }, /* Component specific modules */ { DST_SALLEN_KEY ,"DST_SALLEN_KEY" , 1 ,sizeof(struct dss_filter2_context) ,dst_sallen_key_reset ,dst_sallen_key_step ,NULL ,NULL }, { DST_CRFILTER ,"DST_CRFILTER" , 1 ,sizeof(struct dst_rcfilter_context) ,dst_crfilter_reset ,dst_crfilter_step ,NULL ,NULL }, { DST_OP_AMP_FILT ,"DST_OP_AMP_FILT" , 1 ,sizeof(struct dst_op_amp_filt_context) ,dst_op_amp_filt_reset ,dst_op_amp_filt_step ,NULL ,NULL }, { DST_RC_CIRCUIT_1,"DST_RC_CIRCUIT_1", 1 ,sizeof(struct dst_rc_circuit_1_context),dst_rc_circuit_1_reset,dst_rc_circuit_1_step,NULL ,NULL }, { DST_RCDISC ,"DST_RCDISC" , 1 ,sizeof(struct dst_rcdisc_context) ,dst_rcdisc_reset ,dst_rcdisc_step ,NULL ,NULL }, { DST_RCDISC2 ,"DST_RCDISC2" , 1 ,sizeof(struct dst_rcdisc_context) ,dst_rcdisc2_reset ,dst_rcdisc2_step ,NULL ,NULL }, { DST_RCDISC3 ,"DST_RCDISC3" , 1 ,sizeof(struct dst_rcdisc_context) ,dst_rcdisc3_reset ,dst_rcdisc3_step ,NULL ,NULL }, { DST_RCDISC4 ,"DST_RCDISC4" , 1 ,sizeof(struct dst_rcdisc4_context) ,dst_rcdisc4_reset ,dst_rcdisc4_step ,NULL ,NULL }, { DST_RCDISC5 ,"DST_RCDISC5" , 1 ,sizeof(struct dst_rcdisc_context) ,dst_rcdisc5_reset ,dst_rcdisc5_step ,NULL ,NULL }, { DST_RCINTEGRATE ,"DST_RCINTEGRATE" , 1 ,sizeof(struct dst_rcintegrate_context) ,dst_rcintegrate_reset ,dst_rcintegrate_step ,NULL ,NULL }, { DST_RCDISC_MOD ,"DST_RCDISC_MOD" , 1 ,sizeof(struct dst_rcdisc_mod_context) ,dst_rcdisc_mod_reset ,dst_rcdisc_mod_step ,NULL ,NULL }, { DST_RCFILTER ,"DST_RCFILTER" , 1 ,sizeof(struct dst_rcfilter_context) ,dst_rcfilter_reset ,dst_rcfilter_step ,NULL ,NULL }, { DST_RCFILTER_SW ,"DST_RCFILTER_SW" , 1 ,sizeof(struct dst_rcfilter_sw_context) ,dst_rcfilter_sw_reset ,dst_rcfilter_sw_step ,NULL ,NULL }, /* For testing - seem to be buggered. Use versions not ending in N. */ { DST_RCFILTERN ,"DST_RCFILTERN" , 1 ,sizeof(struct dss_filter1_context) ,dst_rcfilterN_reset ,dst_filter1_step ,NULL ,NULL }, { DST_RCDISCN ,"DST_RCDISCN" , 1 ,sizeof(struct dss_filter1_context) ,dst_rcdiscN_reset ,dst_rcdiscN_step ,NULL ,NULL }, { DST_RCDISC2N ,"DST_RCDISC2N" , 1 ,sizeof(struct dss_rcdisc2_context) ,dst_rcdisc2N_reset ,dst_rcdisc2N_step ,NULL ,NULL }, /* from disc_dev.c */ /* generic modules */ { DST_CUSTOM ,"DST_CUSTOM" , 1 ,0 ,NULL ,NULL ,NULL ,NULL }, /* Component specific modules */ { DSD_555_ASTBL ,"DSD_555_ASTBL" , 1 ,sizeof(struct dsd_555_astbl_context) ,dsd_555_astbl_reset ,dsd_555_astbl_step ,NULL ,NULL }, { DSD_555_MSTBL ,"DSD_555_MSTBL" , 1 ,sizeof(struct dsd_555_mstbl_context) ,dsd_555_mstbl_reset ,dsd_555_mstbl_step ,NULL ,NULL }, { DSD_555_CC ,"DSD_555_CC" , 1 ,sizeof(struct dsd_555_cc_context) ,dsd_555_cc_reset ,dsd_555_cc_step ,NULL ,NULL }, { DSD_555_VCO1 ,"DSD_555_VCO1" , 1 ,sizeof(struct dsd_555_vco1_context) ,dsd_555_vco1_reset ,dsd_555_vco1_step ,NULL ,NULL }, { DSD_566 ,"DSD_566" , 1 ,sizeof(struct dsd_566_context) ,dsd_566_reset ,dsd_566_step ,NULL ,NULL }, { DSD_LS624 ,"DSD_LS624" , 1 ,sizeof(struct dsd_ls624_context) ,dsd_ls624_reset ,dsd_ls624_step ,NULL ,NULL }, { DSD_LS629 ,"DSD_LS629" , 1 ,sizeof(struct dsd_ls629_context) ,dsd_ls629_reset ,dsd_ls629_step ,NULL ,NULL }, /* must be the last one */ { DSS_NULL ,"DSS_NULL" , 0 ,0 ,NULL ,NULL ,NULL ,NULL } }; INLINE void step_nodes_in_list(const linked_list_entry *list) { const linked_list_entry *entry; if (EXPECTED(!profiling)) { for (entry = list; entry != NULL; entry = entry->next) { node_description *node = (node_description *) entry->ptr; /* Now step the node */ (*node->step)(node); } } else { osd_ticks_t last = get_profile_ticks(); for (entry = list; entry != NULL; entry = entry->next) { node_description *node = (node_description *) entry->ptr; node->run_time -= last; (*node->step)(node); last = get_profile_ticks(); node->run_time += last; } } } /************************************* * * Find a given node * *************************************/ static node_description *discrete_find_node(const discrete_info *info, int node) { if (node < NODE_START || node > NODE_END) return NULL; return info->indexed_node[NODE_INDEX(node)]; } /************************************* * * Build import list * *************************************/ static void discrete_build_list(discrete_info *info, const discrete_sound_block *intf, linked_list_entry ***current) { int node_count = 0; for (; intf[node_count].type != DSS_NULL; ) { /* scan imported */ if (intf[node_count].type == DSO_IMPORT) { discrete_log(info, "discrete_build_list() - DISCRETE_IMPORT @ NODE_%02d", NODE_INDEX(intf[node_count].node) ); discrete_build_list(info, (discrete_sound_block *) intf[node_count].custom, current); } else if (intf[node_count].type == DSO_REPLACE) { linked_list_entry *entry; node_count++; if (intf[node_count].type == DSS_NULL) fatalerror("discrete_build_list: DISCRETE_REPLACE at end of node_list"); for (entry = info->block_list; entry != NULL; entry = entry->next) { discrete_sound_block *block = (discrete_sound_block *) entry->ptr; if (block->type != NODE_SPECIAL ) if (block->node == intf[node_count].node) { entry->ptr = (void *) &intf[node_count]; discrete_log(info, "discrete_build_list() - DISCRETE_REPLACE @ NODE_%02d", NODE_INDEX(intf[node_count].node) ); break; } } if (entry == NULL) fatalerror("discrete_build_list: DISCRETE_REPLACE did not found node %d", NODE_INDEX(intf[node_count].node)); } else if (intf[node_count].type == DSO_DELETE) { linked_list_entry *entry, *last; last = NULL; for (entry = info->block_list; entry != NULL; last = entry, entry = entry->next) { discrete_sound_block *block = (discrete_sound_block *) entry->ptr; if ((block->node >= intf[node_count].input_node[0]) && (block->node <= intf[node_count].input_node[1])) { discrete_log(info, "discrete_build_list() - DISCRETE_DELETE deleted NODE_%02d", NODE_INDEX(block->node) ); if (last != NULL) last->next = entry->next; else info->block_list = entry->next; } } } else { discrete_log(info, "discrete_build_list() - adding node %d (*current %p)\n", node_count, *current); linked_list_tail_add(info, current, &intf[node_count]); } node_count++; } } /************************************* * * Sanity check list * *************************************/ static void discrete_sanity_check(const discrete_info *info) { const linked_list_entry *entry; int node_count = 0; discrete_log(info, "discrete_start() - Doing node list sanity check"); for (entry = info->block_list; entry != NULL; entry = entry->next) { discrete_sound_block *block = (discrete_sound_block *) entry->ptr; /* make sure we don't have too many nodes overall */ if (node_count > DISCRETE_MAX_NODES) fatalerror("discrete_start() - Upper limit of %d nodes exceeded, have you terminated the interface block?", DISCRETE_MAX_NODES); /* make sure the node number is in range */ if (block->node < NODE_START || block->node > NODE_END) fatalerror("discrete_start() - Invalid node number on node %02d descriptor", block->node); /* make sure the node type is valid */ if (block->type > DSO_OUTPUT) fatalerror("discrete_start() - Invalid function type on NODE_%02d", NODE_INDEX(block->node) ); /* make sure this is a main node */ if (NODE_CHILD_NODE_NUM(block->node) > 0) fatalerror("discrete_start() - Child node number on NODE_%02d", NODE_INDEX(block->node) ); node_count++; } discrete_log(info, "discrete_start() - Sanity check counted %d nodes", node_count); } /************************************* * * Master discrete system start * *************************************/ static DEVICE_START( discrete ) { linked_list_entry **intf; const linked_list_entry *entry; const discrete_sound_block *intf_start = (discrete_sound_block *)device->baseconfig().static_config(); discrete_info *info = get_safe_token(device); char name[32]; info->device = device; /* If a clock is specified we will use it, otherwise run at the audio sample rate. */ if (device->clock()) info->sample_rate = device->clock(); else info->sample_rate = device->machine->sample_rate; info->sample_time = 1.0 / info->sample_rate; info->neg_sample_time = - info->sample_time; info->total_samples = 0; info->total_stream_updates = 0; /* create the logfile */ sprintf(name, "discrete%s.log", device->tag()); if (DISCRETE_DEBUGLOG) info->disclogfile = fopen(name, "w"); /* enable profiling */ if (getenv("DISCRETE_PROFILING")) profiling = atoi(getenv("DISCRETE_PROFILING")); /* Build the final block list */ info->block_list = NULL; intf = &info->block_list; discrete_build_list(info, intf_start, &intf); /* first pass through the nodes: sanity check, fill in the indexed_nodes, and make a total count */ discrete_sanity_check(info); /* Start with empty lists */ info->node_list = NULL; info->output_list = NULL; info->input_list = NULL; /* allocate memory to hold pointers to nodes by index */ info->indexed_node = auto_alloc_array_clear(device->machine, node_description *, DISCRETE_MAX_NODES); /* initialize the node data */ init_nodes(info, info->block_list, device); /* now go back and find pointers to all input nodes */ find_input_nodes(info); /* initialize the stream(s) */ info->discrete_stream = stream_create(device,linked_list_count(info->input_list), linked_list_count(info->output_list), info->sample_rate, info, discrete_stream_update); /* allocate a queue */ info->queue = osd_work_queue_alloc(WORK_QUEUE_FLAG_MULTI | WORK_QUEUE_FLAG_HIGH_FREQ); /* Process nodes which have a start func */ for (entry = info->node_list; entry != NULL; entry = entry->next) { node_description *node = (node_description *) entry->ptr; if (node->module->start) (*node->module->start)(node); } } /************************************* * * Master discrete system stop * *************************************/ static UINT64 list_run_time(const linked_list_entry *list) { const linked_list_entry *entry; UINT64 total = 0; for (entry = list; entry != NULL; entry = entry->next) { node_description *node = (node_description *) entry->ptr; total += node->run_time; } return total; } static void display_profiling(const discrete_info *info) { int count; UINT64 total; UINT64 tresh; double tt; linked_list_entry *entry; /* calculate total time */ total = list_run_time(info->node_list); count = linked_list_count(info->node_list); /* print statistics */ printf("Total Samples : %16" I64FMT "d\n", info->total_samples); tresh = total / count; printf("Threshold (mean): %16" I64FMT "d\n", tresh / info->total_samples ); for (entry = info->node_list; entry != NULL; entry = entry->next) { node_description *node = (node_description *) entry->ptr; if (node->run_time > tresh) printf("%3d: %20s %8.2f %10.2f\n", NODE_BLOCKINDEX(node), node->module->name, (float) node->run_time / (float) total * 100.0, ((float) node->run_time) / (float) info->total_samples); } /* Task information */ for (entry = info->task_list; entry != 0; entry = entry->next) { discrete_task *task = (discrete_task *) entry->ptr; tt = list_run_time(task->list); printf("Task(%d): %8.2f %15.2f\n", task->task_group, tt / (double) total * 100.0, tt / (double) info->total_samples); } printf("Average samples/stream_update: %8.2f\n", (double) info->total_samples / (double) info->total_stream_updates); } static DEVICE_STOP( discrete ) { discrete_info *info = get_safe_token(device); const linked_list_entry *entry; osd_work_queue_free(info->queue); if (profiling) { display_profiling(info); } /* Process nodes which have a stop func */ for (entry = info->node_list; entry != NULL; entry = entry->next) { node_description *node = (node_description *) entry->ptr; if (node->module->stop) (*node->module->stop)(node); } if (DISCRETE_DEBUGLOG) { /* close the debug log */ if (info->disclogfile) fclose(info->disclogfile); info->disclogfile = NULL; } } /************************************* * * Master reset of all nodes * *************************************/ static DEVICE_RESET( discrete ) { const discrete_info *info = get_safe_token(device); const linked_list_entry *entry; /* loop over all nodes */ for (entry = info->node_list; entry != 0; entry = entry->next) { node_description *node = (node_description *) entry->ptr; node->output[0] = 0; /* if the node has a reset function, call it */ if (node->module->reset) (*node->module->reset)(node); /* otherwise, just step it */ else if (node->step) (*node->step)(node); } } /************************************* * * Stream update functions * *************************************/ static void *task_callback(void *param, int threadid) { const linked_list_entry *list = (linked_list_entry *) param; const linked_list_entry *entry; int samples; do { for (entry = list; entry != 0; entry = entry->next) { discrete_task *task = (discrete_task *) entry->ptr; INT32 prev_id; /* try to lock */ prev_id = compare_exchange32(&task->threadid, -1, threadid); if (prev_id == -1 && task->threadid == threadid) { linked_list_entry *src_entry; samples = MIN(task->samples, MAX_SAMPLES_PER_TASK_SLICE); /* check dependencies */ for (src_entry = task->source_list; src_entry != NULL; src_entry = src_entry->next) { discrete_source_node *sn = (discrete_source_node *) src_entry->ptr; int avail; avail = sn->task->ptr[sn->output_node] - sn->ptr; assert_always(avail >= 0, "task_callback: available samples are negative"); if (avail < samples) samples = avail; } task->samples -= samples; assert_always(task->samples >=0, "task_callback: task_samples got negative"); while (samples > 0) { /* step */ step_nodes_in_list(task->list); samples--; } if (task->samples == 0) { return NULL; } task->threadid = -1; } } } while (1); return NULL; } static STREAM_UPDATE( buffer_stream_update ) { const node_description *node = (node_description *) param; const struct dss_input_context *context = (struct dss_input_context *)node->context; stream_sample_t *ptr = outputs[0]; int data = context->data; int samplenum = samples; while (samplenum-- > 0) *(ptr++) = data; } static STREAM_UPDATE( discrete_stream_update ) { discrete_info *info = (discrete_info *)param; const linked_list_entry *entry; int outputnum; //, task_group; if (samples == 0) return; /* Setup any output streams */ for (entry = info->output_list, outputnum = 0; entry != NULL; entry = entry->next, outputnum++) { ((node_description *) entry->ptr)->context = (void *) outputs[outputnum]; } /* Setup any input streams */ for (entry = info->input_list; entry != NULL; entry = entry->next) { struct dss_input_context *context = (struct dss_input_context *) ((node_description *) entry->ptr)->context; context->ptr = (stream_sample_t *) inputs[context->stream_in_number]; } /* Setup tasks */ for (entry = info->task_list; entry != 0; entry = entry->next) { discrete_task *task = (discrete_task *) entry->ptr; linked_list_entry *src_entry; int i; task->samples = samples; task->threadid = -1; /* set up task buffers */ for (i = 0; i < task->numbuffered; i++) task->ptr[i] = task->node_buf[i]; /* initialize sources */ for (src_entry = task->source_list; src_entry != 0; src_entry = src_entry->next) { discrete_source_node *sn = (discrete_source_node *) src_entry->ptr; sn->ptr = sn->task->node_buf[sn->output_node]; } } for (entry = info->task_list; entry != 0; entry = entry->next) { /* Fire a work item for each task */ osd_work_item_queue(info->queue, task_callback, (void *) info->task_list, WORK_ITEM_FLAG_AUTO_RELEASE); } osd_work_queue_wait(info->queue, osd_ticks_per_second()*10); if (profiling) { info->total_samples += samples; info->total_stream_updates++; } } /************************************* * * First pass init of nodes * *************************************/ static void init_nodes(discrete_info *info, const linked_list_entry *block_list, running_device *device) { const linked_list_entry *entry; linked_list_entry *task_node_list = NULL; discrete_task *task = NULL; /* list tail pointers */ linked_list_entry **task_node_list_ptr = NULL; linked_list_entry **node_list_ptr = &info->node_list; linked_list_entry **task_list_ptr = &info->task_list; linked_list_entry **output_list_ptr = &info->output_list; linked_list_entry **input_list_ptr = &info->input_list; int has_tasks = 0; /* check whether we have tasks ... */ for (entry = block_list; entry != NULL; entry = entry->next) { const discrete_sound_block *block = (discrete_sound_block *) entry->ptr; if (block->type == DSO_TASK_START) has_tasks = 1; } if (!has_tasks) { /* set up a main task */ task_node_list = NULL; task_node_list_ptr = &task_node_list; } /* loop over all nodes */ for (entry = block_list; entry != NULL; entry = entry->next) { const discrete_sound_block *block = (discrete_sound_block *) entry->ptr; node_description *node = auto_alloc_clear(info->device->machine, node_description); int modulenum; /* find the requested module */ for (modulenum = 0; module_list[modulenum].type != DSS_NULL; modulenum++) if (module_list[modulenum].type == block->type) break; if (module_list[modulenum].type != block->type) fatalerror("init_nodes() - Unable to find discrete module type %d for NODE_%02d", block->type, NODE_INDEX(block->node)); /* static inits */ node->context = NULL; node->info = info; node->module = &module_list[modulenum]; node->output[0] = 0.0; node->block = block; node->custom = block->custom; node->active_inputs = block->active_inputs; node->run_time = 0; /* setup module if custom */ if (block->type == DST_CUSTOM) { const discrete_custom_info *custom = (const discrete_custom_info *)node->custom; node->module = &custom->module; node->custom = custom->custom; } /* copy initial / default step function */ node->step = node->module->step; /* allocate memory if necessary */ if (node->module->contextsize) node->context = auto_alloc_array_clear(device->machine, UINT8, node->module->contextsize); /* keep track of special nodes */ if (block->node == NODE_SPECIAL) { switch(block->type) { /* Output Node */ case DSO_OUTPUT: linked_list_tail_add(info, &output_list_ptr, node); break; /* CSVlog Node for debugging */ case DSO_CSVLOG: break; /* Wavelog Node for debugging */ case DSO_WAVELOG: break; /* Task processing */ case DSO_TASK_START: if (task_node_list_ptr != NULL) fatalerror("init_nodes() - Nested DISCRETE_START_TASK."); task = auto_alloc_clear(info->device->machine, discrete_task); node->context = task; task_node_list = NULL; task_node_list_ptr = &task_node_list; break; case DSO_TASK_END: if (task_node_list_ptr == NULL) fatalerror("init_nodes() - NO DISCRETE_START_TASK."); task->numbuffered = 0; task->list = task_node_list; task->task_group = -1; /* will be set later */ task->source_list = NULL; linked_list_tail_add(info, &task_list_ptr, task); node->context = task; task = NULL; task_node_list = NULL; break; default: fatalerror("init_nodes() - Failed, trying to create unknown special discrete node."); } } /* otherwise, make sure we are not a duplicate, and put ourselves into the indexed list */ else { if (info->indexed_node[NODE_INDEX(block->node)]) fatalerror("init_nodes() - Duplicate entries for NODE_%02d", NODE_INDEX(block->node)); info->indexed_node[NODE_INDEX(block->node)] = node; } /* if we are an stream input node, track that */ if (block->type == DSS_INPUT_STREAM) { linked_list_tail_add(info, &input_list_ptr, node); } else if (block->type == DSS_INPUT_BUFFER) { linked_list_tail_add(info, &input_list_ptr, node); } /* add to node list */ linked_list_tail_add(info, &node_list_ptr, node); /* our running order just follows the order specified */ /* does the node step ? */ if (node->step != NULL) { /* do we belong to a task? */ if (task_node_list_ptr == NULL) fatalerror("init_nodes() - found node outside of task."); else linked_list_tail_add(info, &task_node_list_ptr, node); } if (block->type == DSO_TASK_END) { task_node_list_ptr = NULL; } /* and register save state */ if (node->block->node != NODE_SPECIAL) state_save_register_device_item_array(device, node->block->node, node->output); } if (!has_tasks) { /* make sure we have one simple task * No need to create a node since there are no dependencies. */ task = auto_alloc_clear(info->device->machine, discrete_task); task->numbuffered = 0; task->list = task_node_list; task->task_group = 0; task->source_list = NULL; linked_list_tail_add(info, &task_list_ptr, task); } /* if no outputs, give an error */ if (linked_list_count(info->output_list) == 0) fatalerror("init_nodes() - Couldn't find an output node"); } /************************************* * * Find and attach all input nodes * *************************************/ /* attempt to group all static node parameters together. * Has a negative impact on performance - but it should * reduce memory bandwidth - this is weird. */ #if 0 static double dbuf[10240] = { 0.0, 1.0 }; static int dbufptr = 2; static double *getDoublePtr(double val) { int i; for (i=0; i<dbufptr; i+=1) { if (dbuf[i] == val) { return &dbuf[i]; } } dbuf[dbufptr] = val; dbufptr+=1; return &dbuf[dbufptr-1]; } #endif static void find_input_nodes(const discrete_info *info) { const linked_list_entry *entry; int inputnum; /* loop over all nodes */ for (entry = info->node_list; entry != NULL; entry = entry->next) { node_description *node = (node_description *) entry->ptr; const discrete_sound_block *block = node->block; /* loop over all active inputs */ for (inputnum = 0; inputnum < node->active_inputs; inputnum++) { int inputnode = block->input_node[inputnum]; /* if this input is node-based, find the node in the indexed list */ if IS_VALUE_A_NODE(inputnode) { const node_description *node_ref = info->indexed_node[NODE_INDEX(inputnode)]; if (!node_ref) fatalerror("discrete_start - NODE_%02d referenced a non existent node NODE_%02d", NODE_BLOCKINDEX(node), NODE_INDEX(inputnode)); if (NODE_CHILD_NODE_NUM(inputnode) >= node_ref->module->num_output) fatalerror("discrete_start - NODE_%02d referenced non existent output %d on node NODE_%02d", NODE_BLOCKINDEX(node), NODE_CHILD_NODE_NUM(inputnode), NODE_INDEX(inputnode)); node->input[inputnum] = &(node_ref->output[NODE_CHILD_NODE_NUM(inputnode)]); /* Link referenced node out to input */ node->input_is_node |= 1 << inputnum; /* Bit flag if input is node */ } else { /* warn if trying to use a node for an input that can only be static */ if IS_VALUE_A_NODE(block->initial[inputnum]) { discrete_log(info, "Warning - discrete_start - NODE_%02d trying to use a node on static input %d", NODE_BLOCKINDEX(node), inputnum); /* also report it in the error log so it is not missed */ logerror("Warning - discrete_start - NODE_%02d trying to use a node on static input %d", NODE_BLOCKINDEX(node), inputnum); } else { node->input[inputnum] = &(node->block->initial[inputnum]); //node->input[inputnum] = getDoublePtr(node->block->initial[inputnum]); } } } for (inputnum = node->active_inputs; inputnum < DISCRETE_MAX_INPUTS; inputnum++) { /* FIXME: Check that no nodes follow ! */ node->input[inputnum] = &(block->initial[inputnum]); } } } /************************************************************************** * Generic get_info **************************************************************************/ DEVICE_GET_INFO( discrete ) { switch (state) { /* --- the following bits of info are returned as 64-bit signed integers --- */ case DEVINFO_INT_TOKEN_BYTES: info->i = sizeof(discrete_info); break; /* --- the following bits of info are returned as pointers to data or functions --- */ case DEVINFO_FCT_START: info->start = DEVICE_START_NAME( discrete ); break; case DEVINFO_FCT_STOP: info->stop = DEVICE_STOP_NAME( discrete ); break; case DEVINFO_FCT_RESET: info->reset = DEVICE_RESET_NAME( discrete ); break; /* --- the following bits of info are returned as NULL-terminated strings --- */ case DEVINFO_STR_NAME: strcpy(info->s, "Discrete"); break; case DEVINFO_STR_FAMILY: strcpy(info->s, "Analog"); break; case DEVINFO_STR_VERSION: strcpy(info->s, "1.1"); break; case DEVINFO_STR_SOURCE_FILE: strcpy(info->s, __FILE__); break; case DEVINFO_STR_CREDITS: strcpy(info->s, "Copyright Nicola Salmoria and the MAME Team"); break; } } DEFINE_LEGACY_SOUND_DEVICE(DISCRETE, discrete);
39.799451
185
0.587009
[ "3d" ]
bb3ac02a310f164948078be06ae403ebb9be59c8
160,177
h
C
coast/regex/Test/config/LargeLiteralData.h
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/regex/Test/config/LargeLiteralData.h
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/regex/Test/config/LargeLiteralData.h
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
"\\input texinfo @c -*-texinfo-*-" "@c %**start of header" "@setfilename rx.info" "@settitle Rx" "@setchapternewpage odd" "@c %**end of header" "" "@c This title page illustrates only one of the" "@c two methods of forming a title page." "" "@titlepage" "@title Rx" "@author Tom Lord" "" "@center except the chapter \"Posix Entry Points\" " "@center from @emph{The GNU C Library} reference manual" "@center by Sandra Loosemore" "@center with" "@center Richard M. Stallman, Roland McGrath, and Andrew Oram" "" "@c The following two commands" "@c start the copyright page." "@page" "@vskip 0pt plus 1filll" "Copyright @copyright{} 1995 Cygnus Support" "" "except the chapter \"Posix Entry Points\" which is:" "" "Copyright @copyright{} 1995 Free Software Foundation, Inc." "" "Permission is granted to make and distribute verbatim copies of" "this manual provided the copyright notice and this permission notice" "are preserved on all copies." "" "Permission is granted to copy and distribute modified versions of this" "manual under the conditions for verbatim copying, provided that the entire" "resulting derived work is distributed under the terms of a permission" "notice identical to this one." "" "Permission is granted to copy and distribute translations of this manual" "into another language, under the above conditions for modified versions," "except that this permission notice may be stated in a translation approved" "by the author." "" "@end titlepage" "" "@node Top, Copying, (dir), (dir)" "@top Rx" "" "This document describes Rx." "" "@menu" "* Copying:: Sharing is good." "* Overview:: Fnord" "* Posix Basic Regular Expressions:: A popular regexp syntax." "* Posix Entry Points:: The POSIX way to regexp." "* Beyond POSIX:: Hints about cool features." "* Rx Theory:: Hints about how it works." "@end menu" "" "@node Copying, Overview, Top, Top" "@chapter Copying" "" "@center Copyright (C) 1996" "@center Tom Lord" "@center Berkeley, CA USA" "" "@center except portions of \"POSIX Regex Functions\" which are" "@center Copyright (C) 1995" "@center Free Software Foundation, Inc." "" "@noindent" "Permission to use, copy, modify, distribute, and sell this software and" "its documentation for any purpose is hereby granted without fee," "provided that the above copyright notice appear in all copies and that" "both that copyright notice and this permission notice appear in" "supporting documentation." "" "@center NO WARRANTY" "" "@noindent" "BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR" "THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN" "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES" "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER" "EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED" "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE" "ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH" "YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL" "NECESSARY SERVICING, REPAIR OR CORRECTION." "" "@noindent" "IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING" "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR" "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR" "DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL" "DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM" "(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED" "INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF" "THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR" "OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES." "" "@node Overview, Posix Basic Regular Expressions, Copying, Top" "@chapter Overview" "" "Nothing to say here, yet." "" "@node Posix Basic Regular Expressions, Posix Entry Points, Overview, Top" "@chapter Posix Basic Regular Expressions" "" "The Posix Basic Regular Expression language is a notation for describing" "textual patterns. Regexps are typically used by comparing them to a" "string to see if that string matches the pattern, or by searching within" "a string for a substring that matches." "" "This chapter introduces the Posix regexp notation. This is not a formal" "or precise definition of Posix regexps -- it is an intuitive and" "hopefully expository description of them." "" "@menu" "* An Introduction to Regexps:: " "* Literal Regexps:: " "* Character Sets:: " "* Subexpressions:: " "* Repeated Subexpressions:: " "* Optional Subexpressions:: " "* Counted Subexpressions:: " "* Alternative Subexpressions:: " "* Backreferences:: " "* A Summary of Regexp Syntax:: " "* Ambiguous Patterns:: " "@end menu" "" "" "@node An Introduction to Regexps, Literal Regexps, Posix Basic Regular Expressions, Posix Basic Regular Expressions" "@section An Introduction to Regexps" "" "In the simplest cases, a regexp is just a literal string that must" "match exactly. For example, the pattern:" "" "@example" "regexp" "@end example" "" "matches the string \"regexp\" and no others." "" "Some characters have a special meaning when they occur in a regexp." "They aren't matched literally as in the previous example, but instead" "denote a more general pattern. For example, the character @code{*}" "is used to indicate that the preceeding element of a regexp may be" "repeated 0, 1, or more times. In the pattern:" "" "@example" "smooo*th" "@end example" "" "the @code{*} indicates that the preceeding @code{o} can be repeated 0 or" "more times. So the pattern matches:" "" "@example" "smooth" "smoooth" "smooooth" "smoooooth" "..." "@end example" "" "Suppose you want to write a pattern that literally matches a special" "character like @code{*} -- in other words, you don't want to @code{*} to" "indicate a permissible repetition, but to match @code{*} literally. This" "is accomplished by quoting the special character with a backslash. " "The pattern:" "" "@example" "smoo\\*th" "@end example" "" "matches the string:" "" "@example" "smoo*th" "@end example" "" "" "and no other strings." "" "In five cases, the pattern is reversed -- a backslash makes the" "character special instead of making a special character normal. The" "characters @code{+}, @code{?}, @code{|}, @code{(}, and @code{)} are" "normal but the sequences @code{\\+}, @code{\\?}, @code{\\|}, @code{\\(}, and" "@code{\\)} are special (their meaning is described later)." "" "The remaining sections of this chapter introduce and explain the various" "special characters that can occur in regexps." "" "@node Literal Regexps, Character Sets, An Introduction to Regexps, Posix Basic Regular Expressions" "@section Literal Regexps" "" "A literal regexp is a string which contains no special characters." "A literal regexp matches an identical string, but no other characters." "For example:" "" "@example" "literally" "@end example" "" "matches" "" "@example" "literally" "@end example" "" "and nothing else." "" "Generally, whitespace characters, numbers, and letters are not special." "Some punctuation characters are special and some are not (the syntax" "summary at the end of this chapter makes a convenient reference for" "which characters are special and which aren't)." "" "" "@node Character Sets, Subexpressions, Literal Regexps, Posix Basic Regular Expressions" "@section Character Sets" "" "This section introduces the special characters @code{.} and @code{[}." "" "@code{.} matches any character except the NULL character. For example:" "" "@example" "p.ck" "@end example" "" "matches" "" "@example" "pick" "pack" "puck" "pbck" "pcck" "p.ck" "" "..." "@end example" "" "" "@code{[} begins a @dfn{character set}. A character set is similar to" "@code{.} in that it matches not a single, literal character, but any" "of a set of characters. @code{[} is different from @code{.} in that" "with @code{[}, you define the set of characters explicitly." "" "There are three basic forms a character set can take." "" "In the first form, the character set is spelled out:" "" "@example" "[<cset-spec>] -- every character in <cset-spec> is in the set." "@end example" "" "In the second form, the character set indicated is the negation of" "a character set is explicitly spelled out:" "" "@example" "[^<cset-spec>] -- every character *not* in <cset-spec> is in the set." "@end example" "" "A @code{<cset-spec>} is more or less an explicit enumeration of a set" "of characters. It can be written as a string of individual characters:" "" "@example" "[aeiou]" "@end example" "" "or as a range of characters:" "" "@example" "[0-9]" "@end example" "" "These two forms can be mixed:" "" "@example" "[A-za-z0-9_$]" "@end example" "" "Note that special regexp characters (such as @code{*}) are @emph{not}" "special within a character set. @code{-}, as illustrated above," "@emph{is} special, except, as illustrated below, when it is the first" "character mentioned." "" "This is a four-character set:" "" "@example" "[-+*/]" "@end example" "" "The third form of a character set makes use of a pre-defined \"character" "class\":" "" "@example" "[[:class-name:]] -- every character described by class-name is in the set." "@end example" "" "The supported character classes are:" "" "@example" "alnum - the set of alpha-numeric characters" "alpha - the set of alphabetic characters" "blank - tab and space" "cntrl - the control characters" "digit - decimal digits" "graph - all printable characters except space" "lower - lower case letters" "print - the \"printable\" characters" "punct - punctuation" "space - whitespace characters" "upper - upper case letters" "xdigit - hexidecimal digits" "@end example" "" "Finally, character class sets can also be inverted:" "" "@example" "[^[:space:]] - all non-whitespace characters" "@end example" "" "Character sets can be used in a regular expression anywhere a literal" "character can." "" "@node Subexpressions, Repeated Subexpressions, Character Sets, Posix Basic Regular Expressions" "@section Subexpressions" "" "A subexpression is a regular expression enclosed in @code{\\(} and" "@code{\\)}. A subexpression can be used anywhere a single character or" "character set can be used." "" "Subexpressions are useful for grouping regexp constructs. For example," "the repeat operator, @code{*}, usually applies to just the preceeding" "character. Recall that:" "" "@example" "smooo*th" "@end example" "" "matches" "" "@example" "smooth" "smoooth" "..." "@end example" "" "" "Using a subexpression, we can apply @code{*} to a longer string:" "" "@example" "banan\\(an\\)*a" "@end example" "" "matches" "" "@example" "banana" "bananana" "banananana" "..." "@end example" "" "Subexpressions also have a special meaning with regard to backreferences" "and substitutions (see @xref{Backreferences})." "" "" "@node Repeated Subexpressions, Optional Subexpressions, Subexpressions, Posix Basic Regular Expressions" "@section Repeated Subexpressions" "" "" "@code{*} is the repeat operator. It applies to the preceeding" "character, character set, subexpression or backreference. It indicates" "that the preceeding element can be matched 0 or more times:" "" "@example" "bana\\(na\\)*" "@end example" "" "matches" "" "@example" "bana" "banana" "bananana" "banananana" "..." "@end example" "" "" "" "@code{\\+} is similar to @code{*} except that @code{\\+} requires the" "preceeding element to be matched at least once. So while:" "" "@example" "bana\\(na\\)*" "@end example" "" "matches" "" "@example" "bana" "@end example" "" "@example" "bana(na\\)\\+" "@end example" "" "does not. Both match " "" "@example" "banana" "bananana" "banananana" "..." "@end example" "" "Thus, @code{bana\\(na\\)+} is short-hand for @code{banana\\(na\\)*}." "" "" "@node Optional Subexpressions, Counted Subexpressions, Repeated Subexpressions, Posix Basic Regular Expressions" "@section Optional Subexpressions" "" "@code{\\?} indicates that the preceeding character, character set, or" "subexpression is optional. It is permitted to match, or to be skipped:" "" "@example" "CSNY\\?" "@end example" "" "matches both" "" "@example" "CSN" "@end example" "" "and " "" "@example" "CSNY" "@end example" "" "" "@node Counted Subexpressions, Alternative Subexpressions, Optional Subexpressions, Posix Basic Regular Expressions" "@section Counted Subexpressions" "" "An interval expression, @code{@{m,n@}} where @code{m} and @code{n} are" "non-negative integers with @code{n >= m}, applies to the preceeding" "character, character set, subexpression or backreference. It indicates" "that the preceeding element must match at least @code{m} times and may" "match as many as @code{n} times." "" "For example:" "" "@example" "c\\([ad]\\)@{1,4@}" "@end example" "" "matches" "" "@example" "car" "cdr" "caar" "cdar" "..." "caaar" "cdaar" "..." "cadddr" "cddddr" "@end example" "" "" "" "@node Alternative Subexpressions, Backreferences, Counted Subexpressions, Posix Basic Regular Expressions" "@section Alternative Subexpressions" "" "An alternative is written:" "" "@example" "regexp-1\\|regexp-2\\|regexp-3\\|..." "@end example" "" "It matches anything matched by some @code{regexp-n}. For example:" "" "@example" "Crosby, Stills, \\(and Nash\\|Nash, and Young\\)" "@end example" "" "matches" "" "@example" "Crosby, Stills, and Nash" "@end example" "" "and" "" "@example" "Crosby, Stills, Nash, and Young" "@end example" "" "" "@node Backreferences, A Summary of Regexp Syntax, Alternative Subexpressions, Posix Basic Regular Expressions" "@section Backreferences, Extractions and Substitutions" "" "A backreference is written @code{\\n} where @code{n} is some single digit" "other than 0. To be a valid backreference, there must be at least" "@code{n} parenthesized subexpressions in the pattern prior to the" "backreference." "" "A backreference matches a literal copy of whatever was matched by the" "corresponding subexpression. For example," "" "@example" "\\(.*\\)-\\1" "@end example" "" "matches:" "" "@example" "go-go" "ha-ha" "wakka-wakka" "..." "@end example" "" "In some applications, subexpressions are used to extract substrings." "For example, Emacs has the functions @code{match-beginnning} and" "@code{match-end} which report the positions of strings matched by" "subexpressions. These functions use the same numbering scheme for" "subexpressions as backreferences, with the additional rule that" "subexpression 0 is defined to be the whole regexp." "" "In some applications, subexpressions are used in string substitution." "This again uses the backreference numbering scheme. For example, this sed" "command:" "" "@example" "s/From:.*<\\(.*\\)>/To: \\1/" "@end example" "" "first matches the line:" "" "@example" "From: Joe Schmoe <schmoe@@uspringfield.edu>" "@end example" "" "when it does, subexpression 1 matches \"schmoe@@uspringfield.edu\"." "The command replaces the matched line with \"To: \\1\" after doing" "subexpression substitution on it to get:" "" "@example" "To: schmoe@@uspringfield.edu" "@end example" "" "" "@node A Summary of Regexp Syntax, Ambiguous Patterns, Backreferences, Posix Basic Regular Expressions" "@section A Summary of Regexp Syntax" "" "In summary, regexps can be:" "" "@code{abcd} -- matching a string literally" "" "@code{.} -- matching everything except NULL" "" "@code{[a-z_?]}, @code{^[a-z_?]}, @code{[[:alpha:]]} and" "@code{[^[:alpha:]]} -- matching character sets" "" "@code{\\(subexp\\)} -- grouping an expression into a subexpression." "" "@code{\\n} -- match a copy of whatever was matched by the nth subexpression." "" "The following special characters and sequences can be applied to a" "character, character set, subexpression, or backreference:" "" "@code{*} -- repeat the preceeding element 0 or more times." "" "@code{\\+} -- repeat the preceeding element 1 or more times." "" "@code{\\?} -- match the preceeding element 0 or 1 time." "" "@code{@{m,n@}} -- match the preceeding element at least @code{m}, and as" "many as @code{n} times." "" "@code{regexp-1\\|regexp-2\\|..} -- match any regexp-n." "" "A special character, like @code{.} or @code{*} can be made into a literal" "character by prefixing it with @code{\\}." "" "A special sequence, like @code{\\+} or @code{\\?} can be made into a" "literal character by dropping the @code{\\}." "" "" "@node Ambiguous Patterns, , A Summary of Regexp Syntax, Posix Basic Regular Expressions" "@section Ambiguous Patterns" "" "Sometimes a regular expression appears to be ambiguous. For example, suppose" "we compare the pattern:" "" "@example" "begin\\|beginning" "@end example" "" "to the string" "" "@example" "beginning" "@end example" "" "either just the first 5 characters will match, or the whole string will match." "" "In every case like this, the longer match is preferred. The whole" "string will match." "" "Sometimes there is ambiguity not about how many characters to match, but" "where the subexpressions occur within the match. This can effect" "extraction functions like Emacs' @code{match-beginning} or rewrite" "functions like sed's @code{s} command. For example, consider matching" "the pattern:" "" "@example" "b\\(\\[^q]*\\)\\(ing\\)?" "@end example" "" "against the string" "" "@example" "beginning" "@end example" "" "One possibility is that the first subexpression matches \"eginning\" and" "the second is skipped. Another possibility is that the first" "subexpression matches \"eginn\" and the second matches \"ing\"." "" "The rule is that consistant with matching as many characters as " "possible, the length of lower numbered subexpressions is maximized" "in preference to maximizing the length of later subexpressions." "" "In the case of the above example, the two possible matches are equal in" "overall length. Therefore, it comes down to maximizing the" "lower-numbered subexpression, \\1. The correct answer is that \\1 matches" "\"eginning\" and \\2 is skipped." "" "@node Posix Entry Points, Beyond POSIX, Posix Basic Regular Expressions, Top" "@chapter Posix Entry Points" "" "This section is excerpted from @emph{The GNU C Library} reference manual" "by Sandra Loosemore with Richard M. Stallman, Roland McGrath, and Andrew" "Oram." "" "The GNU C library supports the standard POSIX.2 interface. Programs" "using this interface should include the header file @file{rxposix.h}." "" "@menu" "* POSIX Regexp Compilation:: Using @code{regcomp} to prepare to match." "* Flags for POSIX Regexps:: Syntax variations for @code{regcomp}." "* Matching POSIX Regexps:: Using @code{regexec} to match the compiled" " pattern that you get from @code{regcomp}." "* Regexp Subexpressions:: Finding which parts of the string were matched." "* Subexpression Complications:: Find points of which parts were matched." "* Regexp Cleanup:: Freeing storage; reporting errors." "@end menu" "" "@node POSIX Regexp Compilation, Flags for POSIX Regexps, Posix Entry Points, Posix Entry Points" "@section POSIX Regular Expression Compilation" "" "Before you can actually match a regular expression, you must" "@dfn{compile} it. This is not true compilation---it produces a special" "data structure, not machine instructions. But it is like ordinary" "compilation in that its purpose is to enable you to ``execute'' the" "pattern fast. (@xref{Matching POSIX Regexps}, for how to use the" "compiled regular expression for matching.)" "" "There is a special data type for compiled regular expressions:" "" "@comment regex.h" "@comment POSIX.2" "@deftp {Data Type} regex_t" "This type of object holds a compiled regular expression." "It is actually a structure. It has just one field that your programs" "should look at:" "" "@table @code" "@item re_nsub" "This field holds the number of parenthetical subexpressions in the" "regular expression that was compiled." "@end table" "" "There are several other fields, but we don't describe them here, because" "only the functions in the library should use them." "@end deftp" "" "After you create a @code{regex_t} object, you can compile a regular" "expression into it by calling @code{regcomp}." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun int regcomp (regex_t *@var{compiled}, const char *@var{pattern}, int @var{cflags})" "@deftypefunx int regncomp (regex_t *@var{compiled}, int len, const char *@var{pattern}, int @var{cflags})" "The function @code{regcomp} ``compiles'' a regular expression into a" "data structure that you can use with @code{regexec} to match against a" "string. The compiled regular expression format is designed for" "efficient matching. @code{regcomp} stores it into @code{*@var{compiled}}." "" "The parameter @var{pattern} points to the regular expression to be" "compiled. When using @code{regcomp}, @var{pattern} must be" "0-terminated. When using @code{regncomp}, @var{pattern} must be" "@var{len} characters long." "" "@code{regncomp} is not a standard function; strictly POSIX programs" "should avoid using it." "" "It's up to you to allocate an object of type @code{regex_t} and pass its" "address to @code{regcomp}." "" "The argument @var{cflags} lets you specify various options that control" "the syntax and semantics of regular expressions. @xref{Flags for POSIX" "Regexps}." "" "If you use the flag @code{REG_NOSUB}, then @code{regcomp} omits from" "the compiled regular expression the information necessary to record" "how subexpressions actually match. In this case, you might as well" "pass @code{0} for the @var{matchptr} and @var{nmatch} arguments when" "you call @code{regexec}." "" "If you don't use @code{REG_NOSUB}, then the compiled regular expression" "does have the capacity to record how subexpressions match. Also," "@code{regcomp} tells you how many subexpressions @var{pattern} has, by" "storing the number in @code{@var{compiled}->re_nsub}. You can use that" "value to decide how long an array to allocate to hold information about" "subexpression matches." "" "@code{regcomp} returns @code{0} if it succeeds in compiling the regular" "expression; otherwise, it returns a nonzero error code (see the table" "below). You can use @code{regerror} to produce an error message string" "describing the reason for a nonzero value; see @ref{Regexp Cleanup}." "" "@end deftypefun" "" "Here are the possible nonzero values that @code{regcomp} can return:" "" "@table @code" "@comment regex.h" "@comment POSIX.2" "@item REG_BADBR" "There was an invalid @samp{\\@{@dots{}\\@}} construct in the regular" "expression. A valid @samp{\\@{@dots{}\\@}} construct must contain either" "a single number, or two numbers in increasing order separated by a" "comma." "" "@comment regex.h" "@comment POSIX.2" "@item REG_BADPAT" "There was a syntax error in the regular expression." "" "@comment regex.h" "@comment POSIX.2" "@item REG_BADRPT" "A repetition operator such as @samp{?} or @samp{*} appeared in a bad" "position (with no preceding subexpression to act on)." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ECOLLATE" "The regular expression referred to an invalid collating element (one not" "defined in the current locale for string collation). " "" "@comment regex.h" "@comment POSIX.2" "@item REG_ECTYPE" "The regular expression referred to an invalid character class name." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EESCAPE" "The regular expression ended with @samp{\\}." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ESUBREG" "There was an invalid number in the @samp{\\@var{digit}} construct." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EBRACK" "There were unbalanced square brackets in the regular expression." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EPAREN" "An extended regular expression had unbalanced parentheses," "or a basic regular expression had unbalanced @samp{\\(} and @samp{\\)}." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EBRACE" "The regular expression had unbalanced @samp{\\@{} and @samp{\\@}}." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ERANGE" "One of the endpoints in a range expression was invalid." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ESPACE" "@code{regcomp} ran out of memory." "@end table" "" "@node Flags for POSIX Regexps, Matching POSIX Regexps, POSIX Regexp Compilation, Posix Entry Points" "@section Flags for POSIX Regular Expressions" "" "These are the bit flags that you can use in the @var{cflags} operand when" "compiling a regular expression with @code{regcomp}." " " "@table @code" "@comment regex.h" "@comment POSIX.2" "@item REG_EXTENDED" "Treat the pattern as an extended regular expression, rather than as a" "basic regular expression." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ICASE" "Ignore case when matching letters." "" "@comment regex.h" "@comment POSIX.2" "@item REG_NOSUB" "Don't bother storing the contents of the @var{matches-ptr} array." "" "@comment regex.h" "@comment POSIX.2" "@item REG_NEWLINE" "Treat a newline in @var{string} as dividing @var{string} into multiple" "lines, so that @samp{$} can match before the newline and @samp{^} can" "match after. Also, don't permit @samp{.} to match a newline, and don't" "permit @samp{[^@dots{}]} to match a newline." "" "Otherwise, newline acts like any other ordinary character." "@end table" "" "@node Matching POSIX Regexps, Regexp Subexpressions, Flags for POSIX Regexps, Posix Entry Points" "@section Matching a Compiled POSIX Regular Expression" "" "Once you have compiled a regular expression, as described in @ref{POSIX" "Regexp Compilation}, you can match it against strings using" "@code{regexec}. A match anywhere inside the string counts as success," "unless the regular expression contains anchor characters (@samp{^} or" "@samp{$})." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun int regexec (regex_t *@var{compiled}, char *@var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr} @t{[]}, int @var{eflags})" "@deftypefunx int regnexec (regex_t *@var{compiled}, int len, char *@var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr} @t{[]}, int @var{eflags})" "This function tries to match the compiled regular expression" "@code{*@var{compiled}} against @var{string}." "" "@code{regexec} returns @code{0} if the regular expression matches;" "otherwise, it returns a nonzero value. See the table below for" "what nonzero values mean. You can use @code{regerror} to produce an" "error message string describing the reason for a nonzero value; " "see @ref{Regexp Cleanup}." "" "The parameter @var{string} points to the text to search. When using" "@code{regexec}, @var{string} must be 0-terminated. When using" "@code{regnexec}, @var{string} must be @var{len} characters long." "" "@code{regnexec} is not a standard function; strictly POSIX programs" "should avoid using it." "" "The argument @var{eflags} is a word of bit flags that enable various" "options." "" "If you want to get information about what part of @var{string} actually" "matched the regular expression or its subexpressions, use the arguments" "@var{matchptr} and @var{nmatch}. Otherwise, pass @code{0} for " "@var{nmatch}, and @code{NULL} for @var{matchptr}. @xref{Regexp" "Subexpressions}." "@end deftypefun" "" "You must match the regular expression with the same set of current" "locales that were in effect when you compiled the regular expression." "" "The function @code{regexec} accepts the following flags in the" "@var{eflags} argument:" "" "@table @code " "@comment regex.h" "@comment POSIX.2" "@item REG_NOTBOL" "Do not regard the beginning of the specified string as the beginning of" "a line; more generally, don't make any assumptions about what text might" "precede it." "" "@comment regex.h" "@comment POSIX.2" "@item REG_NOTEOL" "Do not regard the end of the specified string as the end of a line; more" "generally, don't make any assumptions about what text might follow it." "@end table" "" "Here are the possible nonzero values that @code{regexec} can return:" "" "@table @code" "@comment regex.h" "@comment POSIX.2" "@item REG_NOMATCH" "The pattern didn't match the string. This isn't really an error." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ESPACE" "@code{regexec} ran out of memory." "@end table" "" "@node Regexp Subexpressions, Subexpression Complications, Matching POSIX Regexps, Posix Entry Points" "@section Match Results with Subexpressions" "" "When @code{regexec} matches parenthetical subexpressions of" "@var{pattern}, it records which parts of @var{string} they match. It" "returns that information by storing the offsets into an array whose" "elements are structures of type @code{regmatch_t}. The first element of" "the array (index @code{0}) records the part of the string that matched" "the entire regular expression. Each other element of the array records" "the beginning and end of the part that matched a single parenthetical" "subexpression." "" "@comment regex.h" "@comment POSIX.2" "@deftp {Data Type} regmatch_t" "This is the data type of the @var{matcharray} array that you pass to" "@code{regexec}. It containes two structure fields, as follows:" "" "@table @code" "@item rm_so" "The offset in @var{string} of the beginning of a substring. Add this" "value to @var{string} to get the address of that part." "" "@item rm_eo" "The offset in @var{string} of the end of the substring." "@end table" "@end deftp" "" "@comment regex.h" "@comment POSIX.2" "@deftp {Data Type} regoff_t" "@code{regoff_t} is an alias for another signed integer type." "The fields of @code{regmatch_t} have type @code{regoff_t}." "@end deftp" "" "The @code{regmatch_t} elements correspond to subexpressions" "positionally; the first element (index @code{1}) records where the first" "subexpression matched, the second element records the second" "subexpression, and so on. The order of the subexpressions is the order" "in which they begin." "" "When you call @code{regexec}, you specify how long the @var{matchptr}" "array is, with the @var{nmatch} argument. This tells @code{regexec} how" "many elements to store. If the actual regular expression has more than" "@var{nmatch} subexpressions, then you won't get offset information about" "the rest of them. But this doesn't alter whether the pattern matches a" "particular string or not." "" "If you don't want @code{regexec} to return any information about where" "the subexpressions matched, you can either supply @code{0} for" "@var{nmatch}, or use the flag @code{REG_NOSUB} when you compile the" "pattern with @code{regcomp}." "" "@node Subexpression Complications, Regexp Cleanup, Regexp Subexpressions, Posix Entry Points" "@section Complications in Subexpression Matching" "" "Sometimes a subexpression matches a substring of no characters. This" "happens when @samp{f\\(o*\\)} matches the string @samp{fum}. (It really" "matches just the @samp{f}.) In this case, both of the offsets identify" "the point in the string where the null substring was found. In this" "example, the offsets are both @code{1}." "" "Sometimes the entire regular expression can match without using some of" "its subexpressions at all---for example, when @samp{ba\\(na\\)*} matches the" "string @samp{ba}, the parenthetical subexpression is not used. When" "this happens, @code{regexec} stores @code{-1} in both fields of the" "element for that subexpression." "" "Sometimes matching the entire regular expression can match a particular" "subexpression more than once---for example, when @samp{ba\\(na\\)*}" "matches the string @samp{bananana}, the parenthetical subexpression" "matches three times. When this happens, @code{regexec} usually stores" "the offsets of the last part of the string that matched the" "subexpression. In the case of @samp{bananana}, these offsets are" "@code{6} and @code{8}." "" "But the last match is not always the one that is chosen. It's more" "accurate to say that the last @emph{opportunity} to match is the one" "that takes precedence. What this means is that when one subexpression" "appears within another, then the results reported for the inner" "subexpression reflect whatever happened on the last match of the outer" "subexpression. For an example, consider @samp{\\(ba\\(na\\)*s \\)*} matching" "the string @samp{bananas bas }. The last time the inner expression" "actually matches is near the end of the first word. But it is " "@emph{considered} again in the second word, and fails to match there." "@code{regexec} reports nonuse of the ``na'' subexpression." "" "Another place where this rule applies is when the regular expression" "@w{@samp{\\(ba\\(na\\)*s \\|nefer\\(ti\\)* \\)*}} matches @samp{bananas nefertiti}." "The ``na'' subexpression does match in the first word, but it doesn't" "match in the second word because the other alternative is used there." "Once again, the second repetition of the outer subexpression overrides" "the first, and within that second repetition, the ``na'' subexpression" "is not used. So @code{regexec} reports nonuse of the ``na''" "subexpression." "" "@node Regexp Cleanup, , Subexpression Complications, Posix Entry Points" "@section POSIX Regexp Matching Cleanup" "" "When you are finished using a compiled regular expression, you can" "free the storage it uses by calling @code{regfree}." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun void regfree (regex_t *@var{compiled})" "Calling @code{regfree} frees all the storage that @code{*@var{compiled}}" "points to. This includes various internal fields of the @code{regex_t}" "structure that aren't documented in this manual." "" "@code{regfree} does not free the object @code{*@var{compiled}} itself." "@end deftypefun" "" "You should always free the space in a @code{regex_t} structure with" "@code{regfree} before using the structure to compile another regular" "expression." "" "When @code{regcomp} or @code{regexec} reports an error, you can use" "the function @code{regerror} to turn it into an error message string." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun size_t regerror (int @var{errcode}, regex_t *@var{compiled}, char *@var{buffer}, size_t @var{length})" "This function produces an error message string for the error code" "@var{errcode}, and stores the string in @var{length} bytes of memory" "starting at @var{buffer}. For the @var{compiled} argument, supply the" "same compiled regular expression structure that @code{regcomp} or" "@code{regexec} was working with when it got the error. Alternatively," "you can supply @code{NULL} for @var{compiled}; you will still get a" "meaningful error message, but it might not be as detailed." "" "If the error message can't fit in @var{length} bytes (including a" "terminating null character), then @code{regerror} truncates it." "The string that @code{regerror} stores is always null-terminated" "even if it has been truncated." "" "The return value of @code{regerror} is the minimum length needed to" "store the entire error message. If this is less than @var{length}, then" "the error message was not truncated, and you can use it. Otherwise, you" "should call @code{regerror} again with a larger buffer." "" "Here is a function which uses @code{regerror}, but always dynamically" "allocates a buffer for the error message:" "" "@smallexample" "char *get_regerror (int errcode, regex_t *compiled)" "@{" " size_t length = regerror (errcode, compiled, NULL, 0);" " char *buffer = xmalloc (length);" " (void) regerror (errcode, compiled, buffer, length);" " return buffer;" "@}" "@end smallexample" "@end deftypefun" "" "@node Beyond POSIX, Rx Theory, Posix Entry Points, Top" "@chapter Beyond POSIX" "" "This section is not finished documentation, but rather a collection of" "pointers towards some of the interesting, non-standard features of Rx." "" "@section New Regexp Operators" "" "Rx supports some unusual regexp syntax." "" "@code{[[:cut N:]]} sets @code{pmatch[0].final_tag} to N and causes the" "matching to stop instantly. If N is 0, the overall match fails," "otherwise it succeeds." "" "@code{[[:(:]] ... [[:):]]} is just like @code{\\( ... \\)} except that in" "the first case, no pmatch entries are changed, and the subexpression is" "not counted in the numbering of parenthesized subexpressions." "" "@code{[[:(:]] ... [[:):]]} can be used when you do not need to know" "where a subexpression matched but are only using parentheses to effect" "the parsing of the regexp. " "" "There are two reasons to use @code{[[:(:]] ... [[:):]]}:" "" "1. regexec will run faster." "" "2. Currently, only 8 backreferencable subexpressions are supported:" "@code{\\1 .. \\9}. Using @code{[[:(:]] ... [[:):]]} is a way to conserve" "backreferencable subexpression names in an expression with many" "parentheses." "" "@section New POSIX Functions" "" "@code{regncomp} and @code{regnexec} are non-standard generalizations of" "@code{regcomp} and @code{regexec}." "" "@section Tuning POSIX performance" "" "Two mysterious parmaters can be used to trade-off performance and" "memory use." "" "At compile-time they are @code{RX_DEFAULT_DFA_CACHE_SIZE} and" "@code{RX_DEFAULT_NFA_DELAY}. " "" "If you want to mess with these (I generally don't advise it), I suggest" "experimenting for your particular application/memory situation; frob" "these by powers of two and try out the results on what you expect will" "be typical regexp workloads." "" "You can also set those parameters at run-time (before calling any regexp" "functions) by tweaking the corresponding variables:" "" "@code{rx_default_cache->bytes_allowed}" "" "and" "" "@code{rx_basic_unfaniverse_delay}" "" "" "" "@section POSIX stream-style interface" "" "@code{rx_make_solutions}, @code{rx_next_solution}, and" "@code{rx_free_solutions} are a lower level alternative to the posix" "functions. Using those functions, you can compare a compiled regexp to" "a string that is not contiguous in memory or even a string that is not" "entirely in memory at any one time." "" "The code in rxposix.c points out how those functions are used." "" "" "@section DFAs Directly" "" "If you are only interested in pure regular expressions (no pmatch data," "no backreferences, and no counted subexpressions), you can parse a" "regexp using @code{rx_parse}, convert it to an nfa using @code{rx_unfa}," "and run the dfa using @code{rx_init_system}, @code{rx_advance_to_final}," "and @code{rx_terminate_system}. The dfa Scheme primitives in" "@file{rgx.c} may provide some guide." "" "@node Rx Theory, , Beyond POSIX, Top" "@chapter Rx Theory" "@cindex Rx Theory" "" "There are two match algorithms. One is for truly regular regexps (those" "that can be reduced to a dfa). The other is for non-regular regexps." "" "The dfa algorithm implements the idea suggested in @cite{Compilers} by" "Aho, Sethi and Ullman:" "" "@quotation" "[One] approach [to pattern matching regular expressions] is to use a" "DFA, but avoid constructing all of the transition table by using a" "technique called \"lazy transition evaluation\". Here, transitions are" "computed at run time [when] actually needed. [T]ransitions are" "stored in a cache. [....] If the cache becomes full, we can erase some" "previously computed transition to make room for the new transition." "@end quotation" "" "The implementation in Rx is generalized from that, but the above" "description covers what is used for Posix patterns. " "" "The non-dfa algorithm implements a \"recursive decomposition\" technique" "described in email by Henry Spencer. For a given pattern, this" "algorithm first checks to see if a simpler, superset language," "DFA-pattern matches. If it does, then this algorithm does the" "detail-work to see if the non-DFA pattern matches." "\\input texinfo @c -*-texinfo-*-" "@c %**start of header" "@setfilename rx.info" "@settitle Rx" "@setchapternewpage odd" "@c %**end of header" "" "@c This title page illustrates only one of the" "@c two methods of forming a title page." "" "@titlepage" "@title Rx" "@author Tom Lord" "" "@center except the chapter \"Posix Entry Points\" " "@center from @emph{The GNU C Library} reference manual" "@center by Sandra Loosemore" "@center with" "@center Richard M. Stallman, Roland McGrath, and Andrew Oram" "" "@c The following two commands" "@c start the copyright page." "@page" "@vskip 0pt plus 1filll" "Copyright @copyright{} 1995 Cygnus Support" "" "except the chapter \"Posix Entry Points\" which is:" "" "Copyright @copyright{} 1995 Free Software Foundation, Inc." "" "Permission is granted to make and distribute verbatim copies of" "this manual provided the copyright notice and this permission notice" "are preserved on all copies." "" "Permission is granted to copy and distribute modified versions of this" "manual under the conditions for verbatim copying, provided that the entire" "resulting derived work is distributed under the terms of a permission" "notice identical to this one." "" "Permission is granted to copy and distribute translations of this manual" "into another language, under the above conditions for modified versions," "except that this permission notice may be stated in a translation approved" "by the author." "" "@end titlepage" "" "@node Top, Copying, (dir), (dir)" "@top Rx" "" "This document describes Rx." "" "@menu" "* Copying:: Sharing is good." "* Overview:: Fnord" "* Posix Basic Regular Expressions:: A popular regexp syntax." "* Posix Entry Points:: The POSIX way to regexp." "* Beyond POSIX:: Hints about cool features." "* Rx Theory:: Hints about how it works." "@end menu" "" "@node Copying, Overview, Top, Top" "@chapter Copying" "" "@center Copyright (C) 1996" "@center Tom Lord" "@center Berkeley, CA USA" "" "@center except portions of \"POSIX Regex Functions\" which are" "@center Copyright (C) 1995" "@center Free Software Foundation, Inc." "" "@noindent" "Permission to use, copy, modify, distribute, and sell this software and" "its documentation for any purpose is hereby granted without fee," "provided that the above copyright notice appear in all copies and that" "both that copyright notice and this permission notice appear in" "supporting documentation." "" "@center NO WARRANTY" "" "@noindent" "BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR" "THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN" "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES" "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER" "EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED" "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE" "ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH" "YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL" "NECESSARY SERVICING, REPAIR OR CORRECTION." "" "@noindent" "IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING" "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR" "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR" "DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL" "DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM" "(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED" "INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF" "THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR" "OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES." "" "@node Overview, Posix Basic Regular Expressions, Copying, Top" "@chapter Overview" "" "Nothing to say here, yet." "" "@node Posix Basic Regular Expressions, Posix Entry Points, Overview, Top" "@chapter Posix Basic Regular Expressions" "" "The Posix Basic Regular Expression language is a notation for describing" "textual patterns. Regexps are typically used by comparing them to a" "string to see if that string matches the pattern, or by searching within" "a string for a substring that matches." "" "This chapter introduces the Posix regexp notation. This is not a formal" "or precise definition of Posix regexps -- it is an intuitive and" "hopefully expository description of them." "" "@menu" "* An Introduction to Regexps:: " "* Literal Regexps:: " "* Character Sets:: " "* Subexpressions:: " "* Repeated Subexpressions:: " "* Optional Subexpressions:: " "* Counted Subexpressions:: " "* Alternative Subexpressions:: " "* Backreferences:: " "* A Summary of Regexp Syntax:: " "* Ambiguous Patterns:: " "@end menu" "" "" "@node An Introduction to Regexps, Literal Regexps, Posix Basic Regular Expressions, Posix Basic Regular Expressions" "@section An Introduction to Regexps" "" "In the simplest cases, a regexp is just a literal string that must" "match exactly. For example, the pattern:" "" "@example" "regexp" "@end example" "" "matches the string \"regexp\" and no others." "" "Some characters have a special meaning when they occur in a regexp." "They aren't matched literally as in the previous example, but instead" "denote a more general pattern. For example, the character @code{*}" "is used to indicate that the preceeding element of a regexp may be" "repeated 0, 1, or more times. In the pattern:" "" "@example" "smooo*th" "@end example" "" "the @code{*} indicates that the preceeding @code{o} can be repeated 0 or" "more times. So the pattern matches:" "" "@example" "smooth" "smoooth" "smooooth" "smoooooth" "..." "@end example" "" "Suppose you want to write a pattern that literally matches a special" "character like @code{*} -- in other words, you don't want to @code{*} to" "indicate a permissible repetition, but to match @code{*} literally. This" "is accomplished by quoting the special character with a backslash. " "The pattern:" "" "@example" "smoo\\*th" "@end example" "" "matches the string:" "" "@example" "smoo*th" "@end example" "" "" "and no other strings." "" "In five cases, the pattern is reversed -- a backslash makes the" "character special instead of making a special character normal. The" "characters @code{+}, @code{?}, @code{|}, @code{(}, and @code{)} are" "normal but the sequences @code{\\+}, @code{\\?}, @code{\\|}, @code{\\(}, and" "@code{\\)} are special (their meaning is described later)." "" "The remaining sections of this chapter introduce and explain the various" "special characters that can occur in regexps." "" "@node Literal Regexps, Character Sets, An Introduction to Regexps, Posix Basic Regular Expressions" "@section Literal Regexps" "" "A literal regexp is a string which contains no special characters." "A literal regexp matches an identical string, but no other characters." "For example:" "" "@example" "literally" "@end example" "" "matches" "" "@example" "literally" "@end example" "" "and nothing else." "" "Generally, whitespace characters, numbers, and letters are not special." "Some punctuation characters are special and some are not (the syntax" "summary at the end of this chapter makes a convenient reference for" "which characters are special and which aren't)." "" "" "@node Character Sets, Subexpressions, Literal Regexps, Posix Basic Regular Expressions" "@section Character Sets" "" "This section introduces the special characters @code{.} and @code{[}." "" "@code{.} matches any character except the NULL character. For example:" "" "@example" "p.ck" "@end example" "" "matches" "" "@example" "pick" "pack" "puck" "pbck" "pcck" "p.ck" "" "..." "@end example" "" "" "@code{[} begins a @dfn{character set}. A character set is similar to" "@code{.} in that it matches not a single, literal character, but any" "of a set of characters. @code{[} is different from @code{.} in that" "with @code{[}, you define the set of characters explicitly." "" "There are three basic forms a character set can take." "" "In the first form, the character set is spelled out:" "" "@example" "[<cset-spec>] -- every character in <cset-spec> is in the set." "@end example" "" "In the second form, the character set indicated is the negation of" "a character set is explicitly spelled out:" "" "@example" "[^<cset-spec>] -- every character *not* in <cset-spec> is in the set." "@end example" "" "A @code{<cset-spec>} is more or less an explicit enumeration of a set" "of characters. It can be written as a string of individual characters:" "" "@example" "[aeiou]" "@end example" "" "or as a range of characters:" "" "@example" "[0-9]" "@end example" "" "These two forms can be mixed:" "" "@example" "[A-za-z0-9_$]" "@end example" "" "Note that special regexp characters (such as @code{*}) are @emph{not}" "special within a character set. @code{-}, as illustrated above," "@emph{is} special, except, as illustrated below, when it is the first" "character mentioned." "" "This is a four-character set:" "" "@example" "[-+*/]" "@end example" "" "The third form of a character set makes use of a pre-defined \"character" "class\":" "" "@example" "[[:class-name:]] -- every character described by class-name is in the set." "@end example" "" "The supported character classes are:" "" "@example" "alnum - the set of alpha-numeric characters" "alpha - the set of alphabetic characters" "blank - tab and space" "cntrl - the control characters" "digit - decimal digits" "graph - all printable characters except space" "lower - lower case letters" "print - the \"printable\" characters" "punct - punctuation" "space - whitespace characters" "upper - upper case letters" "xdigit - hexidecimal digits" "@end example" "" "Finally, character class sets can also be inverted:" "" "@example" "[^[:space:]] - all non-whitespace characters" "@end example" "" "Character sets can be used in a regular expression anywhere a literal" "character can." "" "@node Subexpressions, Repeated Subexpressions, Character Sets, Posix Basic Regular Expressions" "@section Subexpressions" "" "A subexpression is a regular expression enclosed in @code{\\(} and" "@code{\\)}. A subexpression can be used anywhere a single character or" "character set can be used." "" "Subexpressions are useful for grouping regexp constructs. For example," "the repeat operator, @code{*}, usually applies to just the preceeding" "character. Recall that:" "" "@example" "smooo*th" "@end example" "" "matches" "" "@example" "smooth" "smoooth" "..." "@end example" "" "" "Using a subexpression, we can apply @code{*} to a longer string:" "" "@example" "banan\\(an\\)*a" "@end example" "" "matches" "" "@example" "banana" "bananana" "banananana" "..." "@end example" "" "Subexpressions also have a special meaning with regard to backreferences" "and substitutions (see @xref{Backreferences})." "" "" "@node Repeated Subexpressions, Optional Subexpressions, Subexpressions, Posix Basic Regular Expressions" "@section Repeated Subexpressions" "" "" "@code{*} is the repeat operator. It applies to the preceeding" "character, character set, subexpression or backreference. It indicates" "that the preceeding element can be matched 0 or more times:" "" "@example" "bana\\(na\\)*" "@end example" "" "matches" "" "@example" "bana" "banana" "bananana" "banananana" "..." "@end example" "" "" "" "@code{\\+} is similar to @code{*} except that @code{\\+} requires the" "preceeding element to be matched at least once. So while:" "" "@example" "bana\\(na\\)*" "@end example" "" "matches" "" "@example" "bana" "@end example" "" "@example" "bana(na\\)\\+" "@end example" "" "does not. Both match " "" "@example" "banana" "bananana" "banananana" "..." "@end example" "" "Thus, @code{bana\\(na\\)+} is short-hand for @code{banana\\(na\\)*}." "" "" "@node Optional Subexpressions, Counted Subexpressions, Repeated Subexpressions, Posix Basic Regular Expressions" "@section Optional Subexpressions" "" "@code{\\?} indicates that the preceeding character, character set, or" "subexpression is optional. It is permitted to match, or to be skipped:" "" "@example" "CSNY\\?" "@end example" "" "matches both" "" "@example" "CSN" "@end example" "" "and " "" "@example" "CSNY" "@end example" "" "" "@node Counted Subexpressions, Alternative Subexpressions, Optional Subexpressions, Posix Basic Regular Expressions" "@section Counted Subexpressions" "" "An interval expression, @code{@{m,n@}} where @code{m} and @code{n} are" "non-negative integers with @code{n >= m}, applies to the preceeding" "character, character set, subexpression or backreference. It indicates" "that the preceeding element must match at least @code{m} times and may" "match as many as @code{n} times." "" "For example:" "" "@example" "c\\([ad]\\)@{1,4@}" "@end example" "" "matches" "" "@example" "car" "cdr" "caar" "cdar" "..." "caaar" "cdaar" "..." "cadddr" "cddddr" "@end example" "" "" "" "@node Alternative Subexpressions, Backreferences, Counted Subexpressions, Posix Basic Regular Expressions" "@section Alternative Subexpressions" "" "An alternative is written:" "" "@example" "regexp-1\\|regexp-2\\|regexp-3\\|..." "@end example" "" "It matches anything matched by some @code{regexp-n}. For example:" "" "@example" "Crosby, Stills, \\(and Nash\\|Nash, and Young\\)" "@end example" "" "matches" "" "@example" "Crosby, Stills, and Nash" "@end example" "" "and" "" "@example" "Crosby, Stills, Nash, and Young" "@end example" "" "" "@node Backreferences, A Summary of Regexp Syntax, Alternative Subexpressions, Posix Basic Regular Expressions" "@section Backreferences, Extractions and Substitutions" "" "A backreference is written @code{\\n} where @code{n} is some single digit" "other than 0. To be a valid backreference, there must be at least" "@code{n} parenthesized subexpressions in the pattern prior to the" "backreference." "" "A backreference matches a literal copy of whatever was matched by the" "corresponding subexpression. For example," "" "@example" "\\(.*\\)-\\1" "@end example" "" "matches:" "" "@example" "go-go" "ha-ha" "wakka-wakka" "..." "@end example" "" "In some applications, subexpressions are used to extract substrings." "For example, Emacs has the functions @code{match-beginnning} and" "@code{match-end} which report the positions of strings matched by" "subexpressions. These functions use the same numbering scheme for" "subexpressions as backreferences, with the additional rule that" "subexpression 0 is defined to be the whole regexp." "" "In some applications, subexpressions are used in string substitution." "This again uses the backreference numbering scheme. For example, this sed" "command:" "" "@example" "s/From:.*<\\(.*\\)>/To: \\1/" "@end example" "" "first matches the line:" "" "@example" "From: Joe Schmoe <schmoe@@uspringfield.edu>" "@end example" "" "when it does, subexpression 1 matches \"schmoe@@uspringfield.edu\"." "The command replaces the matched line with \"To: \\1\" after doing" "subexpression substitution on it to get:" "" "@example" "To: schmoe@@uspringfield.edu" "@end example" "" "" "@node A Summary of Regexp Syntax, Ambiguous Patterns, Backreferences, Posix Basic Regular Expressions" "@section A Summary of Regexp Syntax" "" "In summary, regexps can be:" "" "@code{abcd} -- matching a string literally" "" "@code{.} -- matching everything except NULL" "" "@code{[a-z_?]}, @code{^[a-z_?]}, @code{[[:alpha:]]} and" "@code{[^[:alpha:]]} -- matching character sets" "" "@code{\\(subexp\\)} -- grouping an expression into a subexpression." "" "@code{\\n} -- match a copy of whatever was matched by the nth subexpression." "" "The following special characters and sequences can be applied to a" "character, character set, subexpression, or backreference:" "" "@code{*} -- repeat the preceeding element 0 or more times." "" "@code{\\+} -- repeat the preceeding element 1 or more times." "" "@code{\\?} -- match the preceeding element 0 or 1 time." "" "@code{@{m,n@}} -- match the preceeding element at least @code{m}, and as" "many as @code{n} times." "" "@code{regexp-1\\|regexp-2\\|..} -- match any regexp-n." "" "A special character, like @code{.} or @code{*} can be made into a literal" "character by prefixing it with @code{\\}." "" "A special sequence, like @code{\\+} or @code{\\?} can be made into a" "literal character by dropping the @code{\\}." "" "" "@node Ambiguous Patterns, , A Summary of Regexp Syntax, Posix Basic Regular Expressions" "@section Ambiguous Patterns" "" "Sometimes a regular expression appears to be ambiguous. For example, suppose" "we compare the pattern:" "" "@example" "begin\\|beginning" "@end example" "" "to the string" "" "@example" "beginning" "@end example" "" "either just the first 5 characters will match, or the whole string will match." "" "In every case like this, the longer match is preferred. The whole" "string will match." "" "Sometimes there is ambiguity not about how many characters to match, but" "where the subexpressions occur within the match. This can effect" "extraction functions like Emacs' @code{match-beginning} or rewrite" "functions like sed's @code{s} command. For example, consider matching" "the pattern:" "" "@example" "b\\(\\[^q]*\\)\\(ing\\)?" "@end example" "" "against the string" "" "@example" "beginning" "@end example" "" "One possibility is that the first subexpression matches \"eginning\" and" "the second is skipped. Another possibility is that the first" "subexpression matches \"eginn\" and the second matches \"ing\"." "" "The rule is that consistant with matching as many characters as " "possible, the length of lower numbered subexpressions is maximized" "in preference to maximizing the length of later subexpressions." "" "In the case of the above example, the two possible matches are equal in" "overall length. Therefore, it comes down to maximizing the" "lower-numbered subexpression, \\1. The correct answer is that \\1 matches" "\"eginning\" and \\2 is skipped." "" "@node Posix Entry Points, Beyond POSIX, Posix Basic Regular Expressions, Top" "@chapter Posix Entry Points" "" "This section is excerpted from @emph{The GNU C Library} reference manual" "by Sandra Loosemore with Richard M. Stallman, Roland McGrath, and Andrew" "Oram." "" "The GNU C library supports the standard POSIX.2 interface. Programs" "using this interface should include the header file @file{rxposix.h}." "" "@menu" "* POSIX Regexp Compilation:: Using @code{regcomp} to prepare to match." "* Flags for POSIX Regexps:: Syntax variations for @code{regcomp}." "* Matching POSIX Regexps:: Using @code{regexec} to match the compiled" " pattern that you get from @code{regcomp}." "* Regexp Subexpressions:: Finding which parts of the string were matched." "* Subexpression Complications:: Find points of which parts were matched." "* Regexp Cleanup:: Freeing storage; reporting errors." "@end menu" "" "@node POSIX Regexp Compilation, Flags for POSIX Regexps, Posix Entry Points, Posix Entry Points" "@section POSIX Regular Expression Compilation" "" "Before you can actually match a regular expression, you must" "@dfn{compile} it. This is not true compilation---it produces a special" "data structure, not machine instructions. But it is like ordinary" "compilation in that its purpose is to enable you to ``execute'' the" "pattern fast. (@xref{Matching POSIX Regexps}, for how to use the" "compiled regular expression for matching.)" "" "There is a special data type for compiled regular expressions:" "" "@comment regex.h" "@comment POSIX.2" "@deftp {Data Type} regex_t" "This type of object holds a compiled regular expression." "It is actually a structure. It has just one field that your programs" "should look at:" "" "@table @code" "@item re_nsub" "This field holds the number of parenthetical subexpressions in the" "regular expression that was compiled." "@end table" "" "There are several other fields, but we don't describe them here, because" "only the functions in the library should use them." "@end deftp" "" "After you create a @code{regex_t} object, you can compile a regular" "expression into it by calling @code{regcomp}." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun int regcomp (regex_t *@var{compiled}, const char *@var{pattern}, int @var{cflags})" "@deftypefunx int regncomp (regex_t *@var{compiled}, int len, const char *@var{pattern}, int @var{cflags})" "The function @code{regcomp} ``compiles'' a regular expression into a" "data structure that you can use with @code{regexec} to match against a" "string. The compiled regular expression format is designed for" "efficient matching. @code{regcomp} stores it into @code{*@var{compiled}}." "" "The parameter @var{pattern} points to the regular expression to be" "compiled. When using @code{regcomp}, @var{pattern} must be" "0-terminated. When using @code{regncomp}, @var{pattern} must be" "@var{len} characters long." "" "@code{regncomp} is not a standard function; strictly POSIX programs" "should avoid using it." "" "It's up to you to allocate an object of type @code{regex_t} and pass its" "address to @code{regcomp}." "" "The argument @var{cflags} lets you specify various options that control" "the syntax and semantics of regular expressions. @xref{Flags for POSIX" "Regexps}." "" "If you use the flag @code{REG_NOSUB}, then @code{regcomp} omits from" "the compiled regular expression the information necessary to record" "how subexpressions actually match. In this case, you might as well" "pass @code{0} for the @var{matchptr} and @var{nmatch} arguments when" "you call @code{regexec}." "" "If you don't use @code{REG_NOSUB}, then the compiled regular expression" "does have the capacity to record how subexpressions match. Also," "@code{regcomp} tells you how many subexpressions @var{pattern} has, by" "storing the number in @code{@var{compiled}->re_nsub}. You can use that" "value to decide how long an array to allocate to hold information about" "subexpression matches." "" "@code{regcomp} returns @code{0} if it succeeds in compiling the regular" "expression; otherwise, it returns a nonzero error code (see the table" "below). You can use @code{regerror} to produce an error message string" "describing the reason for a nonzero value; see @ref{Regexp Cleanup}." "" "@end deftypefun" "" "Here are the possible nonzero values that @code{regcomp} can return:" "" "@table @code" "@comment regex.h" "@comment POSIX.2" "@item REG_BADBR" "There was an invalid @samp{\\@{@dots{}\\@}} construct in the regular" "expression. A valid @samp{\\@{@dots{}\\@}} construct must contain either" "a single number, or two numbers in increasing order separated by a" "comma." "" "@comment regex.h" "@comment POSIX.2" "@item REG_BADPAT" "There was a syntax error in the regular expression." "" "@comment regex.h" "@comment POSIX.2" "@item REG_BADRPT" "A repetition operator such as @samp{?} or @samp{*} appeared in a bad" "position (with no preceding subexpression to act on)." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ECOLLATE" "The regular expression referred to an invalid collating element (one not" "defined in the current locale for string collation). " "" "@comment regex.h" "@comment POSIX.2" "@item REG_ECTYPE" "The regular expression referred to an invalid character class name." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EESCAPE" "The regular expression ended with @samp{\\}." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ESUBREG" "There was an invalid number in the @samp{\\@var{digit}} construct." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EBRACK" "There were unbalanced square brackets in the regular expression." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EPAREN" "An extended regular expression had unbalanced parentheses," "or a basic regular expression had unbalanced @samp{\\(} and @samp{\\)}." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EBRACE" "The regular expression had unbalanced @samp{\\@{} and @samp{\\@}}." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ERANGE" "One of the endpoints in a range expression was invalid." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ESPACE" "@code{regcomp} ran out of memory." "@end table" "" "@node Flags for POSIX Regexps, Matching POSIX Regexps, POSIX Regexp Compilation, Posix Entry Points" "@section Flags for POSIX Regular Expressions" "" "These are the bit flags that you can use in the @var{cflags} operand when" "compiling a regular expression with @code{regcomp}." " " "@table @code" "@comment regex.h" "@comment POSIX.2" "@item REG_EXTENDED" "Treat the pattern as an extended regular expression, rather than as a" "basic regular expression." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ICASE" "Ignore case when matching letters." "" "@comment regex.h" "@comment POSIX.2" "@item REG_NOSUB" "Don't bother storing the contents of the @var{matches-ptr} array." "" "@comment regex.h" "@comment POSIX.2" "@item REG_NEWLINE" "Treat a newline in @var{string} as dividing @var{string} into multiple" "lines, so that @samp{$} can match before the newline and @samp{^} can" "match after. Also, don't permit @samp{.} to match a newline, and don't" "permit @samp{[^@dots{}]} to match a newline." "" "Otherwise, newline acts like any other ordinary character." "@end table" "" "@node Matching POSIX Regexps, Regexp Subexpressions, Flags for POSIX Regexps, Posix Entry Points" "@section Matching a Compiled POSIX Regular Expression" "" "Once you have compiled a regular expression, as described in @ref{POSIX" "Regexp Compilation}, you can match it against strings using" "@code{regexec}. A match anywhere inside the string counts as success," "unless the regular expression contains anchor characters (@samp{^} or" "@samp{$})." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun int regexec (regex_t *@var{compiled}, char *@var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr} @t{[]}, int @var{eflags})" "@deftypefunx int regnexec (regex_t *@var{compiled}, int len, char *@var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr} @t{[]}, int @var{eflags})" "This function tries to match the compiled regular expression" "@code{*@var{compiled}} against @var{string}." "" "@code{regexec} returns @code{0} if the regular expression matches;" "otherwise, it returns a nonzero value. See the table below for" "what nonzero values mean. You can use @code{regerror} to produce an" "error message string describing the reason for a nonzero value; " "see @ref{Regexp Cleanup}." "" "The parameter @var{string} points to the text to search. When using" "@code{regexec}, @var{string} must be 0-terminated. When using" "@code{regnexec}, @var{string} must be @var{len} characters long." "" "@code{regnexec} is not a standard function; strictly POSIX programs" "should avoid using it." "" "The argument @var{eflags} is a word of bit flags that enable various" "options." "" "If you want to get information about what part of @var{string} actually" "matched the regular expression or its subexpressions, use the arguments" "@var{matchptr} and @var{nmatch}. Otherwise, pass @code{0} for " "@var{nmatch}, and @code{NULL} for @var{matchptr}. @xref{Regexp" "Subexpressions}." "@end deftypefun" "" "You must match the regular expression with the same set of current" "locales that were in effect when you compiled the regular expression." "" "The function @code{regexec} accepts the following flags in the" "@var{eflags} argument:" "" "@table @code " "@comment regex.h" "@comment POSIX.2" "@item REG_NOTBOL" "Do not regard the beginning of the specified string as the beginning of" "a line; more generally, don't make any assumptions about what text might" "precede it." "" "@comment regex.h" "@comment POSIX.2" "@item REG_NOTEOL" "Do not regard the end of the specified string as the end of a line; more" "generally, don't make any assumptions about what text might follow it." "@end table" "" "Here are the possible nonzero values that @code{regexec} can return:" "" "@table @code" "@comment regex.h" "@comment POSIX.2" "@item REG_NOMATCH" "The pattern didn't match the string. This isn't really an error." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ESPACE" "@code{regexec} ran out of memory." "@end table" "" "@node Regexp Subexpressions, Subexpression Complications, Matching POSIX Regexps, Posix Entry Points" "@section Match Results with Subexpressions" "" "When @code{regexec} matches parenthetical subexpressions of" "@var{pattern}, it records which parts of @var{string} they match. It" "returns that information by storing the offsets into an array whose" "elements are structures of type @code{regmatch_t}. The first element of" "the array (index @code{0}) records the part of the string that matched" "the entire regular expression. Each other element of the array records" "the beginning and end of the part that matched a single parenthetical" "subexpression." "" "@comment regex.h" "@comment POSIX.2" "@deftp {Data Type} regmatch_t" "This is the data type of the @var{matcharray} array that you pass to" "@code{regexec}. It containes two structure fields, as follows:" "" "@table @code" "@item rm_so" "The offset in @var{string} of the beginning of a substring. Add this" "value to @var{string} to get the address of that part." "" "@item rm_eo" "The offset in @var{string} of the end of the substring." "@end table" "@end deftp" "" "@comment regex.h" "@comment POSIX.2" "@deftp {Data Type} regoff_t" "@code{regoff_t} is an alias for another signed integer type." "The fields of @code{regmatch_t} have type @code{regoff_t}." "@end deftp" "" "The @code{regmatch_t} elements correspond to subexpressions" "positionally; the first element (index @code{1}) records where the first" "subexpression matched, the second element records the second" "subexpression, and so on. The order of the subexpressions is the order" "in which they begin." "" "When you call @code{regexec}, you specify how long the @var{matchptr}" "array is, with the @var{nmatch} argument. This tells @code{regexec} how" "many elements to store. If the actual regular expression has more than" "@var{nmatch} subexpressions, then you won't get offset information about" "the rest of them. But this doesn't alter whether the pattern matches a" "particular string or not." "" "If you don't want @code{regexec} to return any information about where" "the subexpressions matched, you can either supply @code{0} for" "@var{nmatch}, or use the flag @code{REG_NOSUB} when you compile the" "pattern with @code{regcomp}." "" "@node Subexpression Complications, Regexp Cleanup, Regexp Subexpressions, Posix Entry Points" "@section Complications in Subexpression Matching" "" "Sometimes a subexpression matches a substring of no characters. This" "happens when @samp{f\\(o*\\)} matches the string @samp{fum}. (It really" "matches just the @samp{f}.) In this case, both of the offsets identify" "the point in the string where the null substring was found. In this" "example, the offsets are both @code{1}." "" "Sometimes the entire regular expression can match without using some of" "its subexpressions at all---for example, when @samp{ba\\(na\\)*} matches the" "string @samp{ba}, the parenthetical subexpression is not used. When" "this happens, @code{regexec} stores @code{-1} in both fields of the" "element for that subexpression." "" "Sometimes matching the entire regular expression can match a particular" "subexpression more than once---for example, when @samp{ba\\(na\\)*}" "matches the string @samp{bananana}, the parenthetical subexpression" "matches three times. When this happens, @code{regexec} usually stores" "the offsets of the last part of the string that matched the" "subexpression. In the case of @samp{bananana}, these offsets are" "@code{6} and @code{8}." "" "But the last match is not always the one that is chosen. It's more" "accurate to say that the last @emph{opportunity} to match is the one" "that takes precedence. What this means is that when one subexpression" "appears within another, then the results reported for the inner" "subexpression reflect whatever happened on the last match of the outer" "subexpression. For an example, consider @samp{\\(ba\\(na\\)*s \\)*} matching" "the string @samp{bananas bas }. The last time the inner expression" "actually matches is near the end of the first word. But it is " "@emph{considered} again in the second word, and fails to match there." "@code{regexec} reports nonuse of the ``na'' subexpression." "" "Another place where this rule applies is when the regular expression" "@w{@samp{\\(ba\\(na\\)*s \\|nefer\\(ti\\)* \\)*}} matches @samp{bananas nefertiti}." "The ``na'' subexpression does match in the first word, but it doesn't" "match in the second word because the other alternative is used there." "Once again, the second repetition of the outer subexpression overrides" "the first, and within that second repetition, the ``na'' subexpression" "is not used. So @code{regexec} reports nonuse of the ``na''" "subexpression." "" "@node Regexp Cleanup, , Subexpression Complications, Posix Entry Points" "@section POSIX Regexp Matching Cleanup" "" "When you are finished using a compiled regular expression, you can" "free the storage it uses by calling @code{regfree}." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun void regfree (regex_t *@var{compiled})" "Calling @code{regfree} frees all the storage that @code{*@var{compiled}}" "points to. This includes various internal fields of the @code{regex_t}" "structure that aren't documented in this manual." "" "@code{regfree} does not free the object @code{*@var{compiled}} itself." "@end deftypefun" "" "You should always free the space in a @code{regex_t} structure with" "@code{regfree} before using the structure to compile another regular" "expression." "" "When @code{regcomp} or @code{regexec} reports an error, you can use" "the function @code{regerror} to turn it into an error message string." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun size_t regerror (int @var{errcode}, regex_t *@var{compiled}, char *@var{buffer}, size_t @var{length})" "This function produces an error message string for the error code" "@var{errcode}, and stores the string in @var{length} bytes of memory" "starting at @var{buffer}. For the @var{compiled} argument, supply the" "same compiled regular expression structure that @code{regcomp} or" "@code{regexec} was working with when it got the error. Alternatively," "you can supply @code{NULL} for @var{compiled}; you will still get a" "meaningful error message, but it might not be as detailed." "" "If the error message can't fit in @var{length} bytes (including a" "terminating null character), then @code{regerror} truncates it." "The string that @code{regerror} stores is always null-terminated" "even if it has been truncated." "" "The return value of @code{regerror} is the minimum length needed to" "store the entire error message. If this is less than @var{length}, then" "the error message was not truncated, and you can use it. Otherwise, you" "should call @code{regerror} again with a larger buffer." "" "Here is a function which uses @code{regerror}, but always dynamically" "allocates a buffer for the error message:" "" "@smallexample" "char *get_regerror (int errcode, regex_t *compiled)" "@{" " size_t length = regerror (errcode, compiled, NULL, 0);" " char *buffer = xmalloc (length);" " (void) regerror (errcode, compiled, buffer, length);" " return buffer;" "@}" "@end smallexample" "@end deftypefun" "" "@node Beyond POSIX, Rx Theory, Posix Entry Points, Top" "@chapter Beyond POSIX" "" "This section is not finished documentation, but rather a collection of" "pointers towards some of the interesting, non-standard features of Rx." "" "@section New Regexp Operators" "" "Rx supports some unusual regexp syntax." "" "@code{[[:cut N:]]} sets @code{pmatch[0].final_tag} to N and causes the" "matching to stop instantly. If N is 0, the overall match fails," "otherwise it succeeds." "" "@code{[[:(:]] ... [[:):]]} is just like @code{\\( ... \\)} except that in" "the first case, no pmatch entries are changed, and the subexpression is" "not counted in the numbering of parenthesized subexpressions." "" "@code{[[:(:]] ... [[:):]]} can be used when you do not need to know" "where a subexpression matched but are only using parentheses to effect" "the parsing of the regexp. " "" "There are two reasons to use @code{[[:(:]] ... [[:):]]}:" "" "1. regexec will run faster." "" "2. Currently, only 8 backreferencable subexpressions are supported:" "@code{\\1 .. \\9}. Using @code{[[:(:]] ... [[:):]]} is a way to conserve" "backreferencable subexpression names in an expression with many" "parentheses." "" "@section New POSIX Functions" "" "@code{regncomp} and @code{regnexec} are non-standard generalizations of" "@code{regcomp} and @code{regexec}." "" "@section Tuning POSIX performance" "" "Two mysterious parmaters can be used to trade-off performance and" "memory use." "" "At compile-time they are @code{RX_DEFAULT_DFA_CACHE_SIZE} and" "@code{RX_DEFAULT_NFA_DELAY}. " "" "If you want to mess with these (I generally don't advise it), I suggest" "experimenting for your particular application/memory situation; frob" "these by powers of two and try out the results on what you expect will" "be typical regexp workloads." "" "You can also set those parameters at run-time (before calling any regexp" "functions) by tweaking the corresponding variables:" "" "@code{rx_default_cache->bytes_allowed}" "" "and" "" "@code{rx_basic_unfaniverse_delay}" "" "" "" "@section POSIX stream-style interface" "" "@code{rx_make_solutions}, @code{rx_next_solution}, and" "@code{rx_free_solutions} are a lower level alternative to the posix" "functions. Using those functions, you can compare a compiled regexp to" "a string that is not contiguous in memory or even a string that is not" "entirely in memory at any one time." "" "The code in rxposix.c points out how those functions are used." "" "" "@section DFAs Directly" "" "If you are only interested in pure regular expressions (no pmatch data," "no backreferences, and no counted subexpressions), you can parse a" "regexp using @code{rx_parse}, convert it to an nfa using @code{rx_unfa}," "and run the dfa using @code{rx_init_system}, @code{rx_advance_to_final}," "and @code{rx_terminate_system}. The dfa Scheme primitives in" "@file{rgx.c} may provide some guide." "" "@node Rx Theory, , Beyond POSIX, Top" "@chapter Rx Theory" "@cindex Rx Theory" "" "There are two match algorithms. One is for truly regular regexps (those" "that can be reduced to a dfa). The other is for non-regular regexps." "" "The dfa algorithm implements the idea suggested in @cite{Compilers} by" "Aho, Sethi and Ullman:" "" "@quotation" "[One] approach [to pattern matching regular expressions] is to use a" "DFA, but avoid constructing all of the transition table by using a" "technique called \"lazy transition evaluation\". Here, transitions are" "computed at run time [when] actually needed. [T]ransitions are" "stored in a cache. [....] If the cache becomes full, we can erase some" "previously computed transition to make room for the new transition." "@end quotation" "" "The implementation in Rx is generalized from that, but the above" "description covers what is used for Posix patterns. " "" "The non-dfa algorithm implements a \"recursive decomposition\" technique" "described in email by Henry Spencer. For a given pattern, this" "algorithm first checks to see if a simpler, superset language," "DFA-pattern matches. If it does, then this algorithm does the" "detail-work to see if the non-DFA pattern matches." "\\input texinfo @c -*-texinfo-*-" "@c %**start of header" "@setfilename rx.info" "@settitle Rx" "@setchapternewpage odd" "@c %**end of header" "" "@c This title page illustrates only one of the" "@c two methods of forming a title page." "" "@titlepage" "@title Rx" "@author Tom Lord" "" "@center except the chapter \"Posix Entry Points\" " "@center from @emph{The GNU C Library} reference manual" "@center by Sandra Loosemore" "@center with" "@center Richard M. Stallman, Roland McGrath, and Andrew Oram" "" "@c The following two commands" "@c start the copyright page." "@page" "@vskip 0pt plus 1filll" "Copyright @copyright{} 1995 Cygnus Support" "" "except the chapter \"Posix Entry Points\" which is:" "" "Copyright @copyright{} 1995 Free Software Foundation, Inc." "" "Permission is granted to make and distribute verbatim copies of" "this manual provided the copyright notice and this permission notice" "are preserved on all copies." "" "Permission is granted to copy and distribute modified versions of this" "manual under the conditions for verbatim copying, provided that the entire" "resulting derived work is distributed under the terms of a permission" "notice identical to this one." "" "Permission is granted to copy and distribute translations of this manual" "into another language, under the above conditions for modified versions," "except that this permission notice may be stated in a translation approved" "by the author." "" "@end titlepage" "" "@node Top, Copying, (dir), (dir)" "@top Rx" "" "This document describes Rx." "" "@menu" "* Copying:: Sharing is good." "* Overview:: Fnord" "* Posix Basic Regular Expressions:: A popular regexp syntax." "* Posix Entry Points:: The POSIX way to regexp." "* Beyond POSIX:: Hints about cool features." "* Rx Theory:: Hints about how it works." "@end menu" "" "@node Copying, Overview, Top, Top" "@chapter Copying" "" "@center Copyright (C) 1996" "@center Tom Lord" "@center Berkeley, CA USA" "" "@center except portions of \"POSIX Regex Functions\" which are" "@center Copyright (C) 1995" "@center Free Software Foundation, Inc." "" "@noindent" "Permission to use, copy, modify, distribute, and sell this software and" "its documentation for any purpose is hereby granted without fee," "provided that the above copyright notice appear in all copies and that" "both that copyright notice and this permission notice appear in" "supporting documentation." "" "@center NO WARRANTY" "" "@noindent" "BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR" "THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN" "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES" "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER" "EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED" "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE" "ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH" "YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL" "NECESSARY SERVICING, REPAIR OR CORRECTION." "" "@noindent" "IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING" "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR" "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR" "DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL" "DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM" "(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED" "INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF" "THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR" "OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES." "" "@node Overview, Posix Basic Regular Expressions, Copying, Top" "@chapter Overview" "" "Nothing to say here, yet." "" "@node Posix Basic Regular Expressions, Posix Entry Points, Overview, Top" "@chapter Posix Basic Regular Expressions" "" "The Posix Basic Regular Expression language is a notation for describing" "textual patterns. Regexps are typically used by comparing them to a" "string to see if that string matches the pattern, or by searching within" "a string for a substring that matches." "" "This chapter introduces the Posix regexp notation. This is not a formal" "or precise definition of Posix regexps -- it is an intuitive and" "hopefully expository description of them." "" "@menu" "* An Introduction to Regexps:: " "* Literal Regexps:: " "* Character Sets:: " "* Subexpressions:: " "* Repeated Subexpressions:: " "* Optional Subexpressions:: " "* Counted Subexpressions:: " "* Alternative Subexpressions:: " "* Backreferences:: " "* A Summary of Regexp Syntax:: " "* Ambiguous Patterns:: " "@end menu" "" "" "@node An Introduction to Regexps, Literal Regexps, Posix Basic Regular Expressions, Posix Basic Regular Expressions" "@section An Introduction to Regexps" "" "In the simplest cases, a regexp is just a literal string that must" "match exactly. For example, the pattern:" "" "@example" "regexp" "@end example" "" "matches the string \"regexp\" and no others." "" "Some characters have a special meaning when they occur in a regexp." "They aren't matched literally as in the previous example, but instead" "denote a more general pattern. For example, the character @code{*}" "is used to indicate that the preceeding element of a regexp may be" "repeated 0, 1, or more times. In the pattern:" "" "@example" "smooo*th" "@end example" "" "the @code{*} indicates that the preceeding @code{o} can be repeated 0 or" "more times. So the pattern matches:" "" "@example" "smooth" "smoooth" "smooooth" "smoooooth" "..." "@end example" "" "Suppose you want to write a pattern that literally matches a special" "character like @code{*} -- in other words, you don't want to @code{*} to" "indicate a permissible repetition, but to match @code{*} literally. This" "is accomplished by quoting the special character with a backslash. " "The pattern:" "" "@example" "smoo\\*th" "@end example" "" "matches the string:" "" "@example" "smoo*th" "@end example" "" "" "and no other strings." "" "In five cases, the pattern is reversed -- a backslash makes the" "character special instead of making a special character normal. The" "characters @code{+}, @code{?}, @code{|}, @code{(}, and @code{)} are" "normal but the sequences @code{\\+}, @code{\\?}, @code{\\|}, @code{\\(}, and" "@code{\\)} are special (their meaning is described later)." "" "The remaining sections of this chapter introduce and explain the various" "special characters that can occur in regexps." "" "@node Literal Regexps, Character Sets, An Introduction to Regexps, Posix Basic Regular Expressions" "@section Literal Regexps" "" "A literal regexp is a string which contains no special characters." "A literal regexp matches an identical string, but no other characters." "For example:" "" "@example" "literally" "@end example" "" "matches" "" "@example" "literally" "@end example" "" "and nothing else." "" "Generally, whitespace characters, numbers, and letters are not special." "Some punctuation characters are special and some are not (the syntax" "summary at the end of this chapter makes a convenient reference for" "which characters are special and which aren't)." "" "" "@node Character Sets, Subexpressions, Literal Regexps, Posix Basic Regular Expressions" "@section Character Sets" "" "This section introduces the special characters @code{.} and @code{[}." "" "@code{.} matches any character except the NULL character. For example:" "" "@example" "p.ck" "@end example" "" "matches" "" "@example" "pick" "pack" "puck" "pbck" "pcck" "p.ck" "" "..." "@end example" "" "" "@code{[} begins a @dfn{character set}. A character set is similar to" "@code{.} in that it matches not a single, literal character, but any" "of a set of characters. @code{[} is different from @code{.} in that" "with @code{[}, you define the set of characters explicitly." "" "There are three basic forms a character set can take." "" "In the first form, the character set is spelled out:" "" "@example" "[<cset-spec>] -- every character in <cset-spec> is in the set." "@end example" "" "In the second form, the character set indicated is the negation of" "a character set is explicitly spelled out:" "" "@example" "[^<cset-spec>] -- every character *not* in <cset-spec> is in the set." "@end example" "" "A @code{<cset-spec>} is more or less an explicit enumeration of a set" "of characters. It can be written as a string of individual characters:" "" "@example" "[aeiou]" "@end example" "" "or as a range of characters:" "" "@example" "[0-9]" "@end example" "" "These two forms can be mixed:" "" "@example" "[A-za-z0-9_$]" "@end example" "" "Note that special regexp characters (such as @code{*}) are @emph{not}" "special within a character set. @code{-}, as illustrated above," "@emph{is} special, except, as illustrated below, when it is the first" "character mentioned." "" "This is a four-character set:" "" "@example" "[-+*/]" "@end example" "" "The third form of a character set makes use of a pre-defined \"character" "class\":" "" "@example" "[[:class-name:]] -- every character described by class-name is in the set." "@end example" "" "The supported character classes are:" "" "@example" "alnum - the set of alpha-numeric characters" "alpha - the set of alphabetic characters" "blank - tab and space" "cntrl - the control characters" "digit - decimal digits" "graph - all printable characters except space" "lower - lower case letters" "print - the \"printable\" characters" "punct - punctuation" "space - whitespace characters" "upper - upper case letters" "xdigit - hexidecimal digits" "@end example" "" "Finally, character class sets can also be inverted:" "" "@example" "[^[:space:]] - all non-whitespace characters" "@end example" "" "Character sets can be used in a regular expression anywhere a literal" "character can." "" "@node Subexpressions, Repeated Subexpressions, Character Sets, Posix Basic Regular Expressions" "@section Subexpressions" "" "A subexpression is a regular expression enclosed in @code{\\(} and" "@code{\\)}. A subexpression can be used anywhere a single character or" "character set can be used." "" "Subexpressions are useful for grouping regexp constructs. For example," "the repeat operator, @code{*}, usually applies to just the preceeding" "character. Recall that:" "" "@example" "smooo*th" "@end example" "" "matches" "" "@example" "smooth" "smoooth" "..." "@end example" "" "" "Using a subexpression, we can apply @code{*} to a longer string:" "" "@example" "banan\\(an\\)*a" "@end example" "" "matches" "" "@example" "banana" "bananana" "banananana" "..." "@end example" "" "Subexpressions also have a special meaning with regard to backreferences" "and substitutions (see @xref{Backreferences})." "" "" "@node Repeated Subexpressions, Optional Subexpressions, Subexpressions, Posix Basic Regular Expressions" "@section Repeated Subexpressions" "" "" "@code{*} is the repeat operator. It applies to the preceeding" "character, character set, subexpression or backreference. It indicates" "that the preceeding element can be matched 0 or more times:" "" "@example" "bana\\(na\\)*" "@end example" "" "matches" "" "@example" "bana" "banana" "bananana" "banananana" "..." "@end example" "" "" "" "@code{\\+} is similar to @code{*} except that @code{\\+} requires the" "preceeding element to be matched at least once. So while:" "" "@example" "bana\\(na\\)*" "@end example" "" "matches" "" "@example" "bana" "@end example" "" "@example" "bana(na\\)\\+" "@end example" "" "does not. Both match " "" "@example" "banana" "bananana" "banananana" "..." "@end example" "" "Thus, @code{bana\\(na\\)+} is short-hand for @code{banana\\(na\\)*}." "" "" "@node Optional Subexpressions, Counted Subexpressions, Repeated Subexpressions, Posix Basic Regular Expressions" "@section Optional Subexpressions" "" "@code{\\?} indicates that the preceeding character, character set, or" "subexpression is optional. It is permitted to match, or to be skipped:" "" "@example" "CSNY\\?" "@end example" "" "matches both" "" "@example" "CSN" "@end example" "" "and " "" "@example" "CSNY" "@end example" "" "" "@node Counted Subexpressions, Alternative Subexpressions, Optional Subexpressions, Posix Basic Regular Expressions" "@section Counted Subexpressions" "" "An interval expression, @code{@{m,n@}} where @code{m} and @code{n} are" "non-negative integers with @code{n >= m}, applies to the preceeding" "character, character set, subexpression or backreference. It indicates" "that the preceeding element must match at least @code{m} times and may" "match as many as @code{n} times." "" "For example:" "" "@example" "c\\([ad]\\)@{1,4@}" "@end example" "" "matches" "" "@example" "car" "cdr" "caar" "cdar" "..." "caaar" "cdaar" "..." "cadddr" "cddddr" "@end example" "" "" "" "@node Alternative Subexpressions, Backreferences, Counted Subexpressions, Posix Basic Regular Expressions" "@section Alternative Subexpressions" "" "An alternative is written:" "" "@example" "regexp-1\\|regexp-2\\|regexp-3\\|..." "@end example" "" "It matches anything matched by some @code{regexp-n}. For example:" "" "@example" "Crosby, Stills, \\(and Nash\\|Nash, and Young\\)" "@end example" "" "matches" "" "@example" "Crosby, Stills, and Nash" "@end example" "" "and" "" "@example" "Crosby, Stills, Nash, and Young" "@end example" "" "" "@node Backreferences, A Summary of Regexp Syntax, Alternative Subexpressions, Posix Basic Regular Expressions" "@section Backreferences, Extractions and Substitutions" "" "A backreference is written @code{\\n} where @code{n} is some single digit" "other than 0. To be a valid backreference, there must be at least" "@code{n} parenthesized subexpressions in the pattern prior to the" "backreference." "" "A backreference matches a literal copy of whatever was matched by the" "corresponding subexpression. For example," "" "@example" "\\(.*\\)-\\1" "@end example" "" "matches:" "" "@example" "go-go" "ha-ha" "wakka-wakka" "..." "@end example" "" "In some applications, subexpressions are used to extract substrings." "For example, Emacs has the functions @code{match-beginnning} and" "@code{match-end} which report the positions of strings matched by" "subexpressions. These functions use the same numbering scheme for" "subexpressions as backreferences, with the additional rule that" "subexpression 0 is defined to be the whole regexp." "" "In some applications, subexpressions are used in string substitution." "This again uses the backreference numbering scheme. For example, this sed" "command:" "" "@example" "s/From:.*<\\(.*\\)>/To: \\1/" "@end example" "" "first matches the line:" "" "@example" "From: Joe Schmoe <schmoe@@uspringfield.edu>" "@end example" "" "when it does, subexpression 1 matches \"schmoe@@uspringfield.edu\"." "The command replaces the matched line with \"To: \\1\" after doing" "subexpression substitution on it to get:" "" "@example" "To: schmoe@@uspringfield.edu" "@end example" "" "" "@node A Summary of Regexp Syntax, Ambiguous Patterns, Backreferences, Posix Basic Regular Expressions" "@section A Summary of Regexp Syntax" "" "In summary, regexps can be:" "" "@code{abcd} -- matching a string literally" "" "@code{.} -- matching everything except NULL" "" "@code{[a-z_?]}, @code{^[a-z_?]}, @code{[[:alpha:]]} and" "@code{[^[:alpha:]]} -- matching character sets" "" "@code{\\(subexp\\)} -- grouping an expression into a subexpression." "" "@code{\\n} -- match a copy of whatever was matched by the nth subexpression." "" "The following special characters and sequences can be applied to a" "character, character set, subexpression, or backreference:" "" "@code{*} -- repeat the preceeding element 0 or more times." "" "@code{\\+} -- repeat the preceeding element 1 or more times." "" "@code{\\?} -- match the preceeding element 0 or 1 time." "" "@code{@{m,n@}} -- match the preceeding element at least @code{m}, and as" "many as @code{n} times." "" "@code{regexp-1\\|regexp-2\\|..} -- match any regexp-n." "" "A special character, like @code{.} or @code{*} can be made into a literal" "character by prefixing it with @code{\\}." "" "A special sequence, like @code{\\+} or @code{\\?} can be made into a" "literal character by dropping the @code{\\}." "" "" "@node Ambiguous Patterns, , A Summary of Regexp Syntax, Posix Basic Regular Expressions" "@section Ambiguous Patterns" "" "Sometimes a regular expression appears to be ambiguous. For example, suppose" "we compare the pattern:" "" "@example" "begin\\|beginning" "@end example" "" "to the string" "" "@example" "beginning" "@end example" "" "either just the first 5 characters will match, or the whole string will match." "" "In every case like this, the longer match is preferred. The whole" "string will match." "" "Sometimes there is ambiguity not about how many characters to match, but" "where the subexpressions occur within the match. This can effect" "extraction functions like Emacs' @code{match-beginning} or rewrite" "functions like sed's @code{s} command. For example, consider matching" "the pattern:" "" "@example" "b\\(\\[^q]*\\)\\(ing\\)?" "@end example" "" "against the string" "" "@example" "beginning" "@end example" "" "One possibility is that the first subexpression matches \"eginning\" and" "the second is skipped. Another possibility is that the first" "subexpression matches \"eginn\" and the second matches \"ing\"." "" "The rule is that consistant with matching as many characters as " "possible, the length of lower numbered subexpressions is maximized" "in preference to maximizing the length of later subexpressions." "" "In the case of the above example, the two possible matches are equal in" "overall length. Therefore, it comes down to maximizing the" "lower-numbered subexpression, \\1. The correct answer is that \\1 matches" "\"eginning\" and \\2 is skipped." "" "@node Posix Entry Points, Beyond POSIX, Posix Basic Regular Expressions, Top" "@chapter Posix Entry Points" "" "This section is excerpted from @emph{The GNU C Library} reference manual" "by Sandra Loosemore with Richard M. Stallman, Roland McGrath, and Andrew" "Oram." "" "The GNU C library supports the standard POSIX.2 interface. Programs" "using this interface should include the header file @file{rxposix.h}." "" "@menu" "* POSIX Regexp Compilation:: Using @code{regcomp} to prepare to match." "* Flags for POSIX Regexps:: Syntax variations for @code{regcomp}." "* Matching POSIX Regexps:: Using @code{regexec} to match the compiled" " pattern that you get from @code{regcomp}." "* Regexp Subexpressions:: Finding which parts of the string were matched." "* Subexpression Complications:: Find points of which parts were matched." "* Regexp Cleanup:: Freeing storage; reporting errors." "@end menu" "" "@node POSIX Regexp Compilation, Flags for POSIX Regexps, Posix Entry Points, Posix Entry Points" "@section POSIX Regular Expression Compilation" "" "Before you can actually match a regular expression, you must" "@dfn{compile} it. This is not true compilation---it produces a special" "data structure, not machine instructions. But it is like ordinary" "compilation in that its purpose is to enable you to ``execute'' the" "pattern fast. (@xref{Matching POSIX Regexps}, for how to use the" "compiled regular expression for matching.)" "" "There is a special data type for compiled regular expressions:" "" "@comment regex.h" "@comment POSIX.2" "@deftp {Data Type} regex_t" "This type of object holds a compiled regular expression." "It is actually a structure. It has just one field that your programs" "should look at:" "" "@table @code" "@item re_nsub" "This field holds the number of parenthetical subexpressions in the" "regular expression that was compiled." "@end table" "" "There are several other fields, but we don't describe them here, because" "only the functions in the library should use them." "@end deftp" "" "After you create a @code{regex_t} object, you can compile a regular" "expression into it by calling @code{regcomp}." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun int regcomp (regex_t *@var{compiled}, const char *@var{pattern}, int @var{cflags})" "@deftypefunx int regncomp (regex_t *@var{compiled}, int len, const char *@var{pattern}, int @var{cflags})" "The function @code{regcomp} ``compiles'' a regular expression into a" "data structure that you can use with @code{regexec} to match against a" "string. The compiled regular expression format is designed for" "efficient matching. @code{regcomp} stores it into @code{*@var{compiled}}." "" "The parameter @var{pattern} points to the regular expression to be" "compiled. When using @code{regcomp}, @var{pattern} must be" "0-terminated. When using @code{regncomp}, @var{pattern} must be" "@var{len} characters long." "" "@code{regncomp} is not a standard function; strictly POSIX programs" "should avoid using it." "" "It's up to you to allocate an object of type @code{regex_t} and pass its" "address to @code{regcomp}." "" "The argument @var{cflags} lets you specify various options that control" "the syntax and semantics of regular expressions. @xref{Flags for POSIX" "Regexps}." "" "If you use the flag @code{REG_NOSUB}, then @code{regcomp} omits from" "the compiled regular expression the information necessary to record" "how subexpressions actually match. In this case, you might as well" "pass @code{0} for the @var{matchptr} and @var{nmatch} arguments when" "you call @code{regexec}." "" "If you don't use @code{REG_NOSUB}, then the compiled regular expression" "does have the capacity to record how subexpressions match. Also," "@code{regcomp} tells you how many subexpressions @var{pattern} has, by" "storing the number in @code{@var{compiled}->re_nsub}. You can use that" "value to decide how long an array to allocate to hold information about" "subexpression matches." "" "@code{regcomp} returns @code{0} if it succeeds in compiling the regular" "expression; otherwise, it returns a nonzero error code (see the table" "below). You can use @code{regerror} to produce an error message string" "describing the reason for a nonzero value; see @ref{Regexp Cleanup}." "" "@end deftypefun" "" "Here are the possible nonzero values that @code{regcomp} can return:" "" "@table @code" "@comment regex.h" "@comment POSIX.2" "@item REG_BADBR" "There was an invalid @samp{\\@{@dots{}\\@}} construct in the regular" "expression. A valid @samp{\\@{@dots{}\\@}} construct must contain either" "a single number, or two numbers in increasing order separated by a" "comma." "" "@comment regex.h" "@comment POSIX.2" "@item REG_BADPAT" "There was a syntax error in the regular expression." "" "@comment regex.h" "@comment POSIX.2" "@item REG_BADRPT" "A repetition operator such as @samp{?} or @samp{*} appeared in a bad" "position (with no preceding subexpression to act on)." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ECOLLATE" "The regular expression referred to an invalid collating element (one not" "defined in the current locale for string collation). " "" "@comment regex.h" "@comment POSIX.2" "@item REG_ECTYPE" "The regular expression referred to an invalid character class name." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EESCAPE" "The regular expression ended with @samp{\\}." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ESUBREG" "There was an invalid number in the @samp{\\@var{digit}} construct." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EBRACK" "There were unbalanced square brackets in the regular expression." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EPAREN" "An extended regular expression had unbalanced parentheses," "or a basic regular expression had unbalanced @samp{\\(} and @samp{\\)}." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EBRACE" "The regular expression had unbalanced @samp{\\@{} and @samp{\\@}}." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ERANGE" "One of the endpoints in a range expression was invalid." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ESPACE" "@code{regcomp} ran out of memory." "@end table" "" "@node Flags for POSIX Regexps, Matching POSIX Regexps, POSIX Regexp Compilation, Posix Entry Points" "@section Flags for POSIX Regular Expressions" "" "These are the bit flags that you can use in the @var{cflags} operand when" "compiling a regular expression with @code{regcomp}." " " "@table @code" "@comment regex.h" "@comment POSIX.2" "@item REG_EXTENDED" "Treat the pattern as an extended regular expression, rather than as a" "basic regular expression." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ICASE" "Ignore case when matching letters." "" "@comment regex.h" "@comment POSIX.2" "@item REG_NOSUB" "Don't bother storing the contents of the @var{matches-ptr} array." "" "@comment regex.h" "@comment POSIX.2" "@item REG_NEWLINE" "Treat a newline in @var{string} as dividing @var{string} into multiple" "lines, so that @samp{$} can match before the newline and @samp{^} can" "match after. Also, don't permit @samp{.} to match a newline, and don't" "permit @samp{[^@dots{}]} to match a newline." "" "Otherwise, newline acts like any other ordinary character." "@end table" "" "@node Matching POSIX Regexps, Regexp Subexpressions, Flags for POSIX Regexps, Posix Entry Points" "@section Matching a Compiled POSIX Regular Expression" "" "Once you have compiled a regular expression, as described in @ref{POSIX" "Regexp Compilation}, you can match it against strings using" "@code{regexec}. A match anywhere inside the string counts as success," "unless the regular expression contains anchor characters (@samp{^} or" "@samp{$})." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun int regexec (regex_t *@var{compiled}, char *@var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr} @t{[]}, int @var{eflags})" "@deftypefunx int regnexec (regex_t *@var{compiled}, int len, char *@var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr} @t{[]}, int @var{eflags})" "This function tries to match the compiled regular expression" "@code{*@var{compiled}} against @var{string}." "" "@code{regexec} returns @code{0} if the regular expression matches;" "otherwise, it returns a nonzero value. See the table below for" "what nonzero values mean. You can use @code{regerror} to produce an" "error message string describing the reason for a nonzero value; " "see @ref{Regexp Cleanup}." "" "The parameter @var{string} points to the text to search. When using" "@code{regexec}, @var{string} must be 0-terminated. When using" "@code{regnexec}, @var{string} must be @var{len} characters long." "" "@code{regnexec} is not a standard function; strictly POSIX programs" "should avoid using it." "" "The argument @var{eflags} is a word of bit flags that enable various" "options." "" "If you want to get information about what part of @var{string} actually" "matched the regular expression or its subexpressions, use the arguments" "@var{matchptr} and @var{nmatch}. Otherwise, pass @code{0} for " "@var{nmatch}, and @code{NULL} for @var{matchptr}. @xref{Regexp" "Subexpressions}." "@end deftypefun" "" "You must match the regular expression with the same set of current" "locales that were in effect when you compiled the regular expression." "" "The function @code{regexec} accepts the following flags in the" "@var{eflags} argument:" "" "@table @code " "@comment regex.h" "@comment POSIX.2" "@item REG_NOTBOL" "Do not regard the beginning of the specified string as the beginning of" "a line; more generally, don't make any assumptions about what text might" "precede it." "" "@comment regex.h" "@comment POSIX.2" "@item REG_NOTEOL" "Do not regard the end of the specified string as the end of a line; more" "generally, don't make any assumptions about what text might follow it." "@end table" "" "Here are the possible nonzero values that @code{regexec} can return:" "" "@table @code" "@comment regex.h" "@comment POSIX.2" "@item REG_NOMATCH" "The pattern didn't match the string. This isn't really an error." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ESPACE" "@code{regexec} ran out of memory." "@end table" "" "@node Regexp Subexpressions, Subexpression Complications, Matching POSIX Regexps, Posix Entry Points" "@section Match Results with Subexpressions" "" "When @code{regexec} matches parenthetical subexpressions of" "@var{pattern}, it records which parts of @var{string} they match. It" "returns that information by storing the offsets into an array whose" "elements are structures of type @code{regmatch_t}. The first element of" "the array (index @code{0}) records the part of the string that matched" "the entire regular expression. Each other element of the array records" "the beginning and end of the part that matched a single parenthetical" "subexpression." "" "@comment regex.h" "@comment POSIX.2" "@deftp {Data Type} regmatch_t" "This is the data type of the @var{matcharray} array that you pass to" "@code{regexec}. It containes two structure fields, as follows:" "" "@table @code" "@item rm_so" "The offset in @var{string} of the beginning of a substring. Add this" "value to @var{string} to get the address of that part." "" "@item rm_eo" "The offset in @var{string} of the end of the substring." "@end table" "@end deftp" "" "@comment regex.h" "@comment POSIX.2" "@deftp {Data Type} regoff_t" "@code{regoff_t} is an alias for another signed integer type." "The fields of @code{regmatch_t} have type @code{regoff_t}." "@end deftp" "" "The @code{regmatch_t} elements correspond to subexpressions" "positionally; the first element (index @code{1}) records where the first" "subexpression matched, the second element records the second" "subexpression, and so on. The order of the subexpressions is the order" "in which they begin." "" "When you call @code{regexec}, you specify how long the @var{matchptr}" "array is, with the @var{nmatch} argument. This tells @code{regexec} how" "many elements to store. If the actual regular expression has more than" "@var{nmatch} subexpressions, then you won't get offset information about" "the rest of them. But this doesn't alter whether the pattern matches a" "particular string or not." "" "If you don't want @code{regexec} to return any information about where" "the subexpressions matched, you can either supply @code{0} for" "@var{nmatch}, or use the flag @code{REG_NOSUB} when you compile the" "pattern with @code{regcomp}." "" "@node Subexpression Complications, Regexp Cleanup, Regexp Subexpressions, Posix Entry Points" "@section Complications in Subexpression Matching" "" "Sometimes a subexpression matches a substring of no characters. This" "happens when @samp{f\\(o*\\)} matches the string @samp{fum}. (It really" "matches just the @samp{f}.) In this case, both of the offsets identify" "the point in the string where the null substring was found. In this" "example, the offsets are both @code{1}." "" "Sometimes the entire regular expression can match without using some of" "its subexpressions at all---for example, when @samp{ba\\(na\\)*} matches the" "string @samp{ba}, the parenthetical subexpression is not used. When" "this happens, @code{regexec} stores @code{-1} in both fields of the" "element for that subexpression." "" "Sometimes matching the entire regular expression can match a particular" "subexpression more than once---for example, when @samp{ba\\(na\\)*}" "matches the string @samp{bananana}, the parenthetical subexpression" "matches three times. When this happens, @code{regexec} usually stores" "the offsets of the last part of the string that matched the" "subexpression. In the case of @samp{bananana}, these offsets are" "@code{6} and @code{8}." "" "But the last match is not always the one that is chosen. It's more" "accurate to say that the last @emph{opportunity} to match is the one" "that takes precedence. What this means is that when one subexpression" "appears within another, then the results reported for the inner" "subexpression reflect whatever happened on the last match of the outer" "subexpression. For an example, consider @samp{\\(ba\\(na\\)*s \\)*} matching" "the string @samp{bananas bas }. The last time the inner expression" "actually matches is near the end of the first word. But it is " "@emph{considered} again in the second word, and fails to match there." "@code{regexec} reports nonuse of the ``na'' subexpression." "" "Another place where this rule applies is when the regular expression" "@w{@samp{\\(ba\\(na\\)*s \\|nefer\\(ti\\)* \\)*}} matches @samp{bananas nefertiti}." "The ``na'' subexpression does match in the first word, but it doesn't" "match in the second word because the other alternative is used there." "Once again, the second repetition of the outer subexpression overrides" "the first, and within that second repetition, the ``na'' subexpression" "is not used. So @code{regexec} reports nonuse of the ``na''" "subexpression." "" "@node Regexp Cleanup, , Subexpression Complications, Posix Entry Points" "@section POSIX Regexp Matching Cleanup" "" "When you are finished using a compiled regular expression, you can" "free the storage it uses by calling @code{regfree}." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun void regfree (regex_t *@var{compiled})" "Calling @code{regfree} frees all the storage that @code{*@var{compiled}}" "points to. This includes various internal fields of the @code{regex_t}" "structure that aren't documented in this manual." "" "@code{regfree} does not free the object @code{*@var{compiled}} itself." "@end deftypefun" "" "You should always free the space in a @code{regex_t} structure with" "@code{regfree} before using the structure to compile another regular" "expression." "" "When @code{regcomp} or @code{regexec} reports an error, you can use" "the function @code{regerror} to turn it into an error message string." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun size_t regerror (int @var{errcode}, regex_t *@var{compiled}, char *@var{buffer}, size_t @var{length})" "This function produces an error message string for the error code" "@var{errcode}, and stores the string in @var{length} bytes of memory" "starting at @var{buffer}. For the @var{compiled} argument, supply the" "same compiled regular expression structure that @code{regcomp} or" "@code{regexec} was working with when it got the error. Alternatively," "you can supply @code{NULL} for @var{compiled}; you will still get a" "meaningful error message, but it might not be as detailed." "" "If the error message can't fit in @var{length} bytes (including a" "terminating null character), then @code{regerror} truncates it." "The string that @code{regerror} stores is always null-terminated" "even if it has been truncated." "" "The return value of @code{regerror} is the minimum length needed to" "store the entire error message. If this is less than @var{length}, then" "the error message was not truncated, and you can use it. Otherwise, you" "should call @code{regerror} again with a larger buffer." "" "Here is a function which uses @code{regerror}, but always dynamically" "allocates a buffer for the error message:" "" "@smallexample" "char *get_regerror (int errcode, regex_t *compiled)" "@{" " size_t length = regerror (errcode, compiled, NULL, 0);" " char *buffer = xmalloc (length);" " (void) regerror (errcode, compiled, buffer, length);" " return buffer;" "@}" "@end smallexample" "@end deftypefun" "" "@node Beyond POSIX, Rx Theory, Posix Entry Points, Top" "@chapter Beyond POSIX" "" "This section is not finished documentation, but rather a collection of" "pointers towards some of the interesting, non-standard features of Rx." "" "@section New Regexp Operators" "" "Rx supports some unusual regexp syntax." "" "@code{[[:cut N:]]} sets @code{pmatch[0].final_tag} to N and causes the" "matching to stop instantly. If N is 0, the overall match fails," "otherwise it succeeds." "" "@code{[[:(:]] ... [[:):]]} is just like @code{\\( ... \\)} except that in" "the first case, no pmatch entries are changed, and the subexpression is" "not counted in the numbering of parenthesized subexpressions." "" "@code{[[:(:]] ... [[:):]]} can be used when you do not need to know" "where a subexpression matched but are only using parentheses to effect" "the parsing of the regexp. " "" "There are two reasons to use @code{[[:(:]] ... [[:):]]}:" "" "1. regexec will run faster." "" "2. Currently, only 8 backreferencable subexpressions are supported:" "@code{\\1 .. \\9}. Using @code{[[:(:]] ... [[:):]]} is a way to conserve" "backreferencable subexpression names in an expression with many" "parentheses." "" "@section New POSIX Functions" "" "@code{regncomp} and @code{regnexec} are non-standard generalizations of" "@code{regcomp} and @code{regexec}." "" "@section Tuning POSIX performance" "" "Two mysterious parmaters can be used to trade-off performance and" "memory use." "" "At compile-time they are @code{RX_DEFAULT_DFA_CACHE_SIZE} and" "@code{RX_DEFAULT_NFA_DELAY}. " "" "If you want to mess with these (I generally don't advise it), I suggest" "experimenting for your particular application/memory situation; frob" "these by powers of two and try out the results on what you expect will" "be typical regexp workloads." "" "You can also set those parameters at run-time (before calling any regexp" "functions) by tweaking the corresponding variables:" "" "@code{rx_default_cache->bytes_allowed}" "" "and" "" "@code{rx_basic_unfaniverse_delay}" "" "" "" "@section POSIX stream-style interface" "" "@code{rx_make_solutions}, @code{rx_next_solution}, and" "@code{rx_free_solutions} are a lower level alternative to the posix" "functions. Using those functions, you can compare a compiled regexp to" "a string that is not contiguous in memory or even a string that is not" "entirely in memory at any one time." "" "The code in rxposix.c points out how those functions are used." "" "" "@section DFAs Directly" "" "If you are only interested in pure regular expressions (no pmatch data," "no backreferences, and no counted subexpressions), you can parse a" "regexp using @code{rx_parse}, convert it to an nfa using @code{rx_unfa}," "and run the dfa using @code{rx_init_system}, @code{rx_advance_to_final}," "and @code{rx_terminate_system}. The dfa Scheme primitives in" "@file{rgx.c} may provide some guide." "" "@node Rx Theory, , Beyond POSIX, Top" "@chapter Rx Theory" "@cindex Rx Theory" "" "There are two match algorithms. One is for truly regular regexps (those" "that can be reduced to a dfa). The other is for non-regular regexps." "" "The dfa algorithm implements the idea suggested in @cite{Compilers} by" "Aho, Sethi and Ullman:" "" "@quotation" "[One] approach [to pattern matching regular expressions] is to use a" "DFA, but avoid constructing all of the transition table by using a" "technique called \"lazy transition evaluation\". Here, transitions are" "computed at run time [when] actually needed. [T]ransitions are" "stored in a cache. [....] If the cache becomes full, we can erase some" "previously computed transition to make room for the new transition." "@end quotation" "" "The implementation in Rx is generalized from that, but the above" "description covers what is used for Posix patterns. " "" "The non-dfa algorithm implements a \"recursive decomposition\" technique" "described in email by Henry Spencer. For a given pattern, this" "algorithm first checks to see if a simpler, superset language," "DFA-pattern matches. If it does, then this algorithm does the" "detail-work to see if the non-DFA pattern matches." "\\input texinfo @c -*-texinfo-*-" "@c %**start of header" "@setfilename rx.info" "@settitle Rx" "@setchapternewpage odd" "@c %**end of header" "" "@c This title page illustrates only one of the" "@c two methods of forming a title page." "" "@titlepage" "@title Rx" "@author Tom Lord" "" "@center except the chapter \"Posix Entry Points\" " "@center from @emph{The GNU C Library} reference manual" "@center by Sandra Loosemore" "@center with" "@center Richard M. Stallman, Roland McGrath, and Andrew Oram" "" "@c The following two commands" "@c start the copyright page." "@page" "@vskip 0pt plus 1filll" "Copyright @copyright{} 1995 Cygnus Support" "" "except the chapter \"Posix Entry Points\" which is:" "" "Copyright @copyright{} 1995 Free Software Foundation, Inc." "" "Permission is granted to make and distribute verbatim copies of" "this manual provided the copyright notice and this permission notice" "are preserved on all copies." "" "Permission is granted to copy and distribute modified versions of this" "manual under the conditions for verbatim copying, provided that the entire" "resulting derived work is distributed under the terms of a permission" "notice identical to this one." "" "Permission is granted to copy and distribute translations of this manual" "into another language, under the above conditions for modified versions," "except that this permission notice may be stated in a translation approved" "by the author." "" "@end titlepage" "" "@node Top, Copying, (dir), (dir)" "@top Rx" "" "This document describes Rx." "" "@menu" "* Copying:: Sharing is good." "* Overview:: Fnord" "* Posix Basic Regular Expressions:: A popular regexp syntax." "* Posix Entry Points:: The POSIX way to regexp." "* Beyond POSIX:: Hints about cool features." "* Rx Theory:: Hints about how it works." "@end menu" "" "@node Copying, Overview, Top, Top" "@chapter Copying" "" "@center Copyright (C) 1996" "@center Tom Lord" "@center Berkeley, CA USA" "" "@center except portions of \"POSIX Regex Functions\" which are" "@center Copyright (C) 1995" "@center Free Software Foundation, Inc." "" "@noindent" "Permission to use, copy, modify, distribute, and sell this software and" "its documentation for any purpose is hereby granted without fee," "provided that the above copyright notice appear in all copies and that" "both that copyright notice and this permission notice appear in" "supporting documentation." "" "@center NO WARRANTY" "" "@noindent" "BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR" "THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN" "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES" "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER" "EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED" "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE" "ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH" "YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL" "NECESSARY SERVICING, REPAIR OR CORRECTION." "" "@noindent" "IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING" "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR" "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR" "DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL" "DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM" "(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED" "INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF" "THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR" "OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES." "" "@node Overview, Posix Basic Regular Expressions, Copying, Top" "@chapter Overview" "" "Nothing to say here, yet." "" "@node Posix Basic Regular Expressions, Posix Entry Points, Overview, Top" "@chapter Posix Basic Regular Expressions" "" "The Posix Basic Regular Expression language is a notation for describing" "textual patterns. Regexps are typically used by comparing them to a" "string to see if that string matches the pattern, or by searching within" "a string for a substring that matches." "" "This chapter introduces the Posix regexp notation. This is not a formal" "or precise definition of Posix regexps -- it is an intuitive and" "hopefully expository description of them." "" "@menu" "* An Introduction to Regexps:: " "* Literal Regexps:: " "* Character Sets:: " "* Subexpressions:: " "* Repeated Subexpressions:: " "* Optional Subexpressions:: " "* Counted Subexpressions:: " "* Alternative Subexpressions:: " "* Backreferences:: " "* A Summary of Regexp Syntax:: " "* Ambiguous Patterns:: " "@end menu" "" "" "@node An Introduction to Regexps, Literal Regexps, Posix Basic Regular Expressions, Posix Basic Regular Expressions" "@section An Introduction to Regexps" "" "In the simplest cases, a regexp is just a literal string that must" "match exactly. For example, the pattern:" "" "@example" "regexp" "@end example" "" "matches the string \"regexp\" and no others." "" "Some characters have a special meaning when they occur in a regexp." "They aren't matched literally as in the previous example, but instead" "denote a more general pattern. For example, the character @code{*}" "is used to indicate that the preceeding element of a regexp may be" "repeated 0, 1, or more times. In the pattern:" "" "@example" "smooo*th" "@end example" "" "the @code{*} indicates that the preceeding @code{o} can be repeated 0 or" "more times. So the pattern matches:" "" "@example" "smooth" "smoooth" "smooooth" "smoooooth" "..." "@end example" "" "Suppose you want to write a pattern that literally matches a special" "character like @code{*} -- in other words, you don't want to @code{*} to" "indicate a permissible repetition, but to match @code{*} literally. This" "is accomplished by quoting the special character with a backslash. " "The pattern:" "" "@example" "smoo\\*th" "@end example" "" "matches the string:" "" "@example" "smoo*th" "@end example" "" "" "and no other strings." "" "In five cases, the pattern is reversed -- a backslash makes the" "character special instead of making a special character normal. The" "characters @code{+}, @code{?}, @code{|}, @code{(}, and @code{)} are" "normal but the sequences @code{\\+}, @code{\\?}, @code{\\|}, @code{\\(}, and" "@code{\\)} are special (their meaning is described later)." "" "The remaining sections of this chapter introduce and explain the various" "special characters that can occur in regexps." "" "@node Literal Regexps, Character Sets, An Introduction to Regexps, Posix Basic Regular Expressions" "@section Literal Regexps" "" "A literal regexp is a string which contains no special characters." "A literal regexp matches an identical string, but no other characters." "For example:" "" "@example" "literally" "@end example" "" "matches" "" "@example" "literally" "@end example" "" "and nothing else." "" "Generally, whitespace characters, numbers, and letters are not special." "Some punctuation characters are special and some are not (the syntax" "summary at the end of this chapter makes a convenient reference for" "which characters are special and which aren't)." "" "" "@node Character Sets, Subexpressions, Literal Regexps, Posix Basic Regular Expressions" "@section Character Sets" "" "This section introduces the special characters @code{.} and @code{[}." "" "@code{.} matches any character except the NULL character. For example:" "" "@example" "p.ck" "@end example" "" "matches" "" "@example" "pick" "pack" "puck" "pbck" "pcck" "p.ck" "" "..." "@end example" "" "" "@code{[} begins a @dfn{character set}. A character set is similar to" "@code{.} in that it matches not a single, literal character, but any" "of a set of characters. @code{[} is different from @code{.} in that" "with @code{[}, you define the set of characters explicitly." "" "There are three basic forms a character set can take." "" "In the first form, the character set is spelled out:" "" "@example" "[<cset-spec>] -- every character in <cset-spec> is in the set." "@end example" "" "In the second form, the character set indicated is the negation of" "a character set is explicitly spelled out:" "" "@example" "[^<cset-spec>] -- every character *not* in <cset-spec> is in the set." "@end example" "" "A @code{<cset-spec>} is more or less an explicit enumeration of a set" "of characters. It can be written as a string of individual characters:" "" "@example" "[aeiou]" "@end example" "" "or as a range of characters:" "" "@example" "[0-9]" "@end example" "" "These two forms can be mixed:" "" "@example" "[A-za-z0-9_$]" "@end example" "" "Note that special regexp characters (such as @code{*}) are @emph{not}" "special within a character set. @code{-}, as illustrated above," "@emph{is} special, except, as illustrated below, when it is the first" "character mentioned." "" "This is a four-character set:" "" "@example" "[-+*/]" "@end example" "" "The third form of a character set makes use of a pre-defined \"character" "class\":" "" "@example" "[[:class-name:]] -- every character described by class-name is in the set." "@end example" "" "The supported character classes are:" "" "@example" "alnum - the set of alpha-numeric characters" "alpha - the set of alphabetic characters" "blank - tab and space" "cntrl - the control characters" "digit - decimal digits" "graph - all printable characters except space" "lower - lower case letters" "print - the \"printable\" characters" "punct - punctuation" "space - whitespace characters" "upper - upper case letters" "xdigit - hexidecimal digits" "@end example" "" "Finally, character class sets can also be inverted:" "" "@example" "[^[:space:]] - all non-whitespace characters" "@end example" "" "Character sets can be used in a regular expression anywhere a literal" "character can." "" "@node Subexpressions, Repeated Subexpressions, Character Sets, Posix Basic Regular Expressions" "@section Subexpressions" "" "A subexpression is a regular expression enclosed in @code{\\(} and" "@code{\\)}. A subexpression can be used anywhere a single character or" "character set can be used." "" "Subexpressions are useful for grouping regexp constructs. For example," "the repeat operator, @code{*}, usually applies to just the preceeding" "character. Recall that:" "" "@example" "smooo*th" "@end example" "" "matches" "" "@example" "smooth" "smoooth" "..." "@end example" "" "" "Using a subexpression, we can apply @code{*} to a longer string:" "" "@example" "banan\\(an\\)*a" "@end example" "" "matches" "" "@example" "banana" "bananana" "banananana" "..." "@end example" "" "Subexpressions also have a special meaning with regard to backreferences" "and substitutions (see @xref{Backreferences})." "" "" "@node Repeated Subexpressions, Optional Subexpressions, Subexpressions, Posix Basic Regular Expressions" "@section Repeated Subexpressions" "" "" "@code{*} is the repeat operator. It applies to the preceeding" "character, character set, subexpression or backreference. It indicates" "that the preceeding element can be matched 0 or more times:" "" "@example" "bana\\(na\\)*" "@end example" "" "matches" "" "@example" "bana" "banana" "bananana" "banananana" "..." "@end example" "" "" "" "@code{\\+} is similar to @code{*} except that @code{\\+} requires the" "preceeding element to be matched at least once. So while:" "" "@example" "bana\\(na\\)*" "@end example" "" "matches" "" "@example" "bana" "@end example" "" "@example" "bana(na\\)\\+" "@end example" "" "does not. Both match " "" "@example" "banana" "bananana" "banananana" "..." "@end example" "" "Thus, @code{bana\\(na\\)+} is short-hand for @code{banana\\(na\\)*}." "" "" "@node Optional Subexpressions, Counted Subexpressions, Repeated Subexpressions, Posix Basic Regular Expressions" "@section Optional Subexpressions" "" "@code{\\?} indicates that the preceeding character, character set, or" "subexpression is optional. It is permitted to match, or to be skipped:" "" "@example" "CSNY\\?" "@end example" "" "matches both" "" "@example" "CSN" "@end example" "" "and " "" "@example" "CSNY" "@end example" "" "" "@node Counted Subexpressions, Alternative Subexpressions, Optional Subexpressions, Posix Basic Regular Expressions" "@section Counted Subexpressions" "" "An interval expression, @code{@{m,n@}} where @code{m} and @code{n} are" "non-negative integers with @code{n >= m}, applies to the preceeding" "character, character set, subexpression or backreference. It indicates" "that the preceeding element must match at least @code{m} times and may" "match as many as @code{n} times." "" "For example:" "" "@example" "c\\([ad]\\)@{1,4@}" "@end example" "" "matches" "" "@example" "car" "cdr" "caar" "cdar" "..." "caaar" "cdaar" "..." "cadddr" "cddddr" "@end example" "" "" "" "@node Alternative Subexpressions, Backreferences, Counted Subexpressions, Posix Basic Regular Expressions" "@section Alternative Subexpressions" "" "An alternative is written:" "" "@example" "regexp-1\\|regexp-2\\|regexp-3\\|..." "@end example" "" "It matches anything matched by some @code{regexp-n}. For example:" "" "@example" "Crosby, Stills, \\(and Nash\\|Nash, and Young\\)" "@end example" "" "matches" "" "@example" "Crosby, Stills, and Nash" "@end example" "" "and" "" "@example" "Crosby, Stills, Nash, and Young" "@end example" "" "" "@node Backreferences, A Summary of Regexp Syntax, Alternative Subexpressions, Posix Basic Regular Expressions" "@section Backreferences, Extractions and Substitutions" "" "A backreference is written @code{\\n} where @code{n} is some single digit" "other than 0. To be a valid backreference, there must be at least" "@code{n} parenthesized subexpressions in the pattern prior to the" "backreference." "" "A backreference matches a literal copy of whatever was matched by the" "corresponding subexpression. For example," "" "@example" "\\(.*\\)-\\1" "@end example" "" "matches:" "" "@example" "go-go" "ha-ha" "wakka-wakka" "..." "@end example" "" "In some applications, subexpressions are used to extract substrings." "For example, Emacs has the functions @code{match-beginnning} and" "@code{match-end} which report the positions of strings matched by" "subexpressions. These functions use the same numbering scheme for" "subexpressions as backreferences, with the additional rule that" "subexpression 0 is defined to be the whole regexp." "" "In some applications, subexpressions are used in string substitution." "This again uses the backreference numbering scheme. For example, this sed" "command:" "" "@example" "s/From:.*<\\(.*\\)>/To: \\1/" "@end example" "" "first matches the line:" "" "@example" "From: Joe Schmoe <schmoe@@uspringfield.edu>" "@end example" "" "when it does, subexpression 1 matches \"schmoe@@uspringfield.edu\"." "The command replaces the matched line with \"To: \\1\" after doing" "subexpression substitution on it to get:" "" "@example" "To: schmoe@@uspringfield.edu" "@end example" "" "" "@node A Summary of Regexp Syntax, Ambiguous Patterns, Backreferences, Posix Basic Regular Expressions" "@section A Summary of Regexp Syntax" "" "In summary, regexps can be:" "" "@code{abcd} -- matching a string literally" "" "@code{.} -- matching everything except NULL" "" "@code{[a-z_?]}, @code{^[a-z_?]}, @code{[[:alpha:]]} and" "@code{[^[:alpha:]]} -- matching character sets" "" "@code{\\(subexp\\)} -- grouping an expression into a subexpression." "" "@code{\\n} -- match a copy of whatever was matched by the nth subexpression." "" "The following special characters and sequences can be applied to a" "character, character set, subexpression, or backreference:" "" "@code{*} -- repeat the preceeding element 0 or more times." "" "@code{\\+} -- repeat the preceeding element 1 or more times." "" "@code{\\?} -- match the preceeding element 0 or 1 time." "" "@code{@{m,n@}} -- match the preceeding element at least @code{m}, and as" "many as @code{n} times." "" "@code{regexp-1\\|regexp-2\\|..} -- match any regexp-n." "" "A special character, like @code{.} or @code{*} can be made into a literal" "character by prefixing it with @code{\\}." "" "A special sequence, like @code{\\+} or @code{\\?} can be made into a" "literal character by dropping the @code{\\}." "" "" "@node Ambiguous Patterns, , A Summary of Regexp Syntax, Posix Basic Regular Expressions" "@section Ambiguous Patterns" "" "Sometimes a regular expression appears to be ambiguous. For example, suppose" "we compare the pattern:" "" "@example" "begin\\|beginning" "@end example" "" "to the string" "" "@example" "beginning" "@end example" "" "either just the first 5 characters will match, or the whole string will match." "" "In every case like this, the longer match is preferred. The whole" "string will match." "" "Sometimes there is ambiguity not about how many characters to match, but" "where the subexpressions occur within the match. This can effect" "extraction functions like Emacs' @code{match-beginning} or rewrite" "functions like sed's @code{s} command. For example, consider matching" "the pattern:" "" "@example" "b\\(\\[^q]*\\)\\(ing\\)?" "@end example" "" "against the string" "" "@example" "beginning" "@end example" "" "One possibility is that the first subexpression matches \"eginning\" and" "the second is skipped. Another possibility is that the first" "subexpression matches \"eginn\" and the second matches \"ing\"." "" "The rule is that consistant with matching as many characters as " "possible, the length of lower numbered subexpressions is maximized" "in preference to maximizing the length of later subexpressions." "" "In the case of the above example, the two possible matches are equal in" "overall length. Therefore, it comes down to maximizing the" "lower-numbered subexpression, \\1. The correct answer is that \\1 matches" "\"eginning\" and \\2 is skipped." "" "@node Posix Entry Points, Beyond POSIX, Posix Basic Regular Expressions, Top" "@chapter Posix Entry Points" "" "This section is excerpted from @emph{The GNU C Library} reference manual" "by Sandra Loosemore with Richard M. Stallman, Roland McGrath, and Andrew" "Oram." "" "The GNU C library supports the standard POSIX.2 interface. Programs" "using this interface should include the header file @file{rxposix.h}." "" "@menu" "* POSIX Regexp Compilation:: Using @code{regcomp} to prepare to match." "* Flags for POSIX Regexps:: Syntax variations for @code{regcomp}." "* Matching POSIX Regexps:: Using @code{regexec} to match the compiled" " pattern that you get from @code{regcomp}." "* Regexp Subexpressions:: Finding which parts of the string were matched." "* Subexpression Complications:: Find points of which parts were matched." "* Regexp Cleanup:: Freeing storage; reporting errors." "@end menu" "" "@node POSIX Regexp Compilation, Flags for POSIX Regexps, Posix Entry Points, Posix Entry Points" "@section POSIX Regular Expression Compilation" "" "Before you can actually match a regular expression, you must" "@dfn{compile} it. This is not true compilation---it produces a special" "data structure, not machine instructions. But it is like ordinary" "compilation in that its purpose is to enable you to ``execute'' the" "pattern fast. (@xref{Matching POSIX Regexps}, for how to use the" "compiled regular expression for matching.)" "" "There is a special data type for compiled regular expressions:" "" "@comment regex.h" "@comment POSIX.2" "@deftp {Data Type} regex_t" "This type of object holds a compiled regular expression." "It is actually a structure. It has just one field that your programs" "should look at:" "" "@table @code" "@item re_nsub" "This field holds the number of parenthetical subexpressions in the" "regular expression that was compiled." "@end table" "" "There are several other fields, but we don't describe them here, because" "only the functions in the library should use them." "@end deftp" "" "After you create a @code{regex_t} object, you can compile a regular" "expression into it by calling @code{regcomp}." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun int regcomp (regex_t *@var{compiled}, const char *@var{pattern}, int @var{cflags})" "@deftypefunx int regncomp (regex_t *@var{compiled}, int len, const char *@var{pattern}, int @var{cflags})" "The function @code{regcomp} ``compiles'' a regular expression into a" "data structure that you can use with @code{regexec} to match against a" "string. The compiled regular expression format is designed for" "efficient matching. @code{regcomp} stores it into @code{*@var{compiled}}." "" "The parameter @var{pattern} points to the regular expression to be" "compiled. When using @code{regcomp}, @var{pattern} must be" "0-terminated. When using @code{regncomp}, @var{pattern} must be" "@var{len} characters long." "" "@code{regncomp} is not a standard function; strictly POSIX programs" "should avoid using it." "" "It's up to you to allocate an object of type @code{regex_t} and pass its" "address to @code{regcomp}." "" "The argument @var{cflags} lets you specify various options that control" "the syntax and semantics of regular expressions. @xref{Flags for POSIX" "Regexps}." "" "If you use the flag @code{REG_NOSUB}, then @code{regcomp} omits from" "the compiled regular expression the information necessary to record" "how subexpressions actually match. In this case, you might as well" "pass @code{0} for the @var{matchptr} and @var{nmatch} arguments when" "you call @code{regexec}." "" "If you don't use @code{REG_NOSUB}, then the compiled regular expression" "does have the capacity to record how subexpressions match. Also," "@code{regcomp} tells you how many subexpressions @var{pattern} has, by" "storing the number in @code{@var{compiled}->re_nsub}. You can use that" "value to decide how long an array to allocate to hold information about" "subexpression matches." "" "@code{regcomp} returns @code{0} if it succeeds in compiling the regular" "expression; otherwise, it returns a nonzero error code (see the table" "below). You can use @code{regerror} to produce an error message string" "describing the reason for a nonzero value; see @ref{Regexp Cleanup}." "" "@end deftypefun" "" "Here are the possible nonzero values that @code{regcomp} can return:" "" "@table @code" "@comment regex.h" "@comment POSIX.2" "@item REG_BADBR" "There was an invalid @samp{\\@{@dots{}\\@}} construct in the regular" "expression. A valid @samp{\\@{@dots{}\\@}} construct must contain either" "a single number, or two numbers in increasing order separated by a" "comma." "" "@comment regex.h" "@comment POSIX.2" "@item REG_BADPAT" "There was a syntax error in the regular expression." "" "@comment regex.h" "@comment POSIX.2" "@item REG_BADRPT" "A repetition operator such as @samp{?} or @samp{*} appeared in a bad" "position (with no preceding subexpression to act on)." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ECOLLATE" "The regular expression referred to an invalid collating element (one not" "defined in the current locale for string collation). " "" "@comment regex.h" "@comment POSIX.2" "@item REG_ECTYPE" "The regular expression referred to an invalid character class name." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EESCAPE" "The regular expression ended with @samp{\\}." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ESUBREG" "There was an invalid number in the @samp{\\@var{digit}} construct." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EBRACK" "There were unbalanced square brackets in the regular expression." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EPAREN" "An extended regular expression had unbalanced parentheses," "or a basic regular expression had unbalanced @samp{\\(} and @samp{\\)}." "" "@comment regex.h" "@comment POSIX.2" "@item REG_EBRACE" "The regular expression had unbalanced @samp{\\@{} and @samp{\\@}}." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ERANGE" "One of the endpoints in a range expression was invalid." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ESPACE" "@code{regcomp} ran out of memory." "@end table" "" "@node Flags for POSIX Regexps, Matching POSIX Regexps, POSIX Regexp Compilation, Posix Entry Points" "@section Flags for POSIX Regular Expressions" "" "These are the bit flags that you can use in the @var{cflags} operand when" "compiling a regular expression with @code{regcomp}." " " "@table @code" "@comment regex.h" "@comment POSIX.2" "@item REG_EXTENDED" "Treat the pattern as an extended regular expression, rather than as a" "basic regular expression." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ICASE" "Ignore case when matching letters." "" "@comment regex.h" "@comment POSIX.2" "@item REG_NOSUB" "Don't bother storing the contents of the @var{matches-ptr} array." "" "@comment regex.h" "@comment POSIX.2" "@item REG_NEWLINE" "Treat a newline in @var{string} as dividing @var{string} into multiple" "lines, so that @samp{$} can match before the newline and @samp{^} can" "match after. Also, don't permit @samp{.} to match a newline, and don't" "permit @samp{[^@dots{}]} to match a newline." "" "Otherwise, newline acts like any other ordinary character." "@end table" "" "@node Matching POSIX Regexps, Regexp Subexpressions, Flags for POSIX Regexps, Posix Entry Points" "@section Matching a Compiled POSIX Regular Expression" "" "Once you have compiled a regular expression, as described in @ref{POSIX" "Regexp Compilation}, you can match it against strings using" "@code{regexec}. A match anywhere inside the string counts as success," "unless the regular expression contains anchor characters (@samp{^} or" "@samp{$})." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun int regexec (regex_t *@var{compiled}, char *@var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr} @t{[]}, int @var{eflags})" "@deftypefunx int regnexec (regex_t *@var{compiled}, int len, char *@var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr} @t{[]}, int @var{eflags})" "This function tries to match the compiled regular expression" "@code{*@var{compiled}} against @var{string}." "" "@code{regexec} returns @code{0} if the regular expression matches;" "otherwise, it returns a nonzero value. See the table below for" "what nonzero values mean. You can use @code{regerror} to produce an" "error message string describing the reason for a nonzero value; " "see @ref{Regexp Cleanup}." "" "The parameter @var{string} points to the text to search. When using" "@code{regexec}, @var{string} must be 0-terminated. When using" "@code{regnexec}, @var{string} must be @var{len} characters long." "" "@code{regnexec} is not a standard function; strictly POSIX programs" "should avoid using it." "" "The argument @var{eflags} is a word of bit flags that enable various" "options." "" "If you want to get information about what part of @var{string} actually" "matched the regular expression or its subexpressions, use the arguments" "@var{matchptr} and @var{nmatch}. Otherwise, pass @code{0} for " "@var{nmatch}, and @code{NULL} for @var{matchptr}. @xref{Regexp" "Subexpressions}." "@end deftypefun" "" "You must match the regular expression with the same set of current" "locales that were in effect when you compiled the regular expression." "" "The function @code{regexec} accepts the following flags in the" "@var{eflags} argument:" "" "@table @code " "@comment regex.h" "@comment POSIX.2" "@item REG_NOTBOL" "Do not regard the beginning of the specified string as the beginning of" "a line; more generally, don't make any assumptions about what text might" "precede it." "" "@comment regex.h" "@comment POSIX.2" "@item REG_NOTEOL" "Do not regard the end of the specified string as the end of a line; more" "generally, don't make any assumptions about what text might follow it." "@end table" "" "Here are the possible nonzero values that @code{regexec} can return:" "" "@table @code" "@comment regex.h" "@comment POSIX.2" "@item REG_NOMATCH" "The pattern didn't match the string. This isn't really an error." "" "@comment regex.h" "@comment POSIX.2" "@item REG_ESPACE" "@code{regexec} ran out of memory." "@end table" "" "@node Regexp Subexpressions, Subexpression Complications, Matching POSIX Regexps, Posix Entry Points" "@section Match Results with Subexpressions" "" "When @code{regexec} matches parenthetical subexpressions of" "@var{pattern}, it records which parts of @var{string} they match. It" "returns that information by storing the offsets into an array whose" "elements are structures of type @code{regmatch_t}. The first element of" "the array (index @code{0}) records the part of the string that matched" "the entire regular expression. Each other element of the array records" "the beginning and end of the part that matched a single parenthetical" "subexpression." "" "@comment regex.h" "@comment POSIX.2" "@deftp {Data Type} regmatch_t" "This is the data type of the @var{matcharray} array that you pass to" "@code{regexec}. It containes two structure fields, as follows:" "" "@table @code" "@item rm_so" "The offset in @var{string} of the beginning of a substring. Add this" "value to @var{string} to get the address of that part." "" "@item rm_eo" "The offset in @var{string} of the end of the substring." "@end table" "@end deftp" "" "@comment regex.h" "@comment POSIX.2" "@deftp {Data Type} regoff_t" "@code{regoff_t} is an alias for another signed integer type." "The fields of @code{regmatch_t} have type @code{regoff_t}." "@end deftp" "" "The @code{regmatch_t} elements correspond to subexpressions" "positionally; the first element (index @code{1}) records where the first" "subexpression matched, the second element records the second" "subexpression, and so on. The order of the subexpressions is the order" "in which they begin." "" "When you call @code{regexec}, you specify how long the @var{matchptr}" "array is, with the @var{nmatch} argument. This tells @code{regexec} how" "many elements to store. If the actual regular expression has more than" "@var{nmatch} subexpressions, then you won't get offset information about" "the rest of them. But this doesn't alter whether the pattern matches a" "particular string or not." "" "If you don't want @code{regexec} to return any information about where" "the subexpressions matched, you can either supply @code{0} for" "@var{nmatch}, or use the flag @code{REG_NOSUB} when you compile the" "pattern with @code{regcomp}." "" "@node Subexpression Complications, Regexp Cleanup, Regexp Subexpressions, Posix Entry Points" "@section Complications in Subexpression Matching" "" "Sometimes a subexpression matches a substring of no characters. This" "happens when @samp{f\\(o*\\)} matches the string @samp{fum}. (It really" "matches just the @samp{f}.) In this case, both of the offsets identify" "the point in the string where the null substring was found. In this" "example, the offsets are both @code{1}." "" "Sometimes the entire regular expression can match without using some of" "its subexpressions at all---for example, when @samp{ba\\(na\\)*} matches the" "string @samp{ba}, the parenthetical subexpression is not used. When" "this happens, @code{regexec} stores @code{-1} in both fields of the" "element for that subexpression." "" "Sometimes matching the entire regular expression can match a particular" "subexpression more than once---for example, when @samp{ba\\(na\\)*}" "matches the string @samp{bananana}, the parenthetical subexpression" "matches three times. When this happens, @code{regexec} usually stores" "the offsets of the last part of the string that matched the" "subexpression. In the case of @samp{bananana}, these offsets are" "@code{6} and @code{8}." "" "But the last match is not always the one that is chosen. It's more" "accurate to say that the last @emph{opportunity} to match is the one" "that takes precedence. What this means is that when one subexpression" "appears within another, then the results reported for the inner" "subexpression reflect whatever happened on the last match of the outer" "subexpression. For an example, consider @samp{\\(ba\\(na\\)*s \\)*} matching" "the string @samp{bananas bas }. The last time the inner expression" "actually matches is near the end of the first word. But it is " "@emph{considered} again in the second word, and fails to match there." "@code{regexec} reports nonuse of the ``na'' subexpression." "" "Another place where this rule applies is when the regular expression" "@w{@samp{\\(ba\\(na\\)*s \\|nefer\\(ti\\)* \\)*}} matches @samp{bananas nefertiti}." "The ``na'' subexpression does match in the first word, but it doesn't" "match in the second word because the other alternative is used there." "Once again, the second repetition of the outer subexpression overrides" "the first, and within that second repetition, the ``na'' subexpression" "is not used. So @code{regexec} reports nonuse of the ``na''" "subexpression." "" "@node Regexp Cleanup, , Subexpression Complications, Posix Entry Points" "@section POSIX Regexp Matching Cleanup" "" "When you are finished using a compiled regular expression, you can" "free the storage it uses by calling @code{regfree}." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun void regfree (regex_t *@var{compiled})" "Calling @code{regfree} frees all the storage that @code{*@var{compiled}}" "points to. This includes various internal fields of the @code{regex_t}" "structure that aren't documented in this manual." "" "@code{regfree} does not free the object @code{*@var{compiled}} itself." "@end deftypefun" "" "You should always free the space in a @code{regex_t} structure with" "@code{regfree} before using the structure to compile another regular" "expression." "" "When @code{regcomp} or @code{regexec} reports an error, you can use" "the function @code{regerror} to turn it into an error message string." "" "@comment regex.h" "@comment POSIX.2" "@deftypefun size_t regerror (int @var{errcode}, regex_t *@var{compiled}, char *@var{buffer}, size_t @var{length})" "This function produces an error message string for the error code" "@var{errcode}, and stores the string in @var{length} bytes of memory" "starting at @var{buffer}. For the @var{compiled} argument, supply the" "same compiled regular expression structure that @code{regcomp} or" "@code{regexec} was working with when it got the error. Alternatively," "you can supply @code{NULL} for @var{compiled}; you will still get a" "meaningful error message, but it might not be as detailed." "" "If the error message can't fit in @var{length} bytes (including a" "terminating null character), then @code{regerror} truncates it." "The string that @code{regerror} stores is always null-terminated" "even if it has been truncated." "" "The return value of @code{regerror} is the minimum length needed to" "store the entire error message. If this is less than @var{length}, then" "the error message was not truncated, and you can use it. Otherwise, you" "should call @code{regerror} again with a larger buffer." "" "Here is a function which uses @code{regerror}, but always dynamically" "allocates a buffer for the error message:" "" "@smallexample" "char *get_regerror (int errcode, regex_t *compiled)" "@{" " size_t length = regerror (errcode, compiled, NULL, 0);" " char *buffer = xmalloc (length);" " (void) regerror (errcode, compiled, buffer, length);" " return buffer;" "@}" "@end smallexample" "@end deftypefun" "" "@node Beyond POSIX, Rx Theory, Posix Entry Points, Top" "@chapter Beyond POSIX" "" "This section is not finished documentation, but rather a collection of" "pointers towards some of the interesting, non-standard features of Rx." "" "@section New Regexp Operators" "" "Rx supports some unusual regexp syntax." "" "@code{[[:cut N:]]} sets @code{pmatch[0].final_tag} to N and causes the" "matching to stop instantly. If N is 0, the overall match fails," "otherwise it succeeds." "" "@code{[[:(:]] ... [[:):]]} is just like @code{\\( ... \\)} except that in" "the first case, no pmatch entries are changed, and the subexpression is" "not counted in the numbering of parenthesized subexpressions." "" "@code{[[:(:]] ... [[:):]]} can be used when you do not need to know" "where a subexpression matched but are only using parentheses to effect" "the parsing of the regexp. " "" "There are two reasons to use @code{[[:(:]] ... [[:):]]}:" "" "1. regexec will run faster." "" "2. Currently, only 8 backreferencable subexpressions are supported:" "@code{\\1 .. \\9}. Using @code{[[:(:]] ... [[:):]]} is a way to conserve" "backreferencable subexpression names in an expression with many" "parentheses." "" "@section New POSIX Functions" "" "@code{regncomp} and @code{regnexec} are non-standard generalizations of" "@code{regcomp} and @code{regexec}." "" "@section Tuning POSIX performance" "" "Two mysterious parmaters can be used to trade-off performance and" "memory use." "" "At compile-time they are @code{RX_DEFAULT_DFA_CACHE_SIZE} and" "@code{RX_DEFAULT_NFA_DELAY}. " "" "If you want to mess with these (I generally don't advise it), I suggest" "experimenting for your particular application/memory situation; frob" "these by powers of two and try out the results on what you expect will" "be typical regexp workloads." "" "You can also set those parameters at run-time (before calling any regexp" "functions) by tweaking the corresponding variables:" "" "@code{rx_default_cache->bytes_allowed}" "" "and" "" "@code{rx_basic_unfaniverse_delay}" "" "" "" "@section POSIX stream-style interface" "" "@code{rx_make_solutions}, @code{rx_next_solution}, and" "@code{rx_free_solutions} are a lower level alternative to the posix" "functions. Using those functions, you can compare a compiled regexp to" "a string that is not contiguous in memory or even a string that is not" "entirely in memory at any one time." "" "The code in rxposix.c points out how those functions are used." "" "" "@section DFAs Directly" "" "If you are only interested in pure regular expressions (no pmatch data," "no backreferences, and no counted subexpressions), you can parse a" "regexp using @code{rx_parse}, convert it to an nfa using @code{rx_unfa}," "and run the dfa using @code{rx_init_system}, @code{rx_advance_to_final}," "and @code{rx_terminate_system}. The dfa Scheme primitives in" "@file{rgx.c} may provide some guide." "" "@node Rx Theory, , Beyond POSIX, Top" "@chapter Rx Theory" "@cindex Rx Theory" "" "There are two match algorithms. One is for truly regular regexps (those" "that can be reduced to a dfa). The other is for non-regular regexps." "" "The dfa algorithm implements the idea suggested in @cite{Compilers} by" "Aho, Sethi and Ullman:" "" "@quotation" "[One] approach [to pattern matching regular expressions] is to use a" "DFA, but avoid constructing all of the transition table by using a" "technique called \"lazy transition evaluation\". Here, transitions are" "computed at run time [when] actually needed. [T]ransitions are" "stored in a cache. [....] If the cache becomes full, we can erase some" "previously computed transition to make room for the new transition." "@end quotation" "" "The implementation in Rx is generalized from that, but the above" "description covers what is used for Posix patterns. " "" "The non-dfa algorithm implements a \"recursive decomposition\" technique" "described in email by Henry Spencer. For a given pattern, this" "algorithm first checks to see if a simpler, superset language," "DFA-pattern matches. If it does, then this algorithm does the" "detail-work to see if the non-DFA pattern matches." "" "The detail work usually involves recursing on subpatterns. For example," "a concatentation of two subexpressions matches a string if the string" "can be divided into two parts, each matching one subexpression, in the" "right order. More than one solution is often possible for a given" "pattern. This ambiguity is the subject of the \"leftmost longest\" rules" "in the spec, and the back-tracking oriented stream-of-solution functions" "@code{rx_make_solutions}, @code{rx_next_solution} and" "@code{rx_free_solutions}." "" "@example" "rxspencer.[ch] -- The non-DFA algorithm" "rxanal.[ch] rxsuper.[ch] rxnfa.[ch] -- The DFA algorithm" "@end example" "" "@bye" "" ""
33.714376
155
0.719498
[ "object" ]
bb3b4435c04b47897378a9bf4a9241d950b54c44
10,340
h
C
include/restore.h
aerospike/aerospike-tools-backup
62a266e7525f6088171dbee36eeecfc71c47d2bf
[ "Apache-2.0", "MIT" ]
18
2015-09-25T21:24:33.000Z
2022-03-09T16:01:40.000Z
include/restore.h
aerospike/aerospike-tools-backup
62a266e7525f6088171dbee36eeecfc71c47d2bf
[ "Apache-2.0", "MIT" ]
7
2015-11-10T16:12:01.000Z
2019-04-12T05:19:28.000Z
include/restore.h
aerospike/aerospike-tools-backup
62a266e7525f6088171dbee36eeecfc71c47d2bf
[ "Apache-2.0", "MIT" ]
20
2015-10-21T20:05:50.000Z
2021-11-23T01:16:37.000Z
/* * Aerospike Restore * * Copyright (c) 2008-2021 Aerospike, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include <io_proxy.h> #include <shared.h> // The default number of restore threads. #define DEFAULT_THREADS 20 // Maximal number of tries for each record put. #define MAX_TRIES 10 // Initial backoff delay (in ms) between tries when overloaded; doubled after // each try. #define INITIAL_BACKOFF 10 // The interval for logging per-thread timing stats. #define STAT_INTERVAL 10 /* * Encapsulates a UDF file. */ typedef struct { // The language of the UDF file. as_udf_type type; // The name of the UDF file. char *name; // The size of the UDF file. uint32_t size; // The content of the UDF file. void *data; } udf_param; /* * The result codes for the backup file format decoder. */ typedef enum { // A record was read and is returned. DECODER_RECORD, // Secondary index information was read and is returned. DECODER_INDEX, // A UDF file was read and is returned. DECODER_UDF, // The end of the backup file was encountered. DECODER_EOF, // An error occurred. DECODER_ERROR } decoder_status; /* * The interface exposed by the backup file format decoder. */ typedef struct backup_decoder { /* * Reads, parses, and returns the next entity from a backup file descriptor. * * @param fd The file descriptor. * @param legacy Indicates a version 3.0 backup file. * @param ns_vec The (optional) source and (also optional) target namespace to be restored. * @param bin_vec The bins to be restored, as a vector of strings. * @param line_no The current line number. * @param rec The returned record. Only valid, if the result is * [DECODER_RECORD](@ref decoder_status::DECODER_RECORD). * @param extra_ttl Extra-ttl to be added to expirable records. * @param expired Indicates that an expired record was read. Only valid, if the result is * [DECODER_RECORD](@ref decoder_status::DECODER_RECORD). * @param index The returned secondary index information. Only valid, if the result is * [DECODER_INDEX](@ref decoder_status::DECODER_INDEX). * @param udf The returned UDF file. Only valid, if the result is * [DECODER_UDF](@ref decoder_status::DECODER_UDF). * * @result See @ref decoder_status. */ decoder_status (*parse)(io_read_proxy_t *fd, bool legacy, as_vector *ns_vec, as_vector *bin_vec, uint32_t *line_no, as_record *rec, int32_t extra_ttl, bool *expired, index_param *index, udf_param *udf); } backup_decoder_t; /* * The global restore configuration and stats shared by all restore threads and the counter thread. */ typedef struct restore_config { char *host; int32_t port; bool use_services_alternate; char *user; char *password; uint32_t parallel; char *nice_list; bool no_records; bool no_indexes; bool indexes_last; bool no_udfs; bool wait; // timeout for Aerospike commands. uint32_t timeout; as_config_tls tls; char* tls_name; // The Aerospike client. aerospike *as; // The (optional) source and (also optional) target namespace to be restored. char *ns_list; // The directory to restore from. `NULL`, when restoring from a single file. char *directory; // The file to restore from. `NULL`, when restoring from a directory. char *input_file; // The path for the machine-readable output. char *machine; // The bins to be restored. char *bin_list; // The sets to be restored. char *set_list; // The encryption key given by the user encryption_key_t* pkey; // The compression mode to be used (default is none) compression_opt compress_mode; // The encryption mode to be used (default is none) encryption_opt encrypt_mode; // Indicates that existing records shouldn't be touched. bool unique; // Indicates that existing records should be replaced instead of updated. bool replace; // Ignore record specific errors. bool ignore_rec_error; // Indicates that the generation count of existing records should be ignored. bool no_generation; // Amount of extra time-to-live to add to records that have expirable // void-times. int32_t extra_ttl; // The B/s cap for throttling. uint64_t bandwidth; // The TPS cap for throttling. uint32_t tps; // The file format decoder to be used for reading data from a backup file. backup_decoder_t *decoder; // The total size of all backup files to be restored. off_t estimated_bytes; // The total number of bytes read from the backup file(s) so far. cf_atomic64 total_bytes; // The total number of records read from the backup file(s) so far. cf_atomic64 total_records; // The number of records dropped because they were expired. cf_atomic64 expired_records; // The number of records dropped because they didn't contain any of the // selected bins or didn't belong to any of the the selected sets. cf_atomic64 skipped_records; // The number of records ignored because of record level permanent error while // restoring. e.g RECORD_TOO_BIG Enabled or disabled using // --ignore-record-error flag. cf_atomic64 ignored_records; // The number of successfully restored records. cf_atomic64 inserted_records; // The number of records dropped because they already existed in the // database. cf_atomic64 existed_records; // The number of records dropped because the database already contained the // records with a higher generation count. cf_atomic64 fresher_records; // How often we backed off due to server overload. cf_atomic64 backoff_count; // The current limit for total_bytes for throttling. This is periodically // increased by the counter thread to raise the limit according to the // bandwidth limit. volatile uint64_t bytes_limit; // The current limit for total_records for throttling. // This is periodically increased by the counter thread to raise the limit // according to the TPS limit. volatile uint64_t records_limit; // The number of successfully created secondary indexes. volatile uint32_t index_count; // The number of successfully stored UDF files. volatile uint32_t udf_count; // Authentication mode. char *auth_mode; } restore_config_t; /* * The backup file information pushed to the job queue and picked up by the restore threads. */ typedef struct { // The global restore configuration and stats. restore_config_t *conf; // The backup file to be restored. char *path; // When restoring from a single file, the file descriptor of that file. io_read_proxy_t* shared_fd; // The current line number. uint32_t *line_no; // The (optional) source and (also optional) target namespace to be // restored, as a vector of strings. as_vector *ns_vec; // The bins to be restored, as a vector of bin name strings. as_vector *bin_vec; // The sets to be restored, as a vector of set name strings. as_vector *set_vec; // Indicates a version 3.0 backup file. bool legacy; } restore_thread_args; /* * The per-thread context for information about the currently processed backup file. Each restore * thread creates one of these for each backup file that it reads. */ typedef struct per_thread_context { // The global restore configuration and stats. restore_config_t *conf; // The backup file to be restored. Copied from restore_thread_args.path. char *path; // When restoring from a single file, the file descriptor of that file. // Copied from restore_thread_args.shared_fd. io_read_proxy_t* shared_fd; // The current line number. Copied from restore_thread_args.line_no. uint32_t *line_no; // The file descriptor of the currently processed backup file. io_read_proxy_t* fd; // The (optional) source and (also optional) target namespace to be restored, // as a vector of strings. Copied from restore_thread_args.ns_vec. as_vector *ns_vec; // The bins to be restored, as a vector of bin name strings. // Copied from restore_thread_args.bin_vec. as_vector *bin_vec; // The sets to be restored, as a vector of set name strings. // Copied from restore_thread_args.set_vec. as_vector *set_vec; // Indicates a version 3.0 backup file. Copied from // restore_thread_args.legacy. bool legacy; // The total number of bytes read from the current file uint64_t byte_count_file; // The number of records for which we have collected timing stats. uint64_t stat_records; // The time spent on reading records on this thread. cf_clock read_time; // The time spent on storing records on this thread. cf_clock store_time; // The exponential moving average of read latencies. uint32_t read_ema; // The exponential moving average of store latencies. uint32_t store_ema; } per_thread_context_t; /* * Indicates, whether a secondary index exists and matches a given secondary index specification. */ typedef enum { // Invalid. INDEX_STATUS_INVALID, // The secondary index does not exist. INDEX_STATUS_ABSENT, // The secondary index exists and it matches the given specification. INDEX_STATUS_SAME, // The secondary index exists, but it does not match the given specification. INDEX_STATUS_DIFFERENT } index_status; extern int32_t restore_main(int32_t argc, char **argv); extern void restore_config_default(restore_config_t *conf); extern void restore_config_destroy(restore_config_t *conf);
36.027875
99
0.748839
[ "vector" ]
bb3ee26e2a1d41abe33768fabeb43811eb34eeb7
53,883
c
C
measurer/gdb-7.9/gdb/buildsym.c
armoredsoftware/protocol
e3b0c1df8bc1027865caec6d117e5925f71f26d2
[ "BSD-3-Clause" ]
null
null
null
measurer/gdb-7.9/gdb/buildsym.c
armoredsoftware/protocol
e3b0c1df8bc1027865caec6d117e5925f71f26d2
[ "BSD-3-Clause" ]
null
null
null
measurer/gdb-7.9/gdb/buildsym.c
armoredsoftware/protocol
e3b0c1df8bc1027865caec6d117e5925f71f26d2
[ "BSD-3-Clause" ]
null
null
null
/* Support routines for building symbol tables in GDB's internal format. Copyright (C) 1986-2015 Free Software Foundation, Inc. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* This module provides subroutines used for creating and adding to the symbol table. These routines are called from various symbol- file-reading routines. Routines to support specific debugging information formats (stabs, DWARF, etc) belong somewhere else. The basic way this module is used is as follows: buildsym_init (); cleanups = make_cleanup (really_free_pendings, NULL); cust = start_symtab (...); ... read debug info ... cust = end_symtab (...); do_cleanups (cleanups); The compunit symtab pointer ("cust") is returned from both start_symtab and end_symtab to simplify the debug info readers. There are minor variations on this, e.g., dwarf2read.c splits end_symtab into two calls: end_symtab_get_static_block, end_symtab_from_static_block, but all debug info readers follow this basic flow. Reading DWARF Type Units is another variation: buildsym_init (); cleanups = make_cleanup (really_free_pendings, NULL); cust = start_symtab (...); ... read debug info ... cust = end_expandable_symtab (...); do_cleanups (cleanups); And then reading subsequent Type Units within the containing "Comp Unit" will use a second flow: buildsym_init (); cleanups = make_cleanup (really_free_pendings, NULL); cust = restart_symtab (...); ... read debug info ... cust = augment_type_symtab (...); do_cleanups (cleanups); dbxread.c and xcoffread.c use another variation: buildsym_init (); cleanups = make_cleanup (really_free_pendings, NULL); cust = start_symtab (...); ... read debug info ... cust = end_symtab (...); ... start_symtab + read + end_symtab repeated ... do_cleanups (cleanups); */ #include "defs.h" #include "bfd.h" #include "gdb_obstack.h" #include "symtab.h" #include "symfile.h" #include "objfiles.h" #include "gdbtypes.h" #include "complaints.h" #include "expression.h" /* For "enum exp_opcode" used by... */ #include "bcache.h" #include "filenames.h" /* For DOSish file names. */ #include "macrotab.h" #include "demangle.h" /* Needed by SYMBOL_INIT_DEMANGLED_NAME. */ #include "block.h" #include "cp-support.h" #include "dictionary.h" #include "addrmap.h" /* Ask buildsym.h to define the vars it normally declares `extern'. */ #define EXTERN /**/ #include "buildsym.h" /* Our own declarations. */ #undef EXTERN /* For cleanup_undefined_stabs_types and finish_global_stabs (somewhat questionable--see comment where we call them). */ #include "stabsread.h" /* Buildsym's counterpart to struct compunit_symtab. TODO(dje): Move all related global state into here. */ struct buildsym_compunit { /* The objfile we're reading debug info from. */ struct objfile *objfile; /* List of subfiles (source files). Files are added to the front of the list. This is important mostly for the language determination hacks we use, which iterate over previously added files. */ struct subfile *subfiles; /* The subfile of the main source file. */ struct subfile *main_subfile; /* E.g., DW_AT_comp_dir if DWARF. Space for this is malloc'd. */ char *comp_dir; /* Space for this is not malloc'd, and is assumed to have at least the same lifetime as objfile. */ const char *producer; /* Space for this is not malloc'd, and is assumed to have at least the same lifetime as objfile. */ const char *debugformat; /* The compunit we are building. */ struct compunit_symtab *compunit_symtab; }; /* The work-in-progress of the compunit we are building. This is created first, before any subfiles by start_symtab. */ static struct buildsym_compunit *buildsym_compunit; /* List of free `struct pending' structures for reuse. */ static struct pending *free_pendings; /* Non-zero if symtab has line number info. This prevents an otherwise empty symtab from being tossed. */ static int have_line_numbers; /* The mutable address map for the compilation unit whose symbols we're currently reading. The symtabs' shared blockvector will point to a fixed copy of this. */ static struct addrmap *pending_addrmap; /* The obstack on which we allocate pending_addrmap. If pending_addrmap is NULL, this is uninitialized; otherwise, it is initialized (and holds pending_addrmap). */ static struct obstack pending_addrmap_obstack; /* Non-zero if we recorded any ranges in the addrmap that are different from those in the blockvector already. We set this to zero when we start processing a symfile, and if it's still zero at the end, then we just toss the addrmap. */ static int pending_addrmap_interesting; /* An obstack used for allocating pending blocks. */ static struct obstack pending_block_obstack; /* List of blocks already made (lexical contexts already closed). This is used at the end to make the blockvector. */ struct pending_block { struct pending_block *next; struct block *block; }; /* Pointer to the head of a linked list of symbol blocks which have already been finalized (lexical contexts already closed) and which are just waiting to be built into a blockvector when finalizing the associated symtab. */ static struct pending_block *pending_blocks; struct subfile_stack { struct subfile_stack *next; char *name; }; static struct subfile_stack *subfile_stack; /* The macro table for the compilation unit whose symbols we're currently reading. */ static struct macro_table *pending_macros; static void free_buildsym_compunit (void); static int compare_line_numbers (const void *ln1p, const void *ln2p); static void record_pending_block (struct objfile *objfile, struct block *block, struct pending_block *opblock); /* Initial sizes of data structures. These are realloc'd larger if needed, and realloc'd down to the size actually used, when completed. */ #define INITIAL_CONTEXT_STACK_SIZE 10 #define INITIAL_LINE_VECTOR_LENGTH 1000 /* Maintain the lists of symbols and blocks. */ /* Add a symbol to one of the lists of symbols. */ void add_symbol_to_list (struct symbol *symbol, struct pending **listhead) { struct pending *link; /* If this is an alias for another symbol, don't add it. */ if (symbol->ginfo.name && symbol->ginfo.name[0] == '#') return; /* We keep PENDINGSIZE symbols in each link of the list. If we don't have a link with room in it, add a new link. */ if (*listhead == NULL || (*listhead)->nsyms == PENDINGSIZE) { if (free_pendings) { link = free_pendings; free_pendings = link->next; } else { link = (struct pending *) xmalloc (sizeof (struct pending)); } link->next = *listhead; *listhead = link; link->nsyms = 0; } (*listhead)->symbol[(*listhead)->nsyms++] = symbol; } /* Find a symbol named NAME on a LIST. NAME need not be '\0'-terminated; LENGTH is the length of the name. */ struct symbol * find_symbol_in_list (struct pending *list, char *name, int length) { int j; const char *pp; while (list != NULL) { for (j = list->nsyms; --j >= 0;) { pp = SYMBOL_LINKAGE_NAME (list->symbol[j]); if (*pp == *name && strncmp (pp, name, length) == 0 && pp[length] == '\0') { return (list->symbol[j]); } } list = list->next; } return (NULL); } /* At end of reading syms, or in case of quit, ensure everything associated with building symtabs is freed. This is intended to be registered as a cleanup before doing psymtab->symtab expansion. N.B. This is *not* intended to be used when building psymtabs. Some debug info readers call this anyway, which is harmless if confusing. */ void really_free_pendings (void *dummy) { struct pending *next, *next1; for (next = free_pendings; next; next = next1) { next1 = next->next; xfree ((void *) next); } free_pendings = NULL; free_pending_blocks (); for (next = file_symbols; next != NULL; next = next1) { next1 = next->next; xfree ((void *) next); } file_symbols = NULL; for (next = global_symbols; next != NULL; next = next1) { next1 = next->next; xfree ((void *) next); } global_symbols = NULL; if (pending_macros) free_macro_table (pending_macros); pending_macros = NULL; if (pending_addrmap) obstack_free (&pending_addrmap_obstack, NULL); pending_addrmap = NULL; free_buildsym_compunit (); } /* This function is called to discard any pending blocks. */ void free_pending_blocks (void) { if (pending_blocks != NULL) { obstack_free (&pending_block_obstack, NULL); pending_blocks = NULL; } } /* Take one of the lists of symbols and make a block from it. Keep the order the symbols have in the list (reversed from the input file). Put the block on the list of pending blocks. */ static struct block * finish_block_internal (struct symbol *symbol, struct pending **listhead, struct pending_block *old_blocks, CORE_ADDR start, CORE_ADDR end, int is_global, int expandable) { struct objfile *objfile = buildsym_compunit->objfile; struct gdbarch *gdbarch = get_objfile_arch (objfile); struct pending *next, *next1; struct block *block; struct pending_block *pblock; struct pending_block *opblock; block = (is_global ? allocate_global_block (&objfile->objfile_obstack) : allocate_block (&objfile->objfile_obstack)); if (symbol) { BLOCK_DICT (block) = dict_create_linear (&objfile->objfile_obstack, *listhead); } else { if (expandable) { BLOCK_DICT (block) = dict_create_hashed_expandable (); dict_add_pending (BLOCK_DICT (block), *listhead); } else { BLOCK_DICT (block) = dict_create_hashed (&objfile->objfile_obstack, *listhead); } } BLOCK_START (block) = start; BLOCK_END (block) = end; /* Put the block in as the value of the symbol that names it. */ if (symbol) { struct type *ftype = SYMBOL_TYPE (symbol); struct dict_iterator iter; SYMBOL_BLOCK_VALUE (symbol) = block; BLOCK_FUNCTION (block) = symbol; if (TYPE_NFIELDS (ftype) <= 0) { /* No parameter type information is recorded with the function's type. Set that from the type of the parameter symbols. */ int nparams = 0, iparams; struct symbol *sym; /* Here we want to directly access the dictionary, because we haven't fully initialized the block yet. */ ALL_DICT_SYMBOLS (BLOCK_DICT (block), iter, sym) { if (SYMBOL_IS_ARGUMENT (sym)) nparams++; } if (nparams > 0) { TYPE_NFIELDS (ftype) = nparams; TYPE_FIELDS (ftype) = (struct field *) TYPE_ALLOC (ftype, nparams * sizeof (struct field)); iparams = 0; /* Here we want to directly access the dictionary, because we haven't fully initialized the block yet. */ ALL_DICT_SYMBOLS (BLOCK_DICT (block), iter, sym) { if (iparams == nparams) break; if (SYMBOL_IS_ARGUMENT (sym)) { TYPE_FIELD_TYPE (ftype, iparams) = SYMBOL_TYPE (sym); TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0; iparams++; } } } } } else { BLOCK_FUNCTION (block) = NULL; } /* Now "free" the links of the list, and empty the list. */ for (next = *listhead; next; next = next1) { next1 = next->next; next->next = free_pendings; free_pendings = next; } *listhead = NULL; /* Check to be sure that the blocks have an end address that is greater than starting address. */ if (BLOCK_END (block) < BLOCK_START (block)) { if (symbol) { complaint (&symfile_complaints, _("block end address less than block " "start address in %s (patched it)"), SYMBOL_PRINT_NAME (symbol)); } else { complaint (&symfile_complaints, _("block end address %s less than block " "start address %s (patched it)"), paddress (gdbarch, BLOCK_END (block)), paddress (gdbarch, BLOCK_START (block))); } /* Better than nothing. */ BLOCK_END (block) = BLOCK_START (block); } /* Install this block as the superblock of all blocks made since the start of this scope that don't have superblocks yet. */ opblock = NULL; for (pblock = pending_blocks; pblock && pblock != old_blocks; pblock = pblock->next) { if (BLOCK_SUPERBLOCK (pblock->block) == NULL) { /* Check to be sure the blocks are nested as we receive them. If the compiler/assembler/linker work, this just burns a small amount of time. Skip blocks which correspond to a function; they're not physically nested inside this other blocks, only lexically nested. */ if (BLOCK_FUNCTION (pblock->block) == NULL && (BLOCK_START (pblock->block) < BLOCK_START (block) || BLOCK_END (pblock->block) > BLOCK_END (block))) { if (symbol) { complaint (&symfile_complaints, _("inner block not inside outer block in %s"), SYMBOL_PRINT_NAME (symbol)); } else { complaint (&symfile_complaints, _("inner block (%s-%s) not " "inside outer block (%s-%s)"), paddress (gdbarch, BLOCK_START (pblock->block)), paddress (gdbarch, BLOCK_END (pblock->block)), paddress (gdbarch, BLOCK_START (block)), paddress (gdbarch, BLOCK_END (block))); } if (BLOCK_START (pblock->block) < BLOCK_START (block)) BLOCK_START (pblock->block) = BLOCK_START (block); if (BLOCK_END (pblock->block) > BLOCK_END (block)) BLOCK_END (pblock->block) = BLOCK_END (block); } BLOCK_SUPERBLOCK (pblock->block) = block; } opblock = pblock; } block_set_using (block, using_directives, &objfile->objfile_obstack); using_directives = NULL; record_pending_block (objfile, block, opblock); return block; } struct block * finish_block (struct symbol *symbol, struct pending **listhead, struct pending_block *old_blocks, CORE_ADDR start, CORE_ADDR end) { return finish_block_internal (symbol, listhead, old_blocks, start, end, 0, 0); } /* Record BLOCK on the list of all blocks in the file. Put it after OPBLOCK, or at the beginning if opblock is NULL. This puts the block in the list after all its subblocks. Allocate the pending block struct in the objfile_obstack to save time. This wastes a little space. FIXME: Is it worth it? */ static void record_pending_block (struct objfile *objfile, struct block *block, struct pending_block *opblock) { struct pending_block *pblock; if (pending_blocks == NULL) obstack_init (&pending_block_obstack); pblock = (struct pending_block *) obstack_alloc (&pending_block_obstack, sizeof (struct pending_block)); pblock->block = block; if (opblock) { pblock->next = opblock->next; opblock->next = pblock; } else { pblock->next = pending_blocks; pending_blocks = pblock; } } /* Record that the range of addresses from START to END_INCLUSIVE (inclusive, like it says) belongs to BLOCK. BLOCK's start and end addresses must be set already. You must apply this function to all BLOCK's children before applying it to BLOCK. If a call to this function complicates the picture beyond that already provided by BLOCK_START and BLOCK_END, then we create an address map for the block. */ void record_block_range (struct block *block, CORE_ADDR start, CORE_ADDR end_inclusive) { /* If this is any different from the range recorded in the block's own BLOCK_START and BLOCK_END, then note that the address map has become interesting. Note that even if this block doesn't have any "interesting" ranges, some later block might, so we still need to record this block in the addrmap. */ if (start != BLOCK_START (block) || end_inclusive + 1 != BLOCK_END (block)) pending_addrmap_interesting = 1; if (! pending_addrmap) { obstack_init (&pending_addrmap_obstack); pending_addrmap = addrmap_create_mutable (&pending_addrmap_obstack); } addrmap_set_empty (pending_addrmap, start, end_inclusive, block); } static struct blockvector * make_blockvector (void) { struct objfile *objfile = buildsym_compunit->objfile; struct pending_block *next; struct blockvector *blockvector; int i; /* Count the length of the list of blocks. */ for (next = pending_blocks, i = 0; next; next = next->next, i++) {; } blockvector = (struct blockvector *) obstack_alloc (&objfile->objfile_obstack, (sizeof (struct blockvector) + (i - 1) * sizeof (struct block *))); /* Copy the blocks into the blockvector. This is done in reverse order, which happens to put the blocks into the proper order (ascending starting address). finish_block has hair to insert each block into the list after its subblocks in order to make sure this is true. */ BLOCKVECTOR_NBLOCKS (blockvector) = i; for (next = pending_blocks; next; next = next->next) { BLOCKVECTOR_BLOCK (blockvector, --i) = next->block; } free_pending_blocks (); /* If we needed an address map for this symtab, record it in the blockvector. */ if (pending_addrmap && pending_addrmap_interesting) BLOCKVECTOR_MAP (blockvector) = addrmap_create_fixed (pending_addrmap, &objfile->objfile_obstack); else BLOCKVECTOR_MAP (blockvector) = 0; /* Some compilers output blocks in the wrong order, but we depend on their being in the right order so we can binary search. Check the order and moan about it. Note: Remember that the first two blocks are the global and static blocks. We could special case that fact and begin checking at block 2. To avoid making that assumption we do not. */ if (BLOCKVECTOR_NBLOCKS (blockvector) > 1) { for (i = 1; i < BLOCKVECTOR_NBLOCKS (blockvector); i++) { if (BLOCK_START (BLOCKVECTOR_BLOCK (blockvector, i - 1)) > BLOCK_START (BLOCKVECTOR_BLOCK (blockvector, i))) { CORE_ADDR start = BLOCK_START (BLOCKVECTOR_BLOCK (blockvector, i)); complaint (&symfile_complaints, _("block at %s out of order"), hex_string ((LONGEST) start)); } } } return (blockvector); } /* Start recording information about source code that came from an included (or otherwise merged-in) source file with a different name. NAME is the name of the file (cannot be NULL). */ void start_subfile (const char *name) { const char *subfile_dirname; struct subfile *subfile; gdb_assert (buildsym_compunit != NULL); subfile_dirname = buildsym_compunit->comp_dir; /* See if this subfile is already registered. */ for (subfile = buildsym_compunit->subfiles; subfile; subfile = subfile->next) { char *subfile_name; /* If NAME is an absolute path, and this subfile is not, then attempt to create an absolute path to compare. */ if (IS_ABSOLUTE_PATH (name) && !IS_ABSOLUTE_PATH (subfile->name) && subfile_dirname != NULL) subfile_name = concat (subfile_dirname, SLASH_STRING, subfile->name, (char *) NULL); else subfile_name = subfile->name; if (FILENAME_CMP (subfile_name, name) == 0) { current_subfile = subfile; if (subfile_name != subfile->name) xfree (subfile_name); return; } if (subfile_name != subfile->name) xfree (subfile_name); } /* This subfile is not known. Add an entry for it. */ subfile = (struct subfile *) xmalloc (sizeof (struct subfile)); memset (subfile, 0, sizeof (struct subfile)); subfile->buildsym_compunit = buildsym_compunit; subfile->next = buildsym_compunit->subfiles; buildsym_compunit->subfiles = subfile; current_subfile = subfile; subfile->name = xstrdup (name); /* Initialize line-number recording for this subfile. */ subfile->line_vector = NULL; /* Default the source language to whatever can be deduced from the filename. If nothing can be deduced (such as for a C/C++ include file with a ".h" extension), then inherit whatever language the previous subfile had. This kludgery is necessary because there is no standard way in some object formats to record the source language. Also, when symtabs are allocated we try to deduce a language then as well, but it is too late for us to use that information while reading symbols, since symtabs aren't allocated until after all the symbols have been processed for a given source file. */ subfile->language = deduce_language_from_filename (subfile->name); if (subfile->language == language_unknown && subfile->next != NULL) { subfile->language = subfile->next->language; } /* If the filename of this subfile ends in .C, then change the language of any pending subfiles from C to C++. We also accept any other C++ suffixes accepted by deduce_language_from_filename. */ /* Likewise for f2c. */ if (subfile->name) { struct subfile *s; enum language sublang = deduce_language_from_filename (subfile->name); if (sublang == language_cplus || sublang == language_fortran) for (s = buildsym_compunit->subfiles; s != NULL; s = s->next) if (s->language == language_c) s->language = sublang; } /* And patch up this file if necessary. */ if (subfile->language == language_c && subfile->next != NULL && (subfile->next->language == language_cplus || subfile->next->language == language_fortran)) { subfile->language = subfile->next->language; } } /* Start recording information about a primary source file (IOW, not an included source file). COMP_DIR is the directory in which the compilation unit was compiled (or NULL if not known). */ static struct buildsym_compunit * start_buildsym_compunit (struct objfile *objfile, const char *comp_dir) { struct buildsym_compunit *bscu; bscu = (struct buildsym_compunit *) xmalloc (sizeof (struct buildsym_compunit)); memset (bscu, 0, sizeof (struct buildsym_compunit)); bscu->objfile = objfile; bscu->comp_dir = (comp_dir == NULL) ? NULL : xstrdup (comp_dir); /* Initialize the debug format string to NULL. We may supply it later via a call to record_debugformat. */ bscu->debugformat = NULL; /* Similarly for the producer. */ bscu->producer = NULL; return bscu; } /* Delete the buildsym compunit. */ static void free_buildsym_compunit (void) { struct subfile *subfile, *nextsub; if (buildsym_compunit == NULL) return; for (subfile = buildsym_compunit->subfiles; subfile != NULL; subfile = nextsub) { nextsub = subfile->next; xfree (subfile->name); xfree (subfile->line_vector); xfree (subfile); } xfree (buildsym_compunit->comp_dir); xfree (buildsym_compunit); buildsym_compunit = NULL; current_subfile = NULL; } /* For stabs readers, the first N_SO symbol is assumed to be the source file name, and the subfile struct is initialized using that assumption. If another N_SO symbol is later seen, immediately following the first one, then the first one is assumed to be the directory name and the second one is really the source file name. So we have to patch up the subfile struct by moving the old name value to dirname and remembering the new name. Some sanity checking is performed to ensure that the state of the subfile struct is reasonable and that the old name we are assuming to be a directory name actually is (by checking for a trailing '/'). */ void patch_subfile_names (struct subfile *subfile, char *name) { if (subfile != NULL && buildsym_compunit->comp_dir == NULL && subfile->name != NULL && IS_DIR_SEPARATOR (subfile->name[strlen (subfile->name) - 1])) { buildsym_compunit->comp_dir = subfile->name; subfile->name = xstrdup (name); set_last_source_file (name); /* Default the source language to whatever can be deduced from the filename. If nothing can be deduced (such as for a C/C++ include file with a ".h" extension), then inherit whatever language the previous subfile had. This kludgery is necessary because there is no standard way in some object formats to record the source language. Also, when symtabs are allocated we try to deduce a language then as well, but it is too late for us to use that information while reading symbols, since symtabs aren't allocated until after all the symbols have been processed for a given source file. */ subfile->language = deduce_language_from_filename (subfile->name); if (subfile->language == language_unknown && subfile->next != NULL) { subfile->language = subfile->next->language; } } } /* Handle the N_BINCL and N_EINCL symbol types that act like N_SOL for switching source files (different subfiles, as we call them) within one object file, but using a stack rather than in an arbitrary order. */ void push_subfile (void) { struct subfile_stack *tem = (struct subfile_stack *) xmalloc (sizeof (struct subfile_stack)); tem->next = subfile_stack; subfile_stack = tem; if (current_subfile == NULL || current_subfile->name == NULL) { internal_error (__FILE__, __LINE__, _("failed internal consistency check")); } tem->name = current_subfile->name; } char * pop_subfile (void) { char *name; struct subfile_stack *link = subfile_stack; if (link == NULL) { internal_error (__FILE__, __LINE__, _("failed internal consistency check")); } name = link->name; subfile_stack = link->next; xfree ((void *) link); return (name); } /* Add a linetable entry for line number LINE and address PC to the line vector for SUBFILE. */ void record_line (struct subfile *subfile, int line, CORE_ADDR pc) { struct linetable_entry *e; /* Ignore the dummy line number in libg.o */ if (line == 0xffff) { return; } /* Make sure line vector exists and is big enough. */ if (!subfile->line_vector) { subfile->line_vector_length = INITIAL_LINE_VECTOR_LENGTH; subfile->line_vector = (struct linetable *) xmalloc (sizeof (struct linetable) + subfile->line_vector_length * sizeof (struct linetable_entry)); subfile->line_vector->nitems = 0; have_line_numbers = 1; } if (subfile->line_vector->nitems + 1 >= subfile->line_vector_length) { subfile->line_vector_length *= 2; subfile->line_vector = (struct linetable *) xrealloc ((char *) subfile->line_vector, (sizeof (struct linetable) + (subfile->line_vector_length * sizeof (struct linetable_entry)))); } /* Normally, we treat lines as unsorted. But the end of sequence marker is special. We sort line markers at the same PC by line number, so end of sequence markers (which have line == 0) appear first. This is right if the marker ends the previous function, and there is no padding before the next function. But it is wrong if the previous line was empty and we are now marking a switch to a different subfile. We must leave the end of sequence marker at the end of this group of lines, not sort the empty line to after the marker. The easiest way to accomplish this is to delete any empty lines from our table, if they are followed by end of sequence markers. All we lose is the ability to set breakpoints at some lines which contain no instructions anyway. */ if (line == 0 && subfile->line_vector->nitems > 0) { e = subfile->line_vector->item + subfile->line_vector->nitems - 1; while (subfile->line_vector->nitems > 0 && e->pc == pc) { e--; subfile->line_vector->nitems--; } } e = subfile->line_vector->item + subfile->line_vector->nitems++; e->line = line; e->pc = pc; } /* Needed in order to sort line tables from IBM xcoff files. Sigh! */ static int compare_line_numbers (const void *ln1p, const void *ln2p) { struct linetable_entry *ln1 = (struct linetable_entry *) ln1p; struct linetable_entry *ln2 = (struct linetable_entry *) ln2p; /* Note: this code does not assume that CORE_ADDRs can fit in ints. Please keep it that way. */ if (ln1->pc < ln2->pc) return -1; if (ln1->pc > ln2->pc) return 1; /* If pc equal, sort by line. I'm not sure whether this is optimum behavior (see comment at struct linetable in symtab.h). */ return ln1->line - ln2->line; } /* See buildsym.h. */ struct compunit_symtab * buildsym_compunit_symtab (void) { gdb_assert (buildsym_compunit != NULL); return buildsym_compunit->compunit_symtab; } /* See buildsym.h. */ struct macro_table * get_macro_table (void) { struct objfile *objfile; gdb_assert (buildsym_compunit != NULL); objfile = buildsym_compunit->objfile; if (! pending_macros) { pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack, objfile->per_bfd->macro_cache, buildsym_compunit->compunit_symtab); } return pending_macros; } /* Init state to prepare for building a symtab. Note: This can't be done in buildsym_init because dbxread.c and xcoffread.c can call start_symtab+end_symtab multiple times after one call to buildsym_init. */ static void prepare_for_building (const char *name, CORE_ADDR start_addr) { set_last_source_file (name); last_source_start_addr = start_addr; local_symbols = NULL; within_function = 0; have_line_numbers = 0; context_stack_depth = 0; /* These should have been reset either by successful completion of building a symtab, or by the really_free_pendings cleanup. */ gdb_assert (file_symbols == NULL); gdb_assert (global_symbols == NULL); gdb_assert (pending_macros == NULL); gdb_assert (pending_addrmap == NULL); gdb_assert (current_subfile == NULL); } /* Start a new symtab for a new source file in OBJFILE. Called, for example, when a stabs symbol of type N_SO is seen, or when a DWARF TAG_compile_unit DIE is seen. It indicates the start of data for one original source file. NAME is the name of the file (cannot be NULL). COMP_DIR is the directory in which the file was compiled (or NULL if not known). START_ADDR is the lowest address of objects in the file (or 0 if not known). */ struct compunit_symtab * start_symtab (struct objfile *objfile, const char *name, const char *comp_dir, CORE_ADDR start_addr) { prepare_for_building (name, start_addr); buildsym_compunit = start_buildsym_compunit (objfile, comp_dir); /* Allocate the compunit symtab now. The caller needs it to allocate non-primary symtabs. It is also needed by get_macro_table. */ buildsym_compunit->compunit_symtab = allocate_compunit_symtab (objfile, name); /* Build the subfile for NAME (the main source file) so that we can record a pointer to it for later. IMPORTANT: Do not allocate a struct symtab for NAME here. It can happen that the debug info provides a different path to NAME than DIRNAME,NAME. We cope with this in watch_main_source_file_lossage but that only works if the main_subfile doesn't have a symtab yet. */ start_subfile (name); /* Save this so that we don't have to go looking for it at the end of the subfiles list. */ buildsym_compunit->main_subfile = current_subfile; return buildsym_compunit->compunit_symtab; } /* Restart compilation for a symtab. CUST is the result of end_expandable_symtab. NAME, START_ADDR are the source file we are resuming with. This is used when a symtab is built from multiple sources. The symtab is first built with start_symtab/end_expandable_symtab and then for each additional piece call restart_symtab/augment_*_symtab. Note: At the moment there is only augment_type_symtab. */ void restart_symtab (struct compunit_symtab *cust, const char *name, CORE_ADDR start_addr) { prepare_for_building (name, start_addr); buildsym_compunit = start_buildsym_compunit (COMPUNIT_OBJFILE (cust), COMPUNIT_DIRNAME (cust)); buildsym_compunit->compunit_symtab = cust; } /* Subroutine of end_symtab to simplify it. Look for a subfile that matches the main source file's basename. If there is only one, and if the main source file doesn't have any symbol or line number information, then copy this file's symtab and line_vector to the main source file's subfile and discard the other subfile. This can happen because of a compiler bug or from the user playing games with #line or from things like a distributed build system that manipulates the debug info. This can also happen from an innocent symlink in the paths, we don't canonicalize paths here. */ static void watch_main_source_file_lossage (void) { struct subfile *mainsub, *subfile; /* We have to watch for buildsym_compunit == NULL here. It's a quirk of end_symtab, it can return NULL so there may not be a main subfile. */ if (buildsym_compunit == NULL) return; /* Get the main source file. */ mainsub = buildsym_compunit->main_subfile; /* If the main source file doesn't have any line number or symbol info, look for an alias in another subfile. */ if (mainsub->line_vector == NULL && mainsub->symtab == NULL) { const char *mainbase = lbasename (mainsub->name); int nr_matches = 0; struct subfile *prevsub; struct subfile *mainsub_alias = NULL; struct subfile *prev_mainsub_alias = NULL; prevsub = NULL; for (subfile = buildsym_compunit->subfiles; subfile != NULL; subfile = subfile->next) { if (subfile == mainsub) continue; if (filename_cmp (lbasename (subfile->name), mainbase) == 0) { ++nr_matches; mainsub_alias = subfile; prev_mainsub_alias = prevsub; } prevsub = subfile; } if (nr_matches == 1) { gdb_assert (mainsub_alias != NULL && mainsub_alias != mainsub); /* Found a match for the main source file. Copy its line_vector and symtab to the main subfile and then discard it. */ mainsub->line_vector = mainsub_alias->line_vector; mainsub->line_vector_length = mainsub_alias->line_vector_length; mainsub->symtab = mainsub_alias->symtab; if (prev_mainsub_alias == NULL) buildsym_compunit->subfiles = mainsub_alias->next; else prev_mainsub_alias->next = mainsub_alias->next; xfree (mainsub_alias->name); xfree (mainsub_alias); } } } /* Helper function for qsort. Parameters are `struct block *' pointers, function sorts them in descending order by their BLOCK_START. */ static int block_compar (const void *ap, const void *bp) { const struct block *a = *(const struct block **) ap; const struct block *b = *(const struct block **) bp; return ((BLOCK_START (b) > BLOCK_START (a)) - (BLOCK_START (b) < BLOCK_START (a))); } /* Reset state after a successful building of a symtab. This exists because dbxread.c and xcoffread.c can call start_symtab+end_symtab multiple times after one call to buildsym_init, and before the really_free_pendings cleanup is called. We keep the free_pendings list around for dbx/xcoff sake. */ static void reset_symtab_globals (void) { set_last_source_file (NULL); local_symbols = NULL; file_symbols = NULL; global_symbols = NULL; /* We don't free pending_macros here because if the symtab was successfully built then ownership was transferred to the symtab. */ pending_macros = NULL; if (pending_addrmap) obstack_free (&pending_addrmap_obstack, NULL); pending_addrmap = NULL; free_buildsym_compunit (); } /* Implementation of the first part of end_symtab. It allows modifying STATIC_BLOCK before it gets finalized by end_symtab_from_static_block. If the returned value is NULL there is no blockvector created for this symtab (you still must call end_symtab_from_static_block). END_ADDR is the same as for end_symtab: the address of the end of the file's text. If EXPANDABLE is non-zero the STATIC_BLOCK dictionary is made expandable. If REQUIRED is non-zero, then a symtab is created even if it does not contain any symbols. */ struct block * end_symtab_get_static_block (CORE_ADDR end_addr, int expandable, int required) { struct objfile *objfile = buildsym_compunit->objfile; /* Finish the lexical context of the last function in the file; pop the context stack. */ if (context_stack_depth > 0) { struct context_stack *cstk = pop_context (); /* Make a block for the local symbols within. */ finish_block (cstk->name, &local_symbols, cstk->old_blocks, cstk->start_addr, end_addr); if (context_stack_depth > 0) { /* This is said to happen with SCO. The old coffread.c code simply emptied the context stack, so we do the same. FIXME: Find out why it is happening. This is not believed to happen in most cases (even for coffread.c); it used to be an abort(). */ complaint (&symfile_complaints, _("Context stack not empty in end_symtab")); context_stack_depth = 0; } } /* Reordered executables may have out of order pending blocks; if OBJF_REORDERED is true, then sort the pending blocks. */ if ((objfile->flags & OBJF_REORDERED) && pending_blocks) { unsigned count = 0; struct pending_block *pb; struct block **barray, **bp; struct cleanup *back_to; for (pb = pending_blocks; pb != NULL; pb = pb->next) count++; barray = xmalloc (sizeof (*barray) * count); back_to = make_cleanup (xfree, barray); bp = barray; for (pb = pending_blocks; pb != NULL; pb = pb->next) *bp++ = pb->block; qsort (barray, count, sizeof (*barray), block_compar); bp = barray; for (pb = pending_blocks; pb != NULL; pb = pb->next) pb->block = *bp++; do_cleanups (back_to); } /* Cleanup any undefined types that have been left hanging around (this needs to be done before the finish_blocks so that file_symbols is still good). Both cleanup_undefined_stabs_types and finish_global_stabs are stabs specific, but harmless for other symbol readers, since on gdb startup or when finished reading stabs, the state is set so these are no-ops. FIXME: Is this handled right in case of QUIT? Can we make this cleaner? */ cleanup_undefined_stabs_types (objfile); finish_global_stabs (objfile); if (!required && pending_blocks == NULL && file_symbols == NULL && global_symbols == NULL && have_line_numbers == 0 && pending_macros == NULL) { /* Ignore symtabs that have no functions with real debugging info. */ return NULL; } else { /* Define the STATIC_BLOCK. */ return finish_block_internal (NULL, &file_symbols, NULL, last_source_start_addr, end_addr, 0, expandable); } } /* Subroutine of end_symtab_from_static_block to simplify it. Handle the "have blockvector" case. See end_symtab_from_static_block for a description of the arguments. */ static struct compunit_symtab * end_symtab_with_blockvector (struct block *static_block, int section, int expandable) { struct objfile *objfile = buildsym_compunit->objfile; struct compunit_symtab *cu = buildsym_compunit->compunit_symtab; struct symtab *symtab; struct blockvector *blockvector; struct subfile *subfile; CORE_ADDR end_addr; gdb_assert (static_block != NULL); gdb_assert (buildsym_compunit != NULL); gdb_assert (buildsym_compunit->subfiles != NULL); end_addr = BLOCK_END (static_block); /* Create the GLOBAL_BLOCK and build the blockvector. */ finish_block_internal (NULL, &global_symbols, NULL, last_source_start_addr, end_addr, 1, expandable); blockvector = make_blockvector (); /* Read the line table if it has to be read separately. This is only used by xcoffread.c. */ if (objfile->sf->sym_read_linetable != NULL) objfile->sf->sym_read_linetable (objfile); /* Handle the case where the debug info specifies a different path for the main source file. It can cause us to lose track of its line number information. */ watch_main_source_file_lossage (); /* Now create the symtab objects proper, if not already done, one for each subfile. */ for (subfile = buildsym_compunit->subfiles; subfile != NULL; subfile = subfile->next) { int linetablesize = 0; if (subfile->line_vector) { linetablesize = sizeof (struct linetable) + subfile->line_vector->nitems * sizeof (struct linetable_entry); /* Like the pending blocks, the line table may be scrambled in reordered executables. Sort it if OBJF_REORDERED is true. */ if (objfile->flags & OBJF_REORDERED) qsort (subfile->line_vector->item, subfile->line_vector->nitems, sizeof (struct linetable_entry), compare_line_numbers); } /* Allocate a symbol table if necessary. */ if (subfile->symtab == NULL) subfile->symtab = allocate_symtab (cu, subfile->name); symtab = subfile->symtab; /* Fill in its components. */ if (subfile->line_vector) { /* Reallocate the line table on the symbol obstack. */ SYMTAB_LINETABLE (symtab) = (struct linetable *) obstack_alloc (&objfile->objfile_obstack, linetablesize); memcpy (SYMTAB_LINETABLE (symtab), subfile->line_vector, linetablesize); } else { SYMTAB_LINETABLE (symtab) = NULL; } /* Use whatever language we have been using for this subfile, not the one that was deduced in allocate_symtab from the filename. We already did our own deducing when we created the subfile, and we may have altered our opinion of what language it is from things we found in the symbols. */ symtab->language = subfile->language; } /* Make sure the symtab of main_subfile is the first in its list. */ { struct symtab *main_symtab, *prev_symtab; main_symtab = buildsym_compunit->main_subfile->symtab; prev_symtab = NULL; ALL_COMPUNIT_FILETABS (cu, symtab) { if (symtab == main_symtab) { if (prev_symtab != NULL) { prev_symtab->next = main_symtab->next; main_symtab->next = COMPUNIT_FILETABS (cu); COMPUNIT_FILETABS (cu) = main_symtab; } break; } prev_symtab = symtab; } gdb_assert (main_symtab == COMPUNIT_FILETABS (cu)); } /* Fill out the compunit symtab. */ if (buildsym_compunit->comp_dir != NULL) { /* Reallocate the dirname on the symbol obstack. */ COMPUNIT_DIRNAME (cu) = obstack_copy0 (&objfile->objfile_obstack, buildsym_compunit->comp_dir, strlen (buildsym_compunit->comp_dir)); } /* Save the debug format string (if any) in the symtab. */ COMPUNIT_DEBUGFORMAT (cu) = buildsym_compunit->debugformat; /* Similarly for the producer. */ COMPUNIT_PRODUCER (cu) = buildsym_compunit->producer; COMPUNIT_BLOCKVECTOR (cu) = blockvector; { struct block *b = BLOCKVECTOR_BLOCK (blockvector, GLOBAL_BLOCK); set_block_compunit_symtab (b, cu); } COMPUNIT_BLOCK_LINE_SECTION (cu) = section; COMPUNIT_MACRO_TABLE (cu) = pending_macros; /* Default any symbols without a specified symtab to the primary symtab. */ { int block_i; /* The main source file's symtab. */ symtab = COMPUNIT_FILETABS (cu); for (block_i = 0; block_i < BLOCKVECTOR_NBLOCKS (blockvector); block_i++) { struct block *block = BLOCKVECTOR_BLOCK (blockvector, block_i); struct symbol *sym; struct dict_iterator iter; /* Inlined functions may have symbols not in the global or static symbol lists. */ if (BLOCK_FUNCTION (block) != NULL) if (symbol_symtab (BLOCK_FUNCTION (block)) == NULL) symbol_set_symtab (BLOCK_FUNCTION (block), symtab); /* Note that we only want to fix up symbols from the local blocks, not blocks coming from included symtabs. That is why we use ALL_DICT_SYMBOLS here and not ALL_BLOCK_SYMBOLS. */ ALL_DICT_SYMBOLS (BLOCK_DICT (block), iter, sym) if (symbol_symtab (sym) == NULL) symbol_set_symtab (sym, symtab); } } add_compunit_symtab_to_objfile (cu); return cu; } /* Implementation of the second part of end_symtab. Pass STATIC_BLOCK as value returned by end_symtab_get_static_block. SECTION is the same as for end_symtab: the section number (in objfile->section_offsets) of the blockvector and linetable. If EXPANDABLE is non-zero the GLOBAL_BLOCK dictionary is made expandable. */ struct compunit_symtab * end_symtab_from_static_block (struct block *static_block, int section, int expandable) { struct compunit_symtab *cu; if (static_block == NULL) { /* Handle the "no blockvector" case. When this happens there is nothing to record, so there's nothing to do: memory will be freed up later. Note: We won't be adding a compunit to the objfile's list of compunits, so there's nothing to unchain. However, since each symtab is added to the objfile's obstack we can't free that space. We could do better, but this is believed to be a sufficiently rare event. */ cu = NULL; } else cu = end_symtab_with_blockvector (static_block, section, expandable); reset_symtab_globals (); return cu; } /* Finish the symbol definitions for one main source file, close off all the lexical contexts for that file (creating struct block's for them), then make the struct symtab for that file and put it in the list of all such. END_ADDR is the address of the end of the file's text. SECTION is the section number (in objfile->section_offsets) of the blockvector and linetable. Note that it is possible for end_symtab() to return NULL. In particular, for the DWARF case at least, it will return NULL when it finds a compilation unit that has exactly one DIE, a TAG_compile_unit DIE. This can happen when we link in an object file that was compiled from an empty source file. Returning NULL is probably not the correct thing to do, because then gdb will never know about this empty file (FIXME). If you need to modify STATIC_BLOCK before it is finalized you should call end_symtab_get_static_block and end_symtab_from_static_block yourself. */ struct compunit_symtab * end_symtab (CORE_ADDR end_addr, int section) { struct block *static_block; static_block = end_symtab_get_static_block (end_addr, 0, 0); return end_symtab_from_static_block (static_block, section, 0); } /* Same as end_symtab except create a symtab that can be later added to. */ struct compunit_symtab * end_expandable_symtab (CORE_ADDR end_addr, int section) { struct block *static_block; static_block = end_symtab_get_static_block (end_addr, 1, 0); return end_symtab_from_static_block (static_block, section, 1); } /* Subroutine of augment_type_symtab to simplify it. Attach the main source file's symtab to all symbols in PENDING_LIST that don't have one. */ static void set_missing_symtab (struct pending *pending_list, struct compunit_symtab *cu) { struct pending *pending; int i; for (pending = pending_list; pending != NULL; pending = pending->next) { for (i = 0; i < pending->nsyms; ++i) { if (symbol_symtab (pending->symbol[i]) == NULL) symbol_set_symtab (pending->symbol[i], COMPUNIT_FILETABS (cu)); } } } /* Same as end_symtab, but for the case where we're adding more symbols to an existing symtab that is known to contain only type information. This is the case for DWARF4 Type Units. */ void augment_type_symtab (void) { struct compunit_symtab *cust = buildsym_compunit->compunit_symtab; const struct blockvector *blockvector = COMPUNIT_BLOCKVECTOR (cust); if (context_stack_depth > 0) { complaint (&symfile_complaints, _("Context stack not empty in augment_type_symtab")); context_stack_depth = 0; } if (pending_blocks != NULL) complaint (&symfile_complaints, _("Blocks in a type symtab")); if (pending_macros != NULL) complaint (&symfile_complaints, _("Macro in a type symtab")); if (have_line_numbers) complaint (&symfile_complaints, _("Line numbers recorded in a type symtab")); if (file_symbols != NULL) { struct block *block = BLOCKVECTOR_BLOCK (blockvector, STATIC_BLOCK); /* First mark any symbols without a specified symtab as belonging to the primary symtab. */ set_missing_symtab (file_symbols, cust); dict_add_pending (BLOCK_DICT (block), file_symbols); } if (global_symbols != NULL) { struct block *block = BLOCKVECTOR_BLOCK (blockvector, GLOBAL_BLOCK); /* First mark any symbols without a specified symtab as belonging to the primary symtab. */ set_missing_symtab (global_symbols, cust); dict_add_pending (BLOCK_DICT (block), global_symbols); } reset_symtab_globals (); } /* Push a context block. Args are an identifying nesting level (checkable when you pop it), and the starting PC address of this context. */ struct context_stack * push_context (int desc, CORE_ADDR valu) { struct context_stack *new; if (context_stack_depth == context_stack_size) { context_stack_size *= 2; context_stack = (struct context_stack *) xrealloc ((char *) context_stack, (context_stack_size * sizeof (struct context_stack))); } new = &context_stack[context_stack_depth++]; new->depth = desc; new->locals = local_symbols; new->old_blocks = pending_blocks; new->start_addr = valu; new->using_directives = using_directives; new->name = NULL; local_symbols = NULL; using_directives = NULL; return new; } /* Pop a context block. Returns the address of the context block just popped. */ struct context_stack * pop_context (void) { gdb_assert (context_stack_depth > 0); return (&context_stack[--context_stack_depth]); } /* Compute a small integer hash code for the given name. */ int hashname (const char *name) { return (hash(name,strlen(name)) % HASHSIZE); } void record_debugformat (const char *format) { buildsym_compunit->debugformat = format; } void record_producer (const char *producer) { buildsym_compunit->producer = producer; } /* Merge the first symbol list SRCLIST into the second symbol list TARGETLIST by repeated calls to add_symbol_to_list(). This procedure "frees" each link of SRCLIST by adding it to the free_pendings list. Caller must set SRCLIST to a null list after calling this function. Void return. */ void merge_symbol_lists (struct pending **srclist, struct pending **targetlist) { int i; if (!srclist || !*srclist) return; /* Merge in elements from current link. */ for (i = 0; i < (*srclist)->nsyms; i++) add_symbol_to_list ((*srclist)->symbol[i], targetlist); /* Recurse on next. */ merge_symbol_lists (&(*srclist)->next, targetlist); /* "Free" the current link. */ (*srclist)->next = free_pendings; free_pendings = (*srclist); } /* Name of source file whose symbol data we are now processing. This comes from a symbol of type N_SO for stabs. For Dwarf it comes from the DW_AT_name attribute of a DW_TAG_compile_unit DIE. */ static char *last_source_file; /* See buildsym.h. */ void set_last_source_file (const char *name) { xfree (last_source_file); last_source_file = name == NULL ? NULL : xstrdup (name); } /* See buildsym.h. */ const char * get_last_source_file (void) { return last_source_file; } /* Initialize anything that needs initializing when starting to read a fresh piece of a symbol file, e.g. reading in the stuff corresponding to a psymtab. */ void buildsym_init (void) { using_directives = NULL; subfile_stack = NULL; pending_addrmap_interesting = 0; /* Context stack is initially empty. Allocate first one with room for a few levels; reuse it forever afterward. */ if (context_stack == NULL) { context_stack_size = INITIAL_CONTEXT_STACK_SIZE; context_stack = (struct context_stack *) xmalloc (context_stack_size * sizeof (struct context_stack)); } /* Ensure the really_free_pendings cleanup was called after the last time. */ gdb_assert (free_pendings == NULL); gdb_assert (pending_blocks == NULL); gdb_assert (file_symbols == NULL); gdb_assert (global_symbols == NULL); gdb_assert (pending_macros == NULL); gdb_assert (pending_addrmap == NULL); gdb_assert (buildsym_compunit == NULL); } /* Initialize anything that needs initializing when a completely new symbol file is specified (not just adding some symbols from another file, e.g. a shared library). */ void buildsym_new_init (void) { buildsym_init (); }
30.322454
79
0.691647
[ "object", "vector" ]
bb3f810a4c2269d58267730ea97694916de2a899
2,936
h
C
cc/input/scrollbar_animation_controller.h
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
cc/input/scrollbar_animation_controller.h
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
cc/input/scrollbar_animation_controller.h
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CC_INPUT_SCROLLBAR_ANIMATION_CONTROLLER_H_ #define CC_INPUT_SCROLLBAR_ANIMATION_CONTROLLER_H_ #include "base/cancelable_callback.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "cc/base/cc_export.h" #include "cc/layers/layer_impl.h" #include "cc/layers/scrollbar_layer_impl_base.h" #include "ui/gfx/geometry/vector2d_f.h" namespace cc { class ScrollbarAnimationController; class CC_EXPORT ScrollbarAnimationControllerClient { public: virtual void PostDelayedScrollbarAnimationTask(const base::Closure& task, base::TimeDelta delay) = 0; virtual void SetNeedsRedrawForScrollbarAnimation() = 0; virtual void SetNeedsAnimateForScrollbarAnimation() = 0; virtual void DidChangeScrollbarVisibility() = 0; virtual ScrollbarSet ScrollbarsFor(int scroll_layer_id) const = 0; protected: virtual ~ScrollbarAnimationControllerClient() {} }; // This abstract class represents the compositor-side analogy of // ScrollbarAnimator. Individual platforms should subclass it to provide // specialized implementation. class CC_EXPORT ScrollbarAnimationController { public: virtual ~ScrollbarAnimationController(); bool Animate(base::TimeTicks now); virtual void DidScrollBegin(); virtual void DidScrollUpdate(bool on_resize); virtual void DidScrollEnd(); virtual void DidMouseDown() {} virtual void DidMouseUp() {} virtual void DidMouseLeave() {} virtual void DidMouseMoveNear(float distance) {} virtual bool ScrollbarsHidden() const; protected: ScrollbarAnimationController(int scroll_layer_id, ScrollbarAnimationControllerClient* client, base::TimeDelta delay_before_starting, base::TimeDelta resize_delay_before_starting); virtual void RunAnimationFrame(float progress) = 0; virtual const base::TimeDelta& Duration() = 0; void StartAnimation(); void StopAnimation(); ScrollbarSet Scrollbars() const; ScrollbarAnimationControllerClient* client_; void PostDelayedAnimationTask(bool on_resize); int scroll_layer_id() const { return scroll_layer_id_; } private: // Returns how far through the animation we are as a progress value from // 0 to 1. float AnimationProgressAtTime(base::TimeTicks now); base::TimeTicks last_awaken_time_; base::TimeDelta delay_before_starting_; base::TimeDelta resize_delay_before_starting_; bool is_animating_; int scroll_layer_id_; bool currently_scrolling_; bool scroll_gesture_has_scrolled_; base::CancelableClosure delayed_scrollbar_fade_; base::WeakPtrFactory<ScrollbarAnimationController> weak_factory_; }; } // namespace cc #endif // CC_INPUT_SCROLLBAR_ANIMATION_CONTROLLER_H_
31.913043
77
0.757493
[ "geometry" ]
bb3fb19d65c66ceebf409c8d097ec31b7b1f1d89
948
h
C
Samples/AppWindow/cppwinrt/Code/CLS/Corner.h
OSIREM/ecoin-minimal
7d8314484c0cd47c673046c86c273cc48eaa43d2
[ "MIT" ]
null
null
null
Samples/AppWindow/cppwinrt/Code/CLS/Corner.h
OSIREM/ecoin-minimal
7d8314484c0cd47c673046c86c273cc48eaa43d2
[ "MIT" ]
null
null
null
Samples/AppWindow/cppwinrt/Code/CLS/Corner.h
OSIREM/ecoin-minimal
7d8314484c0cd47c673046c86c273cc48eaa43d2
[ "MIT" ]
null
null
null
/* Code - osirem.com Copyright OSIREM LTD (C) 2016 bitolyl.com bitcoin-office.com ecn.world This source is proprietary, and cannot be used, in part or in full without the express permission of the original author. The original author retain the rights to use, modify, and/or relicense this code without notice. */ #ifndef CORNER_H #define CORNER_H #include <vector> #include <math.h> #include "Include/Cube.h" #include "Element.h" using namespace Cube; namespace ecoin { enum CLS_CornerType { CLS_Corner }; class classCorner { public: classCorner(); ~classCorner(); void acMake(void); void acSpecify(shared_ptr<BiVector> f_Corner, shared_ptr<BiVector> f_X, shared_ptr<BiVector> f_Y, shared_ptr<BiVector> f_Z); bool acClassify(void); shared_ptr<BiVector> m_Corner; shared_ptr<BiVector> m_X; shared_ptr<BiVector> m_Y; shared_ptr<BiVector> m_Z; }; }; #endif
18.588235
127
0.701477
[ "vector" ]
bb4003dfbb95573976511989b2c3f28fd2ff9956
4,627
h
C
src/PSMDescription.h
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
71
2015-03-30T17:22:52.000Z
2022-01-01T14:19:23.000Z
src/PSMDescription.h
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
190
2015-01-27T16:18:58.000Z
2022-03-31T16:49:58.000Z
src/PSMDescription.h
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
45
2015-04-13T13:42:35.000Z
2021-12-17T08:26:21.000Z
/******************************************************************************* Copyright 2006-2012 Lukas Käll <lukas.kall@scilifelab.se> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ #ifndef PSMDESCRIPTION_H_ #define PSMDESCRIPTION_H_ #include <map> #include <vector> #include <string> #include <iostream> #include "Enzyme.h" /* * PSMDescription * * Here are some useful abbreviations: * PSM - Peptide Spectrum Match * */ class PSMDescription { public: PSMDescription(); PSMDescription(const std::string& peptide); virtual ~PSMDescription(); static void deletePtr(PSMDescription* psm); virtual void deleteRetentionFeatures() {} void clear() { proteinIds.clear(); } double* getFeatures() { return features; } // TODO: move these static functions somewhere else static std::string removePTMs(const std::string& peptideSeq); static std::string removeFlanks(const std::string& peptideSeq) { return peptideSeq.substr(2, peptideSeq.size()-4); } static bool ptrLess(PSMDescription* one, PSMDescription* other) { return *one < *other; } static bool ptrEqual(PSMDescription* one, PSMDescription* other) { return *one == *other; } std::string getPeptideSequence() { return peptide.substr(2, peptide.size()-4); } std::string& getFullPeptideSequence() { return peptide; } std::string getFlankN() { return peptide.substr(0, 1); } std::string getFlankC() { return peptide.substr(peptide.size()-1, peptide.size()); } friend std::ostream& operator<<(std::ostream& out, PSMDescription& psm); void printProteins(std::ostream& out); bool operator<(const PSMDescription& other) const { return (peptide < other.peptide) || (peptide == other.peptide && getRetentionTime() < other.getRetentionTime()); } bool operator==(const PSMDescription& other) const { return (peptide == other.peptide); } virtual inline void setId(const std::string& id) { id_ = id; } virtual inline std::string& getId() { return id_; } // Virtual functions for PSMDescriptionDOC virtual std::string& getFullPeptide() { return peptide; } virtual PSMDescription* getAParent() { return this; } virtual void checkFragmentPeptides( std::vector<PSMDescription*>::reverse_iterator other, std::vector<PSMDescription*>::reverse_iterator theEnd) {} virtual void setRetentionFeatures(double* retentionFeatures) {} virtual double* getRetentionFeatures() { return NULL; } virtual void setParentFragment(PSMDescription* ) {} virtual PSMDescription* getParentFragment() { return NULL; } virtual inline void setRetentionTime(const double retentionTime) {} virtual inline double getRetentionTime() const { return 0.0; } virtual inline void setUnnormalizedRetentionTime(const double retentionTime) {} virtual inline double getUnnormalizedRetentionTime() const { std::cerr << "Warning: no retention time available" << std::endl; return 0.0; } virtual inline void setMassDiff(const double dm) {} virtual inline double getMassDiff() const { std::cerr << "Warning: no mass difference available" << std::endl; return 0.0; } virtual inline void setIsoElectricPoint(const double pI) {} virtual inline double getIsoElectricPoint() const { std::cerr << "Warning: no iso electric point available" << std::endl; return 0.0; } virtual inline void setPredictedRetentionTime(const double predictedTime) {} virtual inline double getPredictedRetentionTime() const { std::cerr << "Warning: no retention time available" << std::endl; return 0.0; } double* features; // owned by a FeatureMemoryPool instance, no need to delete double expMass, calcMass; unsigned int scan; std::string id_; std::string peptide; std::vector<std::string> proteinIds; }; inline std::ostream& operator<<(std::ostream& out, PSMDescription& psm) { out << "Peptide: " << psm.peptide << endl; out << "Spectrum scan number: " << psm.scan << endl; out << endl; return out; } #endif /*PSMDESCRIPTION_H_*/
34.529851
88
0.687703
[ "vector" ]
bb498b2751d2926d04fedf551d01cce6a56eed9c
1,102
h
C
src/Generic/actors/AWAKEGazetteer.h
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/Generic/actors/AWAKEGazetteer.h
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/Generic/actors/AWAKEGazetteer.h
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
// Copyright 2012 by BBN Technologies Corp. // All Rights Reserved. #ifndef KNOWLEDGE_BASE_GAZETTEER_H #define KNOWLEDGE_BASE_GAZETTEER_H #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include "Generic/common/Symbol.h" #include "Generic/actors/Identifiers.h" #include "Generic/actors/Gazetteer.h" #include <vector> #include <boost/regex.hpp> #include <boost/make_shared.hpp> #include <boost/cstdint.hpp> // Forward declaration class DatabaseConnection; class AWAKEGazetteer : public Gazetteer { public: AWAKEGazetteer(); ~AWAKEGazetteer(); /* Look up a location by name in the icews database country table and return a GeoResolution pointer for each potential match */ virtual std::vector<GeoResolution_ptr> countryLookup(std::wstring locationName); virtual DatabaseConnection_ptr getSingletonGeonamesDb(); virtual Gazetteer::GeoResolution_ptr getCountryResolution(std::wstring country_iso_code); private: Symbol _actorDBName; std::map<std::wstring, Gazetteer::GeoResolution_ptr> _countryResolutionCache; }; #endif
24.488889
91
0.76225
[ "vector" ]
bb4c6a957054c896a053e97d7166e547baab2392
134,015
c
C
daemon/combat_d.c
facadepapergirl/shadowgate
2b811671c5c85952ed93767753d72fc0d12819d8
[ "MIT" ]
null
null
null
daemon/combat_d.c
facadepapergirl/shadowgate
2b811671c5c85952ed93767753d72fc0d12819d8
[ "MIT" ]
null
null
null
daemon/combat_d.c
facadepapergirl/shadowgate
2b811671c5c85952ed93767753d72fc0d12819d8
[ "MIT" ]
null
null
null
/** * @file 8 @brief Various combat subroutines */ //Daemon that handles Combat related stuff //Currently handling checks for shieldmiss/concealing amorpha //damage modifications from body.c - including stoneskin checks, typed damage modifications, etc. //my intention was to make all of this easier to modify on the fly - Saide #include <std.h> #include <dirs.h> #include <daemons.h> #include <damage_types.h> #include <security.h> #define PO previous_object() #define DAMAGE_TRACKER_OBJECT "/realms/saide/damage_tracking_saide" #define BAD_LIMBS ({"torso","neck","waist","lower torso","tail"}) #define TEMP_HIT_BONUS "/realms/ares/temporary_hit.c" // remove this when done #define DEATHS_DOOR_MESSAGE "You are at %^BOLD%^Death's door%^RESET%^. Your body is slipping from you." #define PK_OB "/d/shadowgate/pkill_tracker" mapping DAMAGE_TRACKING; //***** FUNCTIONS DEFINED IN THIS FILE *****// void save_damage_tracker(); void restore_damage_tracker(); varargs int extra_hit_calcs(object attacker, object victim, object weapon, string limb); void track_damage(object attacker, object victim, int damage); varargs int damage_adjustment(object attacker, object victim, int damage); varargs int typed_damage_modification(object attacker, object targ, string limb, int damage, string type); void check_extra_abilities(object attacker, object target, object weapon, int crit_hit); varargs void calculate_damage(object attacker, object targ, object weapon, string target_thing, int critical_hit); int damage_done(object attacker, object weap, int damage, int isranged); varargs int get_damage(object attacker, object weap, object targ); varargs int get_lrdamage(object attacker, object weap, object targ); int get_hand_damage(object attacker, string limb1, int damage, object attacked); void send_messages(object attacker, int magic, object weapon, string what, int x, object victim, int fired, string ammo, int critical_message); void new_struck(int damage, object weapon, object attacker, string limb, object victim, int fired, string ammo, int critical_hit); void do_fumble(object attacker, object weapon); void miss(object attacker, int magic, object target, string type, string target_thing); int calculate_unarmed_damage(object attacker); //****** END OF FUNCTION DEFINITIONS ******// void save_damage_tracker() { seteuid(UID_RESTORE); save_object(DAMAGE_TRACKER_OBJECT); seteuid(geteuid()); } void restore_damage_tracker() { seteuid(UID_RESTORE); restore_object(DAMAGE_TRACKER_OBJECT); seteuid(geteuid()); } //this is called in internal_execute_attack in combat.c //is also called in feat.c in the thaco() function can be ignored there for touch attack type feats //can be called anywhere you want to check to see if a person successfully deflects or avoids an attack //called when the dice roll is not 20 or not a miss - so //only when attacker hits with a dice roll that is not 20 //I am treating 20s as automatic hits bypassing shields and concealing amorpha - Saide //a return value of 1 will be processed as a hit //a return value of 0 is a miss - tell the attacker and the victim - Saide varargs int extra_hit_calcs(object attacker, object victim, object weapon, string limb) { object env; int ShieldMissChance, MissChance, AttackerMissChance; if(!objectp(attacker)) return 1; if(!objectp(victim)) return 1; if(victim->query_paralyzed()) return 1; MissChance = (int)victim->query_missChance(); ShieldMissChance = (int)victim->query_shieldMiss(); AttackerMissChance = (int)attacker->query_property("noMissChance"); //attacker has a property set so that they cannot miss - Saide if(AttackerMissChance) return 1; if(attacker == victim) return 1; if(!MissChance && !ShieldMissChance) return 1; if(attacker->is_spell()) return 1; env = environment(attacker); if(!ShieldMissChance || MissChance > ShieldMissChance) { if(MissChance > roll_dice(1,100)) { tell_object(victim, attacker->QCN+"%^BOLD%^%^WHITE%^ cannot see you and misses!"); tell_object(attacker, "%^BOLD%^%^WHITE%^You cannot see "+victim->QCN+" and miss "+victim->QO+"!"); attacker->delete("featMiss"); attacker->set("featMiss", victim->QCN+" avoided your"); if(objectp(env)) tell_room(env, attacker->QCN+"%^BOLD%^%^WHITE%^ misses "+victim->QCN+"!%^RESET%^", ({victim, attacker})); return 0; } return 1; } else { if(victim->query_property("shapeshifted")) return 1; if(ShieldMissChance > roll_dice(1,100)) { if(living(attacker)) { tell_object(attacker,"%^RESET%^%^BOLD%^Your attack is deflected off of "+victim->QCN+"'s " "shield!%^RESET%^"); attacker->delete("featMiss"); attacker->set("featMiss", victim->QCN+" deflected your"); tell_object(victim,"%^RESET%^%^BOLD%^You deflect "+attacker->QCN+"'s attack with your " "shield!%^RESET%^"); if(objectp(env)) { tell_room(env,"%^RESET%^%^BOLD%^"+victim->QCN+" deflects "+attacker->QCN+"'s attack with " ""+victim->QP+" shield!%^RESET%^",({attacker, victim})); } if(FEATS_D->usable_feat(victim,"counter")) if(random(4)) { victim->counter_attack(victim); } return 0; } else { tell_object(victim,"%^RESET%^%^BOLD%^You deflect the attack with your shield!%^RESET%^"); if(objectp(env)) { tell_room(env,"%^RESET%^%^BOLD%^"+victim->QCN+" deflects the attack with "+victim->QP+" shield!%^RESET%^",({victim})); } if(FEATS_D->usable_feat(victim,"counter")) if(random(4)) { victim->counter_attack(victim); } return 0; } } return 1; } return 1; } //let us track damage - we can keep up with each time this function //is called on a player - and then divide the overall amount / number //of attacks to estimate an average and then go from there - Saide - September 2016 void track_damage(object attacker, object victim, int damage) { string *being_tracked, tname; int myhits = 0, myignore = 0, isuser = 0, mylev = 0, maxdamage = 0; int mindamage = 0, avgdamage = 0; return; if(damage > 0) myhits = 1; else myignore = 1; if(!objectp(attacker)) return; //if(!objectp(victim)) return; if(!mapp(DAMAGE_TRACKING)) restore_damage_tracker(); if(!mapp(DAMAGE_TRACKING)) DAMAGE_TRACKING = ([]); being_tracked = keys(DAMAGE_TRACKING); if(userp(attacker)) isuser = 1; mylev = attacker->query_level(); tname = attacker->query_name() + " @ level "+mylev; if(!sizeof(being_tracked)) { DAMAGE_TRACKING = ([tname : (["damage" : damage, "hits" : myhits, "ignored" : myignore, "user" : isuser, "max damage" : damage, "min damage" : damage, "average damage" : damage]) ]); save_damage_tracker(); return; } else { if(member_array(tname, being_tracked) == -1) { DAMAGE_TRACKING += ([tname : (["damage" : damage, "hits" : myhits, "ignored" : myignore, "user" : isuser, "max damage" : damage, "min damage" : damage, "average damage" : damage]) ]); } else { DAMAGE_TRACKING[tname]["damage"] += damage; DAMAGE_TRACKING[tname]["hits"] += myhits; DAMAGE_TRACKING[tname]["ignored"] += myignore; maxdamage = DAMAGE_TRACKING[tname]["max damage"]; mindamage = DAMAGE_TRACKING[tname]["min damage"]; if(damage < mindamage) DAMAGE_TRACKING[tname]["min damage"] = damage; if(damage > maxdamage) DAMAGE_TRACKING[tname]["max damage"] = damage; if(DAMAGE_TRACKING[tname]["hits"] > 0) avgdamage = DAMAGE_TRACKING[tname]["damage"] / DAMAGE_TRACKING[tname]["hits"]; DAMAGE_TRACKING[tname]["average damage"] = avgdamage; } } save_damage_tracker(); return; } //moved a bunch of code from the do_damage function here - Saide varargs int damage_adjustment(object attacker, object victim, int damage) { int mod, num, layers; object env, myspl; mapping logdata; if(!objectp(attacker)) return damage; if(!objectp(victim)) return damage; if(!intp(damage)) return damage; env = environment(attacker); //adding some damage mitigation after discussion with Octothorpe //should be 2 per 5 levels above 20 only counting melee //type levels only //with current DR feats this would equal 13 points of DR at level 40 //only having it kick in in the event of damage being >= 10 - Saide //tell_object(find_player("saide"), "Damage against "+identify(victim)+ " from "+identify(attacker)+" = "+damage +" in damage_adjustment"); if(interactive(victim) && damage >= 10 && (int)victim->query_level() >= 20) { mod = 0; if((int)victim->query_class_level("fighter") ) mod += (int)victim->query_class_level("fighter"); if((int)victim->query_class_level("thief")) mod += (int)victim->query_class_level("thief"); if((int)victim->query_class_level("antipaladin")) mod += (int)victim->query_class_level("antipaladin"); if((int)victim->query_class_level("paladin")) mod += (int)victim->query_class_level("paladin"); if((int)victim->query_class_level("cavalier")) mod += (int)victim->query_class_level("cavalier"); if((int)victim->query_class_level("ranger")) mod += (int)victim->query_class_level("ranger"); if((int)victim->query_class_level("barbarian")) mod += (int)victim->query_class_level("barbarian"); if((int)victim->query_class_level("monk")) mod += (int)victim->query_class_level("monk"); mod = ((mod - 20)/ 5) * 2; if(mod > 0) damage -= mod; if(damage < 0) { damage = 0; //track_damage(attacker, victim, damage); return damage; } } // adding a damage resistance property which will directly // reduce the damage by the amount. We can probably do away // with this when the types and resistances go into place -Ares // adding in check for new feat 21+ thief/monk to reduce mass-damage blows. N, 4/13. if(FEATS_D->usable_feat(victim,"defensive roll")) { num = (int)victim->query_max_hp() / 4; if(damage > num) { // kicks in for any blow greater than 25% of hp. num = ((int)victim->query_level()/2) + 18; // DC to be roughly 50% success for SC without feats/etc logdata = "/daemon/saving_throw_d.c"->debug_reflex_save(victim,((-1)*num)); // logging success rate if(logdata["save_result"]) { if(userp(victim)) log_file("defensiveroll", "Player "+(string)victim->query_name()+" %^BOLD%^%^RED%^passed" "%^RESET%^. Character level was "+(int)victim->query_level()+", DC was "+num+", varied by "+logdata["final_roll"]+".\n"); damage = damage /2; if(damage < 0) damage = 0; if(living(attacker)) { tell_object(attacker, victim->QCN+"%^RESET%^%^BOLD%^ rolls with your attack, lessening its force!%^RESET%^"); if(objectp(env)) tell_room(env, victim->QCN+"%^RESET%^%^BOLD%^ rolls with "+attacker->QCN+"%^RESET%^%^BOLD%^'s attack, lessing its force!%^RESET%^"); } tell_object(victim, "%^RESET%^%^BOLD%^You roll with the attack, lessening its force!%^RESET%^"); if(damage <= 0) { //track_damage(attacker, victim, damage); return damage; } } else { if(userp(victim)) log_file("defensiveroll", "Player "+(string)victim->query_name()+" %^BOLD%^%^RED%^failed" "%^RESET%^. Character level was "+(int)victim->query_level()+", DC was "+num+", varied by "+logdata["final_roll"]+".\n"); } } } layers = (int)victim->query_stoneSkinned(); if(!layers) { //track_damage(attacker, victim, damage); return damage; } //added && damage >-1 to stop bug with not regenerating HP while //unconscious and stoneskinned. Circe 2/6/04 if(layers && damage > -1) { if(!victim->query_magic_attack() && !victim->query_spell_attack() && !attacker->query_property("magic")&& !attacker->is_spell() && ( objectp(attacker->query_current_weapon()) && !(attacker->query_current_weapon())->query_property("magic") ) ) { if(damage > 0) { /* layers = stoneSkinned; if(layers < 10) { layers = 10; } */ layers = 10; // stoneskin is supposed to knock down 10DR at all times, now that we have greater equivs (eg/ iron body). N, 11/15. if((int)victim->query_stoneSkinned() > 0) { damage = damage - layers; } layers = (int)victim->query_stoneSkinned(); layers -= layers>0?1:-1; // let's remove the stoneskin layer AFTER it checks if we had one to get the DR! victim->set_stoneSkinned(layers); if(damage < 0) { damage = 0; } } } if(!layers && victim->query_property("spelled")) { while(objectp(myspl = MAGIC_D->get_spell_from_array(victim->query_property("spelled"), "stoneskin"))) { victim->remove_property_value("spelled", ({myspl})); myspl->dest_effect(); } } } //track_damage(attacker, victim, damage); return damage; } varargs int typed_damage_modification(object attacker, object targ, string limb, int damage, string type) { object myEB; int resist_perc,resist, reduction, mod, amt; float percentage; if(!objectp(targ)) { return 0; } if(!stringp(limb)) { limb = targ->return_target_limb(); } if(!damage) { return 0; } targ->set_magic_attack(0); targ->spell_attack(0); limb = targ->adjust_targeted_limb(attacker, limb); damage = targ->do_typed_damage_effects(attacker,limb,damage,type); if(!targ->initialized_resistances()) { targ->init_limb_data(); } if(!stringp(type) || !targ->valid_resistance(type)) { if(objectp(attacker)) { log_file("invalid_damage_types",""+ctime(time())+" "+base_name(attacker)+" tried to use an invalid damage type: "+type+"\n"); } return damage; } if(objectp(targ) && FEATS_D->usable_feat(targ,"kinetic conversion")) { switch(type) { case "bludgeoning": case "piercing": case "slashing": case "silver": case "cold iron": case "force": amt = damage / 4; // might need to adjust this if(amt > 3) { amt = 3; } if(amt < 1) { amt = 1; } targ->add_mp(amt); break; default: break; } } if(objectp(targ) && FEATS_D->usable_feat(targ,"way of the learned pupil")){ USER_D->regenerate_ki(targ,1); } resist_perc = (int)targ->query_resistance_percent(type); resist = (int)targ->query_resistance(type); if(resist_perc > 500) { resist_perc = 500; } if(resist_perc < -500) { resist_perc = -500; } switch(resist_perc) { case (-500)..(-1): // resistance less than 0 equals more damage done percentage = to_float( (100 + absolute_value(resist_perc)) / to_float(100) ); break; case 0..100: // resistance between 0 and 100 equals reduced damage percentage = to_float( (100 - resist_perc)/ to_float(100) ); break; case 101..500: // resistance greater than 100 equals healing percentage = to_float( (100 - resist_perc) / to_float(100) ); break; } damage = to_int(damage * percentage); if(damage > 0) { damage = damage - resist; if(damage < 0) { damage = 0; } } if(type == "negative energy") { if(targ->is_undead() || targ->query_property("heart of darkness") || targ->query("subrace")=="dhampir") damage = -abs(damage); else damage = abs(damage); } if(type == "positive energy") { if(targ->is_undead() || targ->query("subrace")=="dhampir") damage = abs(damage); else damage = -abs(damage); } if(damage > 0 && type != "force" && objectp(myEB = targ->query_property("empty body"))) { return 0; } if(damage > 0) if(attacker->is_living()) if(targ->query_property("shadowform")) { int sf_pwr = targ->query_property("shadowform"); if(!"/daemon/saving_throw_d"->will_save(attacker,-sf_pwr)) { damage/=5; } } if(targ->query_verbose_combat()) { if(damage > 0) { tell_object(targ,"You take "+type+" damage."); } if(damage < 0) { tell_object(targ,"You are healed by "+type+" damage."); } } if(objectp(attacker)) { if(attacker->query_property("noMissChance") || attacker->query_property("magic") || ( objectp(attacker->query_current_weapon()) && (attacker->query_current_weapon())->query_property("magic"))) { targ->set_magic_attack(1); } if(PO->is_spell()) { targ->set_spell_attack(1); } } //Healing effects reduction on typed damage if(targ->query_property("fester") && damage < 0) { damage += targ->query_property("fester"); if(damage>0) { damage = 0; return damage; } } if((int)targ->query_property("damage resistance") && member_array(type, PHYSICAL_DAMAGE_TYPES) != -1) { if(damage > 0) { reduction = (int)targ->query_property("damage resistance"); if(attacker->query_property("magic")) { mod = (int)attacker->query_property("magic") * 10; } else if( objectp(attacker->query_current_weapon()) && (attacker->query_current_weapon())->query_property("magic")) { mod = (int)attacker->query_current_weapon()->query_property("magic") * 10; } reduction -= mod; if(reduction < 0) reduction = 0; damage -= reduction; if(damage < 0) { damage = 0; return damage; } } } if((int)targ->query_property("spell damage resistance") && member_array(type, (VALID_DAMAGE_TYPES - PHYSICAL_DAMAGE_TYPES)) != -1) { if(damage > 0) { reduction = (int)targ->query_property("spell damage resistance"); //if we want something to work through this property, it should be set here - Saide mod = 0; reduction -= mod; if(reduction < 0) reduction = 0; damage -= reduction; if(damage < 0) { damage = 0; return damage; } } } return damage; } void check_extra_abilities(object attacker, object target, object weapon, int crit_hit) { int effect_chance; if(!objectp(attacker)) return; if(!objectp(weapon)) return; if( FEATS_D->usable_feat(attacker, "shadow master") && !attacker->query_property("shapeshifted") && objectp(weapon) && crit_hit) { if(!random(3)) { tell_object(attacker,"%^BLUE%^You strike "+target->QCN+" with precision as you channel your command of the shadows, and " +target->QS+ " blinks sightlessly!%^RESET%^"); tell_object(target,"%^BLUE%^As "+attacker->QCN+" strikes you, your vision grows momentarily clouded!%^RESET%^"); target->set_temporary_blinded(1,"Your vision is clouded!"); } } if( FEATS_D->usable_feat(attacker, "spell critical") && crit_hit) { tell_object(attacker,"%^CYAN%^You cry a brief warsong and unleash wave of %^YELLOW%^w%^MAGENTA%^i%^WHITE%^l%^RED%^d %^GREEN%^m%^BLUE%^a%^WHITE%^g%^ORANGE%^i%^RED%^c%^RESET%^%^CYAN%^ at "+target->QCN+"!%^RESET%^"); tell_object(target,"%^CYAN%^"+attacker->QCN+" shouts a brief warsong, and %^YELLOW%^w%^MAGENTA%^i%^WHITE%^l%^RED%^d %^GREEN%^m%^BLUE%^a%^WHITE%^g%^ORANGE%^i%^RED%^c%^RESET%^%^CYAN%^ burns through you!%^RESET%^"); tell_room(environment(attacker),"%^CYAN%^"+attacker->QCN+" shouts a brief warsong and unleashes wave of %^YELLOW%^w%^MAGENTA%^i%^WHITE%^l%^RED%^d %^GREEN%^m%^BLUE%^a%^WHITE%^g%^ORANGE%^i%^RED%^c%^RESET%^%^CYAN%^ at "+target->QCN+"!%^RESET%^",({target,attacker})); target->do_damage(target->return_target_limb(),roll_dice(1,8)); } if(weapon->is_lrweapon() && FEATS_D->usable_feat(attacker, "arcane arrows") && crit_hit) { string element; element=attacker->query_property("arcane arrows"); switch(element) { case "acid": tell_room(environment(target),"%^GREEN%^The projectile explodes with ooze of acid all over "+target->QCN+"%^RESET%^",({target})); tell_object(target,"%^GREEN%^The missile explodes with ooze of acid all over you%^RESET%^"); break; case "cold": tell_room(environment(target),"%^BLUE%^The projectile explodes with sharp shards of ice that pierce "+target->QCN+"%^RESET%^",({target})); tell_object(target,"%^GREEN%^The missile explodes with ooze of acid all over you%^RESET%^"); break; case "sonic": tell_room(environment(target),"%^CYAN%^The projectile explodes sonic scream that shatters "+target->QCN+"%^RESET%^",({target})); tell_object(target,"%^GREEN%^The missile explodes with sonic scream that shatters you%^RESET%^"); break; default: tell_room(environment(target),"%^RED%^The projectile explodes and scorches "+target->QCN+"%^RESET%^",({target})); tell_object(target,"%^GREEN%^The missile explodes and burns you!%^RESET%^"); break; } target->cause_typed_damage(target,target->return_target_limb(),roll_dice(attacker->query_character_level(),8),element); } if(objectp(weapon) && !attacker->query_property("shapeshifted")) { if(objectp(target) && (int)weapon->query("PoisonDoses")) { POISON_D->is_object_poisoned(weapon, target, "hit", 1); } } else if(attacker->query_property("natural poisoner")) { effect_chance = attacker->query_property("poison chance"); if(!intp(effect_chance)) effect_chance = 10; if(effect_chance > roll_dice(1,100)) { POISON_D->ApplyPoison(target, attacker->query_property("natural poison"), attacker, "injury"); } } //monster feat stuff if(attacker->query("combat_feats_enabled") && !attacker->query_property("using instant feat")) { effect_chance = attacker->query_property("feat chance"); if(!intp(effect_chance)) effect_chance = 15; if(effect_chance > roll_dice(1, 100)) { MONSTER_FEAT_D->execute_monster_feat(attacker, attacker->return_player_target(100)); } } //disease stuff if(attacker->query_property("infects disease")) { effect_chance = (int)attacker->query("disease chance"); if(!intp(effect_chance)) effect_chance = 10; if(effect_chance > roll_dice(1, 100)) { "/daemon/disease_d.c"->infect_with_disease(attacker, target, random(2)); } } else if(objectp(weapon) && !attacker->query_property("shapeshifted")) { if(objectp(target) && weapon->query_property("infects disease")) { "/daemon/disease_d.c"->infect_with_disease(weapon, target, 0); } } return; } //all melee damage calculations should be here now //condensing the do_hits() function from /std/living/combat.c //and the damage_done() function int crit_damage(object attacker, object targ, object weapon, int size, int damage) { int mult, crit_dam, perc; string targRace; object *wielded; if(damage <= 0) return 0; if(objectp(weapon) && !attacker->query_property("shapeshifted") && weapon != attacker) { mult = (int)weapon->query_critical_hit_multiplier(); if(FEATS_D->usable_feat(attacker,"skull collector") && attacker->is_wielding("two handed")) { if(objectp(targ)) { perc = 25 + roll_dice(1,25); if( (targ->query_hp_percent() < perc) && (targ->query_hp_percent() > 0) ) { if(!FEATS_D->usable_feat(targ,"death ward") && !targ->query_property("no death")) { if(!targ->fort_save(attacker->query_highest_level())) { tell_object(targ,"%^BOLD%^%^RED%^"+attacker->QCN+" swings "+attacker->QP+" "+weapon->query_short()+" in a brutal swipe, hitting you in the head!\nEverything goes black..."); tell_object(attacker,"%^BOLD%^%^RED%^You swing your "+weapon->query_short()+" in a brutal swipe, hitting "+targ->QCN+" in the head with a certainly fatal strike!"); tell_room(environment(targ),"%^BOLD%^%^RED%^"+attacker->QCN+" swings "+attacker->QP+" "+weapon->query_short()+" in a brutal swipe, hitting "+targ->QCN+" in the head " "with what must cetainly be a fatal strike!",({attacker,targ})); targ->set_hp(-100); } } } } } } else { mult = 2; // currently all unarmed attacks have x2 multiplier if(attacker->is_class("monk")) { mult += (int)"/std/class/monk.c"->critical_multiplier(attacker); if(FEATS_D->usable_feat(attacker,"way of the merciful soul")) { if(objectp(targ)) { if(targ->query_hp_percent() < 26 && targ->query_hp_percent() > 0) { if(!FEATS_D->usable_feat(targ,"death ward") && !targ->query_property("no death")) { if(!targ->fort_save(attacker->query_prestige_level("monk")) && USER_D->can_spend_ki(attacker, 3)) { tell_object(targ,"%^BOLD%^%^BLUE%^"+attacker->QCN+" strikes you swiftly on the forehead and everthing goes black!%^RESET%^"); tell_object(attacker,"%^BOLD%^%^BLUE%^You strike "+targ->QCN+" precisely on the forehead and release pure ki into "+targ->QP+" mind, " "granting "+targ->QO+" the mercy of a painless death."); tell_room(environment(targ),""+attacker->QCN+" strikes "+targ->QCN+" swiftly on the head and "+targ->QS+" drops instantly to the " "ground!",({attacker, targ})); USER_D->spend_ki(attacker, 3); targ->set_hp(-100); } } } } } } } if((int)"/daemon/config_d.c"->check_config("critical damage") == 0) { if(objectp(targ)) { //races that are more/less vulnerable to critical hits - Saide, November 2016 targRace = (string)targ->query_race(); if(CRIT_DAMAGE_MODIFIER[targRace]) { mult = mult * CRIT_DAMAGE_MODIFIER[targRace]; if(mult < 1) mult = 1; } } return (damage * mult); } else if((int)"/daemon/config_d.c"->check_config("critical damage") == 1) { mult -= 1; if(FEATS_D->usable_feat(attacker, "lethal strikes") && !attacker->query_property("shapeshifted")) { wielded = (object *)attacker->query_wielded(); if(sizeof(wielded) >= 2) { if(wielded[0] != wielded[1]) mult += 1; if((int)wielded[0]->query_size() == 1 && (int)wielded[1]->query_size() == 1) mult += 1; } else if(sizeof(wielded) == 1) { mult += 1; if((int)wielded[0]->query_size() == 1) mult += 1; } } else if(FEATS_D->usable_feat(attacker, "exploit weakness") && !attacker->query_property("shapeshifted")) { mult += 2; } crit_dam = 0; while(mult > 0) { mult--; if(objectp(weapon) && !attacker->query_property("shapeshifted") && weapon != attacker) { if(size < 3) { crit_dam += weapon->query_wc(); } else { crit_dam += weapon->query_large_wc(); } continue; } else { //unarmed crit damage if(attacker->is_class("monk")) { crit_dam += (int)"/std/class/monk.c"->critical_damage(attacker); continue; } crit_dam += roll_dice(1, 4); continue; } } if(objectp(targ)) { targRace = (string)targ->query_race(); if(CRIT_DAMAGE_MODIFIER[targRace]) { crit_dam = crit_dam * CRIT_DAMAGE_MODIFIER[targRace]; } } return (damage + crit_dam); } return damage; } int unarmed_enchantment(object who) { int mod = 0; if(!objectp(who)) return mod; if(who->is_class("monk")) mod += (int)"/std/class/monk.c"->effective_enchantment(who); else if(FEATS_D->usable_feat(who, "precise strikes")) { mod += ((int)who->query_base_character_level() / 8); } return mod; } varargs void calculate_damage(object attacker, object targ, object weapon, string target_thing, int critical_hit) { int attacker_size, damage, mod; int res, eff_ench, ench; int i, j, mysize; int speed, enchantment, fired = 0;// added for new stamina formula -Ares object *armor,shape,ammo; string ammoname; if(!objectp(attacker)) { return; } if(!objectp(targ)) { return; } attacker_size = (int)targ->query_size(); if(objectp(weapon) && weapon != attacker && !attacker->query_property("shapeshifted")) { if(attacker_size < 3) { damage = (int)weapon->query_wc(); } else { damage = (int)weapon->query_large_wc(); } if(weapon->is_lrweapon()) { ammoname = weapon->query_ammo(); ammo = present(ammoname,attacker); if(FEATS_D->usable_feat(attacker,"point blank shot") && objectp(ammo) && ammo->use_shots()) { fired = 1; } if(fired) { damage += get_lrdamage(attacker, weapon, targ); if(FEATS_D->usable_feat(attacker,"point blank shot")) { damage += BONUS_D->damage_bonus(attacker->query_stats("dexterity")); } } } else { damage += get_damage(attacker, weapon, targ); mysize = (int)attacker->query_size(); if(mysize == 1) mysize++; //run small creatures as normal size please. mysize -= (int)weapon->query_size(); if(FEATS_D->usable_feat(attacker,"weapon finesse") && (mysize >= 0)) // if has-feat & weapon is smaller than / same size as user - Saide, November 23rd, 2017 { damage += BONUS_D->new_damage_bonus(attacker, attacker->query_stats("dexterity")); } else { damage += BONUS_D->new_damage_bonus(attacker, attacker->query_stats("strength")); } } if(!targ->query_unconscious() && !targ->query_bound()) { enchantment = (int)weapon->query_property("enchantment"); if(enchantment) { damage += enchantment; } } } else if(!weapon || weapon == attacker || attacker->query_property("shapeshifted")) { if(attacker->query_unarmed_damage()) { damage = get_hand_damage(attacker, (string)attacker->return_target_limb(), damage, targ); if(objectp(targ)) if(targ->query_unconscious() || targ->query_bound()) { damage = damage*2; } } else { if(targ->query_unconscious() || targ->query_bound()) { damage = 4; } else damage = random(4); } if(FEATS_D->usable_feat(attacker,"weapon finesse")) damage += BONUS_D->new_damage_bonus(attacker, attacker->query_stats("dexterity")); else damage += BONUS_D->new_damage_bonus(attacker, attacker->query_stats("strength")); damage += COMBAT_D->unarmed_enchantment(attacker); } damage = damage_done(attacker, weapon, damage, fired); if(!objectp(targ)) return; if(!objectp(attacker)) return; if(res = targ->query_property("weapon resistance") > 0) { if(!weapon || weapon == attacker) { eff_ench = (int)attacker->query_property("effective_enchantment"); eff_ench += COMBAT_D->unarmed_enchantment(attacker); if(eff_ench < res) damage = 0; // no need for these to stack, greatest is sufficient to override. } else { ench = (int)weapon->query_property("enchantment"); eff_ench = (int)weapon->query_property("effective_enchantment"); if(( ench + eff_ench ) < res) damage = 0; } } if(objectp(weapon) && !attacker->query_property("shapeshifted")) { weapon->reaction_to_hit(targ,damage); } armor = targ->query_armour(target_thing); j = sizeof(armor); for (i=0;i<j;i++) { if(targ->query_property("shapeshifted")) { continue; } if (!objectp(armor[i])) continue; mod = armor[i]->do_struck(damage,weapon,attacker); if(mod <= 0) damage += mod; if(mod > 0) damage = mod; } if(critical_hit) { damage = crit_damage(attacker, targ, weapon, attacker_size, damage); } new_struck(damage,weapon, attacker, target_thing, targ, fired, ammoname, critical_hit); if (!objectp(weapon) || attacker->query_property("shapeshifted")) { attacker->increment_stamina(1); } else { speed = (int)weapon->query_weapon_speed(); enchantment = (int)weapon->query_property("enchantment"); i = speed - enchantment; if(i<1) { i = 1; } if(i>5) { i = 5; } attacker->increment_stamina(i); } check_extra_abilities(attacker, targ, weapon, critical_hit); if(fired) { // add the flag here for shot on the run, affects only rounds where an attack has hit if(FEATS_D->usable_feat(attacker,"shot on the run") && !attacker->query_property("shotontherun")) attacker->set_property("shotontherun",1); } // added only 1/3 chance to decay weapon on hit; weapons degrade super fast. N, 4/13. if((damage > 0) && (weapon && !attacker->query_property("shapeshifted")) && !random(3)) { weapon->decay(); } return; } int damage_done(object attacker, object weap, int damage, int isranged) { object *wielded; int prof; if(!objectp(attacker)) { return damage; } if(!userp(attacker)) { return damage; } if(!objectp(weap)) { return damage; } if(!weap->query_prof_type()) { return damage; } switch(weap->query_weapon_prof()) { case "simple": if(FEATS_D->usable_feat(attacker,"simple weapon proficiency")) prof = 100; break; case "martial": if(FEATS_D->usable_feat(attacker,"martial weapon proficiency")) prof = 100; break; case "exotic": if(FEATS_D->usable_feat(attacker,"exotic weapon proficiency")) prof = 100; break; default: prof = 30; break; } if(avatarp(attacker)) { prof = 100; } if(pointerp(wielded=(object *)attacker->query_wielded()) && !attacker->query_property("shapeshifted")) { if(isranged) { if(FEATS_D->usable_feat(attacker,"deadeye")) { prof = to_int(prof*1.50); } } else if(sizeof(wielded) == 2) { if(objectp(wielded[0]) && objectp(wielded[1])) { if(wielded[0] == wielded[1] && FEATS_D->usable_feat(attacker,"strength of arm")) { prof = to_int(prof*1.50); } } } else if(sizeof(wielded) == 1) { if(objectp(wielded[0])) { if((int)attacker->query_shieldMiss() && FEATS_D->usable_feat(attacker, "counter")) { prof = to_int(prof * (1.25 + ((int)attacker->query_property("shieldwall") *0.10))); } if(FEATS_D->usable_feat(attacker, "opportunity strikes")) { prof = to_int(prof*1.6); } } } } prof += (random(30) - random(30)); if(prof == 0) { return 0; } if(prof < 0) { damage = absolute_value((damage*prof)/100 + 1); attacker->do_damage("torso",damage); tell_object(attacker,"You hurt yourself with your weapon because of your inexperience."); tell_room(environment(attacker),attacker->QCN+" hurts "+attacker->QO+"self with "+attacker->QP+" weapon.",attacker); return 0; } else { damage = (damage*prof)/100; return damage; } } /*The following two functions were moved from combat.c - in order to attempt to have everything related to damage calculations in combat_d.c - Saide - September 2016 */ varargs int get_damage(object attacker, object weap, object targ) { function f; string hold; int damage; if(!objectp(weap)) return damage; if(!(hold = weap->query_hit()) || WORLD_EVENTS_D->stacking_bonus_active(attacker, -1)) { return damage; } if(!objectp(attacker)) return damage; if(!weap->query_property("fhit")) { message("my_action", hold, attacker); } else { if(!objectp(targ)) targ = (object)attacker->query_current_attacker(); damage += call_other(weap, hold, targ); } return damage; } varargs int get_lrdamage(object attacker, object weap, object targ) { function f; string hold; int damage; if(!objectp(weap)) return damage; if(!(hold = weap->query_lrhit()) || WORLD_EVENTS_D->stacking_bonus_active(attacker, -1)) { return damage; } if(!objectp(attacker)) return damage; if(!weap->query_property("flrhit")) { message("my_action", hold, attacker); } else { if(!objectp(targ)) targ = (object)attacker->query_current_attacker(); damage += call_other(weap, hold, targ); } return damage; } //END //moved here from /std/weaponless_users.c - Saide, September 2016 int get_hand_damage(object attacker, string limb1, int damage, object attacked) { string *attack_limbs = ({}); mapping attack_funcs = ([]); if(!objectp(attacker)) return 0; attack_limbs = attacker->return_attack_limbs(); attack_funcs = attacker->return_attack_funcs(); if(!stringp(limb1) || (limb1 == "") || (limb1 == " ") || !sizeof(attack_limbs) || member_array(limb1,attack_limbs) == -1) { if(!sizeof(attack_limbs)) { return (damage + (int)attacker->query_unarmed_damage()); } limb1 = attack_limbs[random(sizeof(attack_limbs))]; } if(!attack_funcs || attack_funcs == ([]) || WORLD_EVENTS_D->stacking_bonus_active(attacker, -1)) { return (damage + (int)attacker->query_unarmed_damage()); } if(!attack_funcs[limb1]) { return (damage + (int)attacker->query_unarmed_damage()); } if(stringp(attack_funcs[limb1])) { tell_room(environment(attacker), attack_funcs[limb1], attacker); return (damage + (int)attacker->query_unarmed_damage()); } if(functionp(attack_funcs[limb1]) && attacker->query_property("shapeshifted")) { damage += (int)attacker->query_unarmed_damage(); seteuid(UID_SYSTEM); damage += call_other((object)attacker->query_property("shapeshifted"), (*attack_funcs[limb1])(1), attacker, attacked ); seteuid(geteuid()); return damage; } if(functionp(attack_funcs[limb1])) { damage += call_other(attacker, (*attack_funcs[limb1])(1), attacked); return damage; } return (damage + (int)attacker->query_unarmed_damage()); } void send_messages(object attacker, int magic, object weapon, string what, int x, object victim, int fired, string ammo, int critical_message) { string your_name, my_name, me, you, others, used, type, *verb, *adverb,*attack_limbs, *limbs; int i, verbose,num; object shape; if(!objectp(attacker) || !objectp(victim)) { return; } your_name = (string)victim->QCN; my_name = (string)attacker->QCN; verbose = 0; if(interactive(attacker)) { verbose = attacker->query_verbose_combat(); } else if(interactive(victim)) { verbose = victim->query_verbose_combat(); } if(verbose) { if(magic) { type = "magic"; } if(fired) { type = "ranged"; } else if(weapon) { type = (string)weapon->query_type(); } else { type = "melee"; } if(!type) { type= "bludgeon"; } if(objectp(shape = attacker->query_property("shapeshifted"))) { type = shape->get_new_damage_type(); } i = x/2; if(i<0) i=0; if(i>11) i=11; if(magic) { used = "magic"; } else if(fired) { used = ammo; } else if(weapon && !attacker->query_property("shapeshifted") && weapon != attacker) { used = (string)weapon->query_short(); } else { if(attack_limbs = (string*)attacker->query_attack_limbs()) { used = attack_limbs[random(sizeof(attack_limbs))]; } else { limbs = (string*)attacker->query_limbs(); limbs = limbs - BAD_LIMBS; if(!sizeof(limbs)) { used = "body"; } else { if(!used) { used = limbs[random(sizeof(limbs))]; if(!used) { used = "body"; } } } } } if(x < 1) { me = "You hit "+your_name+" ineffectively in the "+what+"."; you = my_name+" hits you ineffectively in the "+what+"."; others = my_name+" hits "+your_name+" ineffectively in the "+what+"."; } else { if(used == "head") { if(x < 5) { me = "You bonk "+your_name+" viciously in the head."; you = my_name+" bonks you viciously in the head."; others = my_name+" bonks "+your_name+" viciously in the head."; } else { me = "You headbutt "+your_name+" furiously."; you = my_name+" headbutts you furiously."; others = my_name+" headbutts "+your_name+" furiously."; } } else { if(type == "blade" || type == "lash" || type == "knife" || type == "slashing" || type == "slash" || type == "thiefslashing" || type == "magicslashing") { verb = ({ "tap", "tickle", "sting", "slash", "cut", "slice", "slice", "shear", "strike", "mutilate", "dismember", "maim"}); adverb = ({ 0, 0, "sharply", 0, 0, 0, "horribly", "to pieces", "letting blood", 0, 0, "utterly"}); } else if(type == "pierce" || type == "thiefpiercing" || type == "piercing" || type == "arrow" || type == "lance" || type == "polearm" || type == "magepierce"|| type == "magepiercing" || type == "ranged") { verb = ({ "tap", "poke", "sting", "pierce", "puncture", "penetrate", "perforate", "shear", "impale", "mutilate", "dismember", "maim"}); adverb = ({ 0, 0, "sharply", 0, 0, 0, "sharply", "to pieces", "letting blood", 0, 0, "utterly"}); } else { verb = ({ "tap", "hit", "whack", "bash", "strike","strike", "send", "knock", "slam", "blast", "destroy", "maim"}); adverb = ({ "innocently", "lightly", "strongly", 0, "badly", 0, "a bone crushing blow", 0,"mercilessly", "powerfully", "utterly", "utterly"}); } me = sprintf("You %s %s%sin the %s with your %s.",verb[i], your_name, (adverb[i] ? " "+adverb[i]+" " : " "), what, used); you = sprintf("%s %ss you%sin the %s with %s %s.",my_name, verb[i],(adverb[i] ? " "+adverb[i]+" " : " "), what,(string) attacker->QP, used); others = sprintf("%s %ss %s%sin the %s with %s %s.", my_name, verb[i], your_name, (adverb[i] ? " "+adverb[i]+" " : " "), what,(string)attacker->QP, used); } if(critical_message) { switch(type) { case "firearm": me = "Bullet stuff"; you = "Bullet stuff"; others = "Bullet stuff"; break; case "blade": case "lash": case "knife": case "slashing": case "slash": case "thiefslashing": case "magicslashing": me = "%^RED%^You land a %^BOLD%^vicious %^RESET%^%^RED%^s%^BOLD%^l%^RESET%^%^RED%^a%^BOLD%^s%^RESET%^%^RED%^h%^BOLD%^i%^RESET%^%^RED%^n%^BOLD%^g %^RESET%^%^RED%^blow with %^BOLD%^%^BLACK%^"+used+" %^RESET%^%^RED%^and %^BOLD%^tear %^RESET%^%^RED%^your weapon free of %^BOLD%^%^BLACK%^"+your_name+"%^RESET%^%^RED%^!%^RESET%^"; you = "%^BOLD%^%^RED%^"+my_name+" %^RESET%^%^RED%^strikes you with a %^BOLD%^vicious %^RESET%^%^RED%^s%^BOLD%^l%^RESET%^%^RED%^a%^BOLD%^s%^RESET%^%^RED%^h%^BOLD%^i%^RESET%^%^RED%^n%^BOLD%^g %^RESET%^%^RED%^blow with %^BOLD%^%^BLACK%^"+used+" %^RESET%^%^RED%^and tears %^BOLD%^%^BLACK%^"+attacker->QP+" %^RESET%^%^RED%^weapon free from you!%^WHITE%^"; others = "%^BOLD%^%^RED%^"+my_name+" %^RESET%^%^RED%^strikes %^BOLD%^"+your_name+" %^RESET%^%^RED%^with a %^BOLD%^vicious %^RESET%^%^RED%^s%^BOLD%^l%^RESET%^%^RED%^a%^BOLD%^s%^RESET%^%^RED%^h%^BOLD%^i%^RESET%^%^RED%^n%^BOLD%^g %^RESET%^%^RED%^blow with %^BOLD%^%^BLACK%^"+attacker->QP+" "+used+" and %^RESET%^%^RED%^tears %^BOLD%^%^BLACK%^"+attacker->QP+" %^RESET%^%^RED%^blade free from %^BOLD%^%^BLACK%^"+your_name+"%^RESET%^%^RED%^!%^WHITE%^"; break; case "pierce": case "thiefpiercing": case "piercing": case "arrow": case "lance": case "polearm": case "magepierce": case "magepiercing": case "ranged": me = "%^CYAN%^You p%^BOLD%^%^i%^RESET%^%^CYAN%^erce through %^BOLD%^"+your_name+"'s%^RESET%^%^CYAN%^ defenses and drive your "+used+" into a %^BOLD%^vital%^RESET%^%^CYAN%^ spot!%^RESET%^"; you = "%^CYAN%^%^BOLD%^"+my_name+"%^RESET%^%^CYAN%^ pierces through your defences and drives %^BOLD%^"+attacker->QP+" "+used+"%^RESET%^ into a v%^BOLD%^i%^RESET%^%^CYAN%^tal spot!%^RESET%^"; others = "%^CYAN%^%^BOLD%^"+my_name+" p%^BOLD%^i%^RESET%^%^CYAN%^erces through %^BOLD%^"+your_name+"'s%^RESET%^ defenses and drives %^BOLD%^"+attacker->QP+" "+used+"%^RESET%^%^CYAN%^ into a v%^BOLD%^i%^RESET%^%^CYAN%^tal spot!%^RESET%^"; break; default: me = "%^GREEN%^You unleash a %^BOLD%^crushing%^RESET%^%^GREEN%^ blow on %^BOLD%^"+your_name+"%^RESET%^%^GREEN%^ with your %^BOLD%^"+used+"%^RESET%^%^GREEN%^ with %^BOLD%^devastating%^RESET%^%^GREEN%^ force."; you = "%^GREEN%^%^BOLD%^"+my_name+"%^RESET%^%^GREEN%^ staggers you with a %^BOLD%^crushing%^RESET%^%^GREEN%^ blow from "+attacker->QP+" %^BOLD%^"+used+"%^RESET%^%^GREEN%^ with %^BOLD%^devastating%^RESET%^%^GREEN%^ force."; others = "%^GREEN%^%^BOLD%^"+my_name+"%^RESET%^%^GREEN%^ staggers %^BOLD%^"+your_name+"%^RESET%^%^GREEN%^ with a %^BOLD%^crushing%^RESET%^%^GREEN%^ blow from "+attacker->QP+" %^BOLD%^"+used+"%^RESET%^%^GREEN%^ with %^BOLD%^devastating%^RESET%^%^GREEN%^ force."; break; } if(!objectp(weapon)) { me = "%^BOLD%^%^BLACK%^You deliver "+your_name+" a %^BOLD%^%^WHITE%^punishing %^BOLD%^%^BLACK%^blow with your "+used+"!%^RESET%^"; you = "%^BOLD%^%^RED%^"+my_name+" %^BOLD%^%^BLACK%^hits you with a %^BOLD%^%^WHITE%^punishing %^BOLD%^%^BLACK%^blow from "+attacker->QP+" "+used+"!%^RESET%^"; others = "%^BOLD%^%^RED%^"+my_name+" %^BOLD%^%^BLACK%^delivers a %^BOLD%^%^WHITE%^punishing %^BOLD%^%^BLACK%^blow to " "%^BOLD%^%^RED%^"+your_name+" with "+attacker->QP+" "+used+"!%^RESET%^"; } } } } else { if(x < 1) { me = "You hit "+your_name+" ineffectively."; you = my_name+" hits you ineffectively."; others = my_name+" hits "+your_name+" ineffectively."; } else { me = "You hit "+your_name+"."; you = my_name+" hits you."; others = my_name+" hits "+your_name+"."; } } if(critical_message) { me = "%^BOLD%^%^RED%^(Critical) %^RESET%^"+me; you = "%^BOLD%^%^RED%^(Critical) %^RESET%^"+you; others = "%^BOLD%^%^RED%^(Critical) %^RESET%^"+others; attacker->reset_critical(); } if(objectp(attacker)) { tell_object(attacker,me); if(objectp(environment(attacker))) tell_room(environment(attacker),others,({attacker,victim})); } if(objectp(victim)) tell_object(victim,you); } void new_struck(int damage, object weapon, object attacker, string limb, object victim, int fired, string ammo, int critical_hit) { string damage_type,tmp,type; object shape; int damage_num,dam; // putting this here so it already passes the various checks to make sure the weapon has hit -Ares if(!objectp(attacker)) return; if(!objectp(victim)) return; victim->set_property("beingDamagedBy", attacker); if(objectp(weapon) && weapon->query_property("oiled")) { tmp = (string)weapon->query_property("oiled"); if(strsrch(tmp,"damage bonus") != -1) { if(sscanf(tmp,"damage bonus %s %d",type,dam) == 2) { if(objectp(victim)) { victim->cause_typed_damage(victim,limb,dam,type); } } } } //temp_oiled can be used by spells and abilities without overriding permanent oils if(objectp(weapon) && weapon->query_property("temp_oiled")) { tmp = (string)weapon->query_property("temp_oiled"); if(strsrch(tmp,"damage bonus") != -1) { if(sscanf(tmp,"damage bonus %s %d",type,dam) == 2) { if(objectp(victim)) { victim->cause_typed_damage(victim,limb,dam,type); } } } } if(objectp(weapon) && !attacker->query_property("shapeshifted") && attacker != weapon) { damage_type = (string)weapon->query_damage_type(); } else if(objectp(attacker)) { damage_type = (string)attacker->query_base_damage_type(); } if(!damage_type || damage_type == "untyped") { damage_type = "bludgeoning"; } if(objectp(shape = attacker->query_property("shapeshifted"))) { damage_type = (string)shape->get_new_damage_type(); } if(damage > 0) { damage_num = (int)victim->cause_typed_damage(victim,limb,damage,damage_type); } else { damage_num = 0; } if(objectp(attacker)) { send_messages(attacker,0,weapon,limb,damage_num,victim,fired,ammo,critical_hit); } if(objectp(victim)) { victim->remove_property("beingDamagedBy"); } } void do_fumble(object attacker, object weapon) { int num; object *attackers, victim; if(!objectp(attacker)) return; if(!weapon || !objectp(weapon)) { tell_object(attacker, "You swing wildly at your target!"); return; } num = random(20)+1; attackers = attacker->query_attackers(); if(!sizeof(attackers)) { tell_object(attacker, "You swing wildly at your target!"); return; } victim = attackers[0]; switch (num) { case 1..9: break; case 10: if (!weapon) miss(attacker, (int)attacker->query_casting(), victim, 0, (string)victim->return_target_limb()); else miss(attacker, 0, victim, (string)weapon->query_type(), (string)victim->return_target_limb()); break; case 11..13: break; case 14: if (objectp(victim)) { calculate_damage(attacker, victim, weapon, (string)victim->return_target_limb()); } break; case 17: break; case 18: if(objectp(weapon)) { tell_object(attacker,"%^GREEN%^You fumble your weapon badly, dropping it!"); tell_room(environment(attacker),"%^GREEN%^You see "+attacker->QCN+" fumble "+attacker->QP+" weapon.",attacker); attacker->force_me("drop "+((string *)weapon->query_id())[0]); } else { tell_object(attacker,"%^GREEN%^You stumble as you wing at your opponent"); tell_room(environment(attacker),"%^GREEN%^You see "+attacker->QCN+" stumble.",attacker); attacker->set_paralyzed(10,"You are recovering from having stumbled."); } break; case 19: break; default: if(objectp(weapon)) { calculate_damage(attacker, attacker, weapon, (string)attacker->return_target_limb()); } break; } return; } void miss(object attacker, int magic, object target, string type, string target_thing) { int verbose; if(!objectp(attacker)) { return; } if(!objectp(environment(attacker))) { return; } if(magic) { return; } if(interactive(attacker)) { verbose = attacker->query_verbose_combat(); } if(objectp(target)) { if(interactive(target)) { verbose = target->query_verbose_combat(); } if(verbose) { tell_object(attacker,"%^RESET%^%^YELLOW%^You miss your attack on "+target->QCN+"%^RESET%^"); tell_room(environment(attacker),""+attacker->QCN+" misses "+attacker->QP+" attack on "+target->QCN+"!",({attacker,target})); tell_object(target,""+attacker->QCN+" missed you!"); } else { tell_object(attacker, "%^YELLOW%^You miss.%^RESET%^"); tell_object(target,""+attacker->QCN+" missed you."); tell_room(environment(attacker),""+attacker->QCN+" misses "+target->QCN+"",({target,attacker})); } return; } tell_object(attacker, "%^YELLOW%^You miss.%^RESET%^"); tell_room(environment(attacker),""+attacker->QCN+" misses "+attacker->QP+" target.",attacker); return; } int is_ok_armour(object who, string myclass) { int i,j; object *armours; int isnotok=0; if(!objectp(who)) return 0; armours = (object *)who->all_armour(); j = sizeof(armours); switch (myclass) { case "thief": for (i=0;i<j;i++) { if(!objectp(armours[i])) { continue; } if (member_array((string)armours[i]->query_type(),({"sheath","leather","bracer","ring","clothing","thiefshield","jewelry"})) == -1 && !armours[i]->query_property("magicarmor")) { isnotok = 1; break; } } break; /*Added barb type for barbarian unarmored defense feat - Octothorpe 1/14/16*/ case "barb": case "barbarian": for (i=0;i<j;i++) { if(!objectp(armours[i])) { continue; } if (member_array((string)armours[i]->query_type(),({"sheath","bracer","ring","clothing","thiefshield","shield","jewelry"})) == -1 && !armours[i]->query_property("magicarmor")) { isnotok = 1; break; } } break; case "mage": for (i=0;i<j;i++) { if(!objectp(armours[i])) { continue; } if (member_array((string)armours[i]->query_type(),({"sheath","ring","bracer","clothing","jewelry"})) == -1 && !armours[i]->query_property("magicarmor")) { isnotok = 1; break; } } break; case "bard": for (i=0;i<j;i++) { if(!objectp(armours[i])) { continue; } if (member_array((string)armours[i]->query_type(),({"sheath", "chain", "bracer", "leather", "ring", "clothing", "thiefshield", "jewelry"})) == -1 && !armours[i]->query_property("magicarmor")) { isnotok = 1; break; } } break; } if (isnotok) return 0; return 1; } int is_ok_weapon(object who, string myclass) { object *weapons; string type; int flag; int i; if(!objectp(who)) return 0; if (myclass == "fighter" || myclass == "paladin" || myclass == "antipaladin" || myclass == "cavalier" || myclass == "ranger" || myclass == "bard") { return 1; } weapons = (object *)who->query_wielded(); for (i=0;i<sizeof(weapons);i++) { type= weapons[i]->query_type(); if (myclass=="thief") { if (member_array(type, ({"magebludgeon","magicslashing","magepiercing","thiefpiercing","lash","thiefslashing"})) == -1) { return 0; } } else if (myclass == "cleric") { if (member_array(type, ({"magebludgeon","magicslashing","lash","bludgeon"})) == -1) { return 0; } } else if (myclass == "mage") { if (member_array(type, ({"magebludgeon","magicslashing","magepiercing"})) == -1) { return 0; } } else if (myclass=="psion") { if (member_array(type, ({"magebludgeon","magicslashing","magepiercing"})) == -1) { return 0; } } } return 1; } int calculate_unarmed_damage(object attacker) { int amt; if(!objectp(attacker)) return 0; if(attacker->is_class("monk") && file_exists("/std/class/monk.c")) { return (int)"/std/class/monk.c"->unarmed_damage(attacker); } else if(FEATS_D->usable_feat(attacker, "unarmed combat")) { switch((int)attacker->query_highest_level()) { case 0..20: return roll_dice(1,6); break; case 21..30: return roll_dice(1,8); break; case 31..40: return roll_dice(1,10); break; case 41..50: return roll_dice(1,12); break; } } return roll_dice(1,4); } //Following functions were moved into here from /std/living/combat.c in January 2017 - Saide void init_combat_vars(object who) { mapping combat_vars; int flag; if(!objectp(who)) return; combat_vars = who->query_combat_vars(); if(!combat_vars || (combat_vars == ([])) || !combat_vars["RNEW"]) { combat_vars = (["gagged" : 0, "bound" : 0, "tripped" : 0, "unconscious" : 0, "asleep" : 0, "blindfolded" : 0, "any attack" : 0, "paralyzed" : 0, "toAttack" : 0, "wimpy" : 0, "any attack" : 0, "react" : 0, "funcCast" : 0, "castFunc" : 0, "swarm" : 0, "RNEW" : 1]); flag = 1; } if(flag) who->set_combat_vars(combat_vars); return; } void init_combat_messages(object who) { mapping combat_messages; int flag; if(!objectp(who)) return; combat_messages = who->query_combat_messages(); if(!combat_messages || (combat_messages == ([])) || !combat_messages["NEW"]) { combat_messages = (["gagged" : 0, "bound" : 0, "tripped" : 0, "unconscious" : 0, "asleep" : 0, "paralyzed" : 0, "blinded" : 0, "blindfolded" : 0, "NEW" : 1]); flag = 1; } if(flag) who->set_combat_messages(combat_messages); return; } void init_combat_counters(object who) { mapping combat_counters; int flag; if(!objectp(who)) return; combat_counters = who->query_combat_counters(); if(!combat_counters || (combat_counters == ([])) || !combat_counters["NEW"]) { combat_counters = (["gagged" : 0, "bound" : 0, "tripped" : 0, "unconscious" : 0, "asleep" : 0, "blindfolded" : 0, "blinded" : 0, "healing" : 0, "block_attack" : 0, "NEW" : 1]); flag = 1; } if (!intp(combat_counters["gagged"])) { combat_counters["gagged"] = 0; flag = 1; } if (!intp(combat_counters["bound"])) { combat_counters["bound"] = 0; flag = 1; } if (!intp(combat_counters["tripped"])) { combat_counters["tripped"] = 0; flag = 1; } if (!intp(combat_counters["asleep"])) { combat_counters["asleep"] = 0; flag = 1; } if (!intp(combat_counters["blindfolded"])) { combat_counters["blindfolded"] = 0; flag = 1; } if (!intp(combat_counters["blinded"])) { combat_counters["blinded"] = 0; flag = 1; } if (!intp(combat_counters["unconscious"])) { combat_counters["unconscious"] = 0; flag = 1; } if (!intp(combat_counters["healing"])) { combat_counters["healing"] = 0; flag = 1; } if (!intp(combat_counters["block_attack"])) { combat_counters["block_attack"] = 0; flag = 1; } if (!intp(combat_counters["tripped counter"])) { combat_counters["tripped counter"] = 0; flag = 1; } if (!intp(combat_counters["paralyzed"])) { combat_counters["paralyzed"] = 0; flag = 1;} if(flag) who->set_combat_counters(combat_counters); } void init_combat_static_vars(object who) { mapping combat_static_vars; int flag; if(!objectp(who)) return; combat_static_vars = who->query_combat_static_vars(); if(!combat_static_vars || (combat_static_vars == ([]))) { combat_static_vars = (["gagged" : 0, "bound" : 0, "tripped" : 0, "unconscious" : 0, "asleep" : 0, "blindfolded" : 0, "blinded" : 0, "critical hit" : 0, "attack count" : 0, "attack loop" : 0, "attacking" : 0, "hunting" : 0, "dead" : 0, "funcing" : 0, "attack" : 0, "toattack" : 0, "lastHand" : 0, "critical message" : 0, "casting" : 0]); flag = 1; } if(flag) who->set_combat_static_vars(combat_static_vars); return; } void init_combat_arrays(object who) { mapping combat_arrays; int flag; if(!objectp(who)) return; combat_arrays = who->query_combat_arrays(); if(!mapp(combat_arrays) || combat_arrays == ([])) { combat_arrays = (["attackers" : ({}), "hunters" : ({}), "atnames" : ({}), ]); flag = 1; } if(flag) who->set_combat_arrays(combat_arrays); return; } int ok_combat_vars(object who) { if(!objectp(who)) return 0; init_combat_vars(who); init_combat_messages(who); init_combat_counters(who); init_combat_static_vars(who); init_combat_arrays(who); return 1; } void send_paralyzed_message(string type, object who) { if(!objectp(who)) return; if (who->query_deaths_door()) { message(type,DEATHS_DOOR_MESSAGE,who); return; } if (who->query_asleep()) { message(type,who->query_asleep_message(), who); return; } if (who->query_unconscious()) { message(type,who->query_unconscious_message(),who); return; } if (who->query_paralyzed()) { message(type,who->query_combat_mapps("messages", "paralyzed"),who); return; } if (who->query_bound()) { message(type,who->query_bound_message(),who); return; } if (who->query_tripped()) { message(type,who->query_tripped_message(),who); return; } } void iterate_combat(object who) { mapping combat_static_vars, combat_counters, combat_vars, combat_messages; object EWHO; int vars, counters, static_vars; if(!objectp(who)) return; EWHO = environment(who); //if (!who->ok_combat_vars()) who->initialize_combat_vars(); // there's a recursion error, not sure if it's caused here or not who->ok_combat_vars(); combat_static_vars = who->query_combat_static_vars(); combat_vars = who->query_combat_vars(); combat_messages = who->query_combat_messages(); combat_counters = who->query_combat_counters(); if (combat_static_vars["blinded"]) { if (combat_counters["blinded"] > 7) { combat_static_vars["blinded"]--; static_vars = 1; combat_counters["blinded"] = 0; if (!who->query_blind()) { message("combat","%^BOLD%^%^BLUE%^You can see again",who); } } combat_counters["blinded"]++; counters = 1; } if (combat_vars["blindfolded"]) { if (combat_counters["blindfolded"] > (25 - (int)who->query_stats("dexterity"))) { vars = 1; combat_vars["blindfolded"]--; combat_counters["blindfolded"] = 0; if (!who->query_blind()) { message("combat","%^BOLD%^%^BLUE%^You can see again",who); } } combat_counters["blindfolded"]++; counters = 1; } if (combat_vars["gagged"]) { if (combat_counters["gagged"] > (25 - (int)who->query_stats("dexterity"))) { vars = 1; combat_vars["gagged"]--; combat_counters["gagged"] = 0; if (!combat_vars["gagged"]) { message("combat","%^BOLD%^%^BLUE%^You have struggled your gag off..",who); if(!who->query_invis() && objectp(environment(who))) { tell_room(environment(who), "%^GREEN%^"+who->QCN+" spits out "+who->QP+" gag.%^RESET%^", who); } } } combat_counters["gagged"]++; counters = 1; } if (combat_vars["bound"]) { if (combat_counters["bound"] > (25 - (int)who->query_stats("strength"))) { vars = 1; combat_vars["bound"]--; combat_counters["bound"] = 0; if (!combat_vars["bound"]) { message("combat","%^BOLD%^%^BLUE%^You have broken your bonds.",who); if(!who->query_invis() && !random(3) && objectp(environment(who))) { tell_room(environment(who), "%^GREEN%^"+who->QCN+" breaks free of "+who->QP+" bonds.%^RESET%^", who); } } } combat_counters["bound"]++; counters = 1; } if (combat_vars["paralyzed"]) { if(combat_counters["paralyzed"] > (1+random(2)))//-(((int)who->query_stats("dexterity") - 10) / 2)) ) { combat_vars["paralyzed"]--; combat_counters["paralyzed"] = 0; if(!combat_vars["paralyzed"]) { if(!who->query_tripped() && !who->query_bound() && !who->query_unconscious()) { message("combat", "%^BOLD%^%^WHITE%^You can move again!", who); if(!who->query_invis() && objectp(environment(who))) { tell_room(environment(who), "%^BOLD%^%^WHITE%^You see "+who->QCN+" moving again.%^RESET%^", who); } } } vars = 1; } combat_counters["paralyzed"]++; counters = 1; } if (combat_vars["tripped"]) { if(combat_counters["tripped counter"]) { combat_counters["tripped counter"]--; if(combat_counters["tripped counter"] < 1 ) { combat_counters["tripped counter"] = 0; combat_vars["tripped"] = 1; combat_counters["tripped"] = 100; } } if (combat_counters["tripped"] > (7+random(5)-(((int)who->query_stats("dexterity") - 10) / 2) ) ) { combat_vars["tripped"]--; vars = 1; combat_counters["tripped"] = 0; if (!combat_vars["tripped"]) { if(!who->query_paralyzed() && !who->query_bound() && !who->query_unconscious()) { message("combat","%^BOLD%^%^BLUE%^You have managed to stand again.",who); if(!who->query_invis() && objectp(environment(who))) { tell_room(environment(who), "%^BOLD%^%^GREEN%^You see "+who->QCN+" standing again.%^RESET%^", who); } } } } combat_counters["tripped"]++; counters = 1; } if (combat_vars["unconscious"]) { if (sizeof(who->query_attackers()) > 0) { combat_vars["unconscious"]=0; combat_counters["unconscious"] = 0; message("combat","%^BOLD%^%^BLUE%^You have regained consciousness.",who); if(!who->query_invis() && objectp(environment(who))) { tell_room(environment(who), "%^GREEN%^You notice "+who->QCN+" waking up.%^RESET%^", who); } } if (combat_counters["unconscious"] > (25 - (int)who->query_stats("constitution")) ) { combat_vars["unconscious"]--;; vars = 1; combat_counters["unconscious"] = 0; if (!combat_vars["unconscious"]) { message("combat","%^BOLD%^%^BLUE%^You have regained consciousness.",who); if(!who->query_invis() && objectp(EWHO)) { tell_room(EWHO, "%^GREEN%^You notice "+who->QCN+" waking up.%^RESET%^", who); } } } combat_counters["unconscious"]++; counters = 1; } if (combat_vars["asleep"]) { combat_vars["asleep"]--; vars = 1; combat_counters["asleep"] = 0; if (!combat_vars["asleep"]) { if(!who->query_invis() && objectp(EWHO)) { tell_room(EWHO, "%^GREEN%^You notice "+who->QCN+" waking up.%^RESET%^", who); } message("combat","%^BOLD%^%^BLUE%^You have awakened.",who); } combat_counters["asleep"]++; counters = 1; } if (who->query_deaths_door() ) { if (combat_counters["healing"] > (25 - (int)who->query_stats("constitution")) ) { who->heal(random(2)+1); combat_counters["healing"]=0; if (!who->query_deaths_door()) { message("combat","%^BOLD%^%^BLUE%^You have healed sufficiently to regain consciousness.",who); if(!who->query_invis() && objectp(EWHO)) { tell_room(EWHO, "%^GREEN%^You notice "+who->QCN+" waking up.%^RESET%^", who); } } } combat_counters["healing"]++; counters = 1; } if(vars) who->set_combat_vars(combat_vars); if(counters) who->set_combat_counters(combat_counters); if(static_vars) who->set_combat_static_vars(combat_static_vars); return; } varargs void set_tripped(object who, int severity, string message, int special) { int chance; if(!objectp(who)) return; if(who->query_property("no tripped")) { tell_object(who,"You cannot be tripped."); return; } if(intp(chance = who->query_property("untrippable"))) { if(chance > roll_dice(1, 100)) { tell_object(who, "You avoid the attempt to trip you!"); if(objectp(environment(who))) { tell_room(environment(who), who->QCN+" avoids the attempt to trip "+who->QO+"!", who); } return; } } who->adjust_combat_mapps("vars", "tripped", severity); who->adjust_combat_mapps("messages", "tripped", message); if(special) { who->adjust_combat_mapps("counters", "tripped counter", special); } // Added to give better control over rush, could // be used for other things. -Ares 12/26/06 return; } /** * Sets target asleep * * @param who target * @param xxx time in rounds * @param message Message displayed to sleeper */ void set_asleep(object who, int xxx, string message) { if(!objectp(who)) return; who->adjust_combat_mapps("vars", "asleep", (xxx>120?120:xxx)); who->adjust_combat_mapps("messages", "asleep", message); } void set_unconscious(object who, int xxx, string message) { if(!objectp(who)) return; who->adjust_combat_mapps("vars", "unconscious", xxx); who->adjust_combat_mapps("messages", "unconscious", message); } void set_gagged(object who, int x, string message) { if(!objectp(who)) return; who->adjust_combat_mapps("vars", "gagged", x); who->adjust_combat_mapps("messages", "gagged", message); } void set_bound(object who, int difficulty, string message) { if(!objectp(who)) return; who->adjust_combat_mapps("vars", "bound", difficulty); who->adjust_combat_mapps("messages", "bound", message); } void set_temporary_blinded(object who, int difficulty, string message) { if(!objectp(who)) return; if(who->query_property("no blind")) { tell_object(who, "You are immune to blindness!"); if(objectp(environment(who))) { tell_room(environment(who), who->QCN+" seems immune to the "+ "blindness attempt!", who); } return; } who->adjust_combat_mapps("static vars", "blinded", difficulty); if(stringp(message)) who->adjust_combat_mapps("messages", "blinded", message); } void set_blindfolded(object who, int difficulty, string message) { if(!objectp(who)) return; who->adjust_combat_mapps("vars", "blindfolded", difficulty); if(stringp(message)) who->adjust_combat_mapps("messages", "blindfolded", message); } /** * Assigns paralyzed state, where 'x' is divisor of 8 rounds. * E.g. x = 16 will set paralyzed status for 2 rounds. */ void set_paralyzed(object who, int x, string paralyze_msg) { if(!objectp(who) || !intp(x)) return; if(archp(who)) { message("my_action", "Your Archhood just saved you from being paralyzed.", who); return; } if(who->query_property("no paralyze")) { message("my_action","You are uneffected by the paralysis.",who); if(objectp(environment(who)) && !who->query_invis()) { tell_room(environment(who), who->QCN+" %^BOLD%^%^GREEN%^is totally uneffected by "+ "the paralysis attempt!%^RESET%^"); } return; } x /= 8; x = x<1?1:x; x = x>72?72:x; who->adjust_combat_mapps("vars", "paralyzed", x); who->adjust_combat_mapps("messages", "paralyzed", paralyze_msg); return; } /** * Removes paralyzed state */ void remove_paralyzed(object who) { if(!objectp(who)) { return; } if(!who->query_paralyzed()) { return; } who->adjust_combat_mapps("vars", "paralyzed", 0); who->adjust_combat_mapps("messages", "paralyzed", 0); if(who->query_tripped() || who->query_bound() || who->query_unconscious()) { return; } tell_object(who,"You can move again."); if(!who->query_invis() && objectp(environment(who))) { tell_room(environment(who), "%^BOLD%^%^GREEN%^You see "+who->QCN+" is moving again.%^RESET%^", who); } return; } object *doProtection(object player) { int i,j; object *pros, *tmp=({}); if (!objectp(player)) { return ({ player }); } pros = player->query_protectors(); j = sizeof(pros); if (!j) { return({player}); } for (i=0;i<j;i++) { if(!objectp(pros[i])) continue; if(!present(pros[i], player) && (!pros[i]->query_following() || (object)pros[i]->query_following() != player)) { player->remove_protector(pros[i]); continue; } if(pros[i] == player) { player->remove_protector(pros[i]); continue; } if(member_array(pros[i], player->query_attackers()) == -1) { tmp+=({pros[i]}); } if((int)pros[i]->query_hp_percent() < 30) { player->remove_protector(pros[i]); tell_object(pros[i], "You are too weak to continue protecting "+player->QCN+"."); pros[i]->set("protecting",0); continue; } //if(random(query_highest_level()*2) > random((int)pros[i]->query_highest_level() + (int)player->query_lowest_level())) if(!random(7) && pros[i]->query("protecting")) { tell_object(pros[i], "You are unable to defend "+player->QCN+" this attack."); pros[i]->set("protecting",0); continue; } //tell_object(pros[i], "You stand in defense of "+player->QCN+"."); //tell_object(player,pros[i]->QCN+" stands in defense of you."); pros[i]->set("protecting",1); tmp += ({pros[i]}); continue; } //if (!sizeof(tmp)) tmp += ({player}); tmp += ({player}); tmp = distinct_array(tmp); return tmp; } object *query_active_protectors(object obj) { object *protectors = ({}),*good_protectors=({}); int i; if(!objectp(obj)) { return ({}); } protectors = (object *)obj->query_protectors(); if(!pointerp(protectors)) { return ({}); } if(!sizeof(protectors)) { return ({}); } for(i=0;i<sizeof(protectors);i++) { if(!objectp(protectors[i])) { continue; } if(!protectors[i]->query("protecting")) { continue; } if(!present(protectors[i],environment(obj))) { continue; } good_protectors += ({ protectors[i] }); continue; } if(!sizeof(good_protectors)) { return ({}); } return good_protectors; } void send_dodge(object who, object att) { int i,j; string *verb,*adverb,v,a; if(!objectp(att) || !objectp(who)) return; verb = ({"flip","back flip","jump","dodge","roll","somersault","dance","spin","scramble"}); adverb = ({"easily","quickly","barely","poorly","with agility","deftly"}); v = verb[random(sizeof(verb))]; a = adverb[random(sizeof(adverb))]; tell_object(who,att->QCN+" "+v+"s "+a+" from your blow."); tell_object(att,"You "+v+" "+a+" from "+who->QCN+"'s blow."); tell_room(environment(who),att->QCN+" "+v+"s "+a+" from "+who->QCN+"'s blow.",({who,att})); return; } //is this even used? Saide - January 2017 void thaco_messages(object who, int thaco) { if(!objectp(who)) return; switch (thaco) { case 8..10: tell_object(who, "%^YELLOW%^Your pitiful attempt at wielding two weapons is just silly.%^RESET%^"); break; case 5..7: tell_object(who, "%^ORANGE%^You look really silly trying to wield two weapons %^RESET%^"); break; case 4: tell_object(who, "%^RED%^You awkwardly attack with two weapons %^RESET%^"); break; case 3: tell_object(who, "%^YELLOW%^You have trouble attacking with two weapons.%^RESET%^"); break; case 2: tell_object(who, "%^BLUE%^You find difficulty in wielding two weapons.%^RESET%^"); break; case 1: tell_object(who, "%^GREEN%^Wielding two weapons is harder but still effective.%^RESET%^"); break; default: break; } return; } int ok_to_kill(object who, object targ) { int vic_level, pk_age_limit; string str, title; object hold, pkob; if(!objectp(targ) || !objectp(who)) return 0; if (targ->is_invincible()) return 0; if(!interactive(who) && !interactive(targ)) return 1; if(who == targ) return 1; //if(ETO->query_property("no kill") || ETO->query_property("no attack")) return 0; if (interactive(who) && interactive(targ)) { if (newbiep(who) && (!avatarp(targ))) { tell_object(who,"%^YELLOW%^You are currently under "+ "%^CYAN%^newbie%^YELLOW%^ protection and unable to "+ "be aggressive against "+targ->QCN+"%^YELLOW%^!%^RESET%^"); return 0; } if (newbiep(targ) && (!avatarp(who))) { tell_object(who,targ->QCN+"%^YELLOW%^ is currently "+ "under %^CYAN%^newbie%^YELLOW%^ protection and "+ "cannot be attacked by you.%^RESET%^"); return 0; } /*pk_age_limit = AVERAGE_AGE_D->return_age_needed((int)targ->query_character_level()); if((int)targ->query_age() < pk_age_limit) { tell_object(who, targ->QCN+"%^YELLOW%^ is currently "+ "time barred from being involved in pkill interactions.%^RESET%^"); return 0; } pk_age_limit = AVERAGE_AGE_D->return_age_needed((int)who->query_character_level()); if((int)who->query_age() < pk_age_limit) { tell_object(who, "%^YELLOW%^You are currently time "+ "barred from being involved in pkill interactions.%^RESET%^"); return 0; } */ if(targ->query("no pk")) { tell_object(who, targ->QCN+"%^YELLOW%^ is currently protected "+ "from pkill interactions.%^RESET%^"); return 0; } if(who->query("no pk")) { tell_object(who, "%^YELLOW%^You are currently protected from pkill "+ "interactions. See help flag in order to turn this off.%^RESET%^"); return 0; } if (in_edit(targ) || in_input(targ) && interactive(who)) { tell_object(who, targ->QCN+"%^RED%^ is currently in "+ "edit and cannot be attacked.%^RESET%^"); return 0; } pkob = new(PK_OB); pkob->move(who); pkob->pkill_start(who, targ, 1); pkob = new(PK_OB); pkob->move(targ); pkob->pkill_start(targ, who, 0); } return 1; } void add_attacker(object who, object ob) { object *attackers; string *atnames; if(!objectp(who) || !objectp(ob)) return; if(!objectp(environment(who)) || !objectp(environment(ob))) return; attackers = who->query_attackers(); atnames = who->query_atnames(); if (ob == who) return; if (member_array(ob, attackers) !=-1) return; attackers += ({ob}); if (userp(ob)) { if (member_array(ob->query_name(), atnames) != -1) return; if (environment(who)->query_property("arena")) return; atnames += ({ob->query_name()}); } if(sizeof(attackers)) who->set_attackers(attackers); if(sizeof(atnames)) who->set_atnames(atnames); who->check_death(); ob->check_death(); who->clean_up_attackers(); ob->clean_up_attackers(); return; } int light_armor_filter(object ob) { if(!objectp(ob)) { return 0; } if((string)ob->query_armor_prof() == "heavy") { return 1; } if((string)ob->query_armor_prof() == "medium") { return 1; } return 0; } void ok_to_wield(object who) { object *wielded,*worn; int Size; if(!objectp(who)) return; if (interactive(who)) { wielded = who->query_wielded(); worn = who->all_armour(); worn = distinct_array(worn); worn = filter_array(worn,"light_armor_filter",TO); if (sizeof(wielded) > 1) { Size = (int)who->query_size() - 1; if(Size == 0) Size = 1; if((wielded[0]->query_size() > Size) && (wielded[1]->query_size() > Size) && (wielded[0] != wielded[1])) { if(FEATS_D->usable_feat(who,"ambidexterity")) { if(sizeof(worn)) { tell_object(who,"You scramble to hang on to your "+wielded[0]->query_name()+" and " "your "+wielded[1]->query_name()+" but all that armor makes it impossible!"); tell_room(environment(who),""+who->QCN+" scrambles to hang on to "+who->QP+" "+wielded[0]->query_name()+" " "and "+who->QP+" "+wielded[1]->query_name()+" but fumbles and drops them!",who); if (!wielded[0]->query_property("enchantment") || (int)wielded[0]->query_property("enchantment") > 0) wielded[0]->move(environment(who)); if (!wielded[1]->query_property("enchantment") || (int)wielded[1]->query_property("enchantment") > 0) wielded[1]->move(environment(who)); } } else { tell_object(who,"In your attempt to wield two such weapons, you fumble and drop them."); tell_room(environment(who),who->QCN+" fumbles with "+who->QP+" "+wielded[0]->query_name()+" and " ""+who->QP+" "+wielded[1]->query_name()+" and then drops them.",who); if (!wielded[0]->query_property("enchantment") || (int)wielded[0]->query_property("enchantment") > 0) wielded[0]->move(environment(who)); if (!wielded[1]->query_property("enchantment") || (int)wielded[1]->query_property("enchantment") > 0) wielded[1]->move(environment(who)); } } } } } void clean_attacker_flags(object who) { if(!objectp(who)) return; who->remove_property("using whirl"); who->remove_property("using sweeping blow"); who->remove_property("using manyshot"); who->remove_property("using spinning kick"); who->remove_property("using smite"); who->remove_property("messids"); //Feat messages tracking } int sight_adjustment(object who) { int elight, ret; ret = 0; elight = effective_light(who); if(elight > 6 || elight < 1) { ret = random(5); } return ret; } void run_away(object who) { string *str; string dir, wimpydir; if(!objectp(who) || !objectp(environment(who))) return; str = (string*)environment(who)->query_exits(); if(!str || !sizeof(str)) { tell_object(who,"There is nowhere to run!!!"); return; } tell_object(who,"You run away."); if(objectp(environment(who)) && !who->query_invis()) { tell_room(environment(who), who->QCN+" runs away!", who); } wimpydir = who->query_wimpydir(); if(member_array(wimpydir, str) != -1) { dir = wimpydir; } else if(wimpydir == "retreat") { dir = environment(who)->query_direction(base_name(who->query_last_location())); } if(!dir || dir == "/d/shadowgate/void") { dir = str[random(sizeof(str))]; } who->set_property("true moving",dir); who->set_property("running away",1); who->force_me(dir); who->remove_property("running away"); who->remove_property("true moving"); who->set_wimped(1); return; } string query_paralyze_message(object who) { if (!objectp(who)) { return ""; } if (who->adminBlock()) { return ""; } if (who->query_deaths_door()) { return DEATHS_DOOR_MESSAGE; } if (who->query_unconscious()) { return who->query_unconscious_message(); } if (who->query_paralyzed()) { return who->query_combat_mapps("messages", "paralyzed"); } if (who->query_bound()) { return who->query_bound_message(); } if (who->query_tripped()) { return who->query_tripped_message(); } } //altered to allow best avoidance type to process //added ultra counter attack if both spring attack and masters parry process //Yves - 11/02/2018 int check_avoidance(object who, object victim, object *weapons) { object EWHO, rider; int athleticsWho, athleticsVictim, avoidance = 0, mod = 0, springAttack = 0, counterAttack = 0; string avoidanceType = ""; if(!objectp(who) || !objectp(victim)) return 0; if(!objectp(EWHO = environment(who))) return 0; if(!objectp(victim)) return 0; //shouldn't be parrying/scrambling, etc, if you are paralyzed if(victim->query_paralyzed()) return 0; //if they have the noMissChance property set, then don't miss via parry/scramble/ride by attack if(who->query_property("noMissChance")) return 0; athleticsWho = (int)who->query_character_level(); athleticsWho += (int)who->query_skill("athletics"); athleticsVictim = (int)victim->query_character_level(); athleticsVictim += (int)victim->query_skill("athletics"); //scramble if (victim->query_scrambling() && (victim->is_ok_armour("thief") || victim->query_property("shapeshifted")) ) { //can't flip around if you are laying on the ground if(!victim->query_tripped()){ if(victim->query_parrying()) mod = -roll_dice(1,10); //else mod = roll_dice(1,8); if((roll_dice(1, athleticsVictim)+mod) > roll_dice(1, athleticsWho)) { avoidance = 1; avoidanceType = "TYPE_SCRAMBLE"; if(FEATS_D->usable_feat(victim,"spring attack") && !random(5)) { springAttack = 1; } } } } if((sizeof(weapons) && !weapons[0]->is_lrweapon()) || !FEATS_D->usable_feat(who, "point blank shot")) { //ride-by attack if(victim->query_in_vehicle() && FEATS_D->usable_feat(victim,"ride-by attack") && !random(5)) { if(roll_dice(1, athleticsVictim) > roll_dice(1, athleticsWho)) { avoidance = 1; avoidanceType = "TYPE_RIDDEN"; } } //shot on the run if(!FEATS_D->usable_feat(victim,"ride-by attack") && victim->query_property("shotontherun") && !random(5)) { if(roll_dice(1, athleticsVictim) > roll_dice(1, athleticsWho)) { avoidance = 1; avoidanceType = "TYPE_SHOT"; } } //mounted combat if(victim->is_animal() && !random(5)) { rider = (object)victim->query_current_rider(); if(objectp(rider)) { if(FEATS_D->usable_feat(rider,"mounted combat") && (roll_dice(1, athleticsVictim) > roll_dice(1, athleticsWho))) { avoidance = 1; avoidanceType = "TYPE_MOUNT"; } } } } //parry if(sizeof(weapons) || FEATS_D->usable_feat(victim, "unarmed parry")) { if ((victim->query_parrying()) && (!victim->query_property("shapeshifted"))) { if(victim->query_property("shield_of_whirling_steel")) { mod += victim->query_property("shield_of_whirling_steel"); } if(victim->query_scrambling() && !victim->query_property("shield_of_whirling_steel")) { mod = -roll_dice(1,10); } //else mod = roll_dice(1,8); if((roll_dice(1, athleticsVictim)+mod) > roll_dice(1, athleticsWho)) { avoidance = 1; avoidanceType = "TYPE_PARRY"; if(FEATS_D->usable_feat(victim,"masters parry") && victim->is_wielding("dual wielding")) { if(random(4)) counterAttack = 1; // should happen frequently as it's a level 47 ability } } } } //ensure the correct avoidance message fires if(counterAttack && springAttack) avoidanceType = "TYPE_COMBINED"; else if(counterAttack) avoidanceType = "TYPE_PARRY"; else if(springAttack) avoidanceType = "TYPE_SCRAMBLE"; switch(avoidanceType) { case "TYPE_COMBINED": tell_object(who,"Your opponent anticipates your attack and maneuvers" " into perfect position!"); tell_object(victim,"You anticipate your opponent's attack and maneuver" " into perfect position!"); tell_room(EWHO,"You see "+who->QCN+"'s attack expertly avoided by "+victim->QCN+"!",({who,victim}) ); combined_attack(who, victim); break; case "TYPE_SCRAMBLE": who->send_dodge(victim); if(springAttack) victim->spring_attack(victim); break; case "TYPE_PARRY": tell_object(who,"Your attack is parried by your attacker!"); tell_object(victim,"You deftly parry your opponent's blow!"); tell_room(EWHO,"You see "+who->QCN+"'s attack parried by "+victim->QCN+".",({who,victim}) ); if(counterAttack) counter_attack(victim); break; case "TYPE_RIDDEN": tell_object(who,"%^RESET%^%^BOLD%^"+victim->QCN+" has already ridden past you and " "is out of reach!%^RESET%^"); tell_object(victim,"%^RESET%^%^BOLD%^You deftly steer your steed and "+who->QCN+ "'s blow falls short of hitting you!%^RESET%^"); tell_room(EWHO,"%^RESET%^%^BOLD%^"+victim->QCN+" deftly steers "+victim->QP+ " steed and "+who->QCN+"'s blow falls short of hitting "+victim->QO+ "!%^RESET%^",({who,victim})); break; case "TYPE_SHOT": tell_object(who,"%^RESET%^%^BOLD%^"+victim->QCN+" uses "+victim->QP+" own attack as " "cover, and manages to move out of your reach!%^RESET%^"); tell_object(victim,"%^RESET%^%^BOLD%^You use your last shot as cover to get clear " "of "+who->QCN+"'s attack!%^RESET%^"); tell_room(EWHO,"%^RESET%^%^BOLD%^"+victim->QCN+" uses "+victim->QP+" last shot as " "cover to get clear of "+who->QCN+"'s attack!%^RESET%^",({who,victim})); break; case "TYPE_MOUNT": tell_object(rider,"%^RESET%^%^BOLD%^You direct your steed out of harm's way!%^RESET%^"); tell_room(EWHO,"%^RESET%^%^BOLD%^"+rider->QCN+" directs "+rider->QP+ "steed out of harm's way!%^RESET%^",rider); break; default: break; } return avoidance; } void combined_attack(object who, object victim) { object *attackers, EWHO; if(!objectp(who) || !objectp(victim)) return; attackers = victim->query_attackers(); attackers -= ({ 0 }); if(!sizeof(attackers)) return; EWHO = environment(who); //special effect on top of an extra attack since they springed AND countered switch(random(50)) { case 0..29: //damage tell_object(who, "%^BOLD%^%^RED%^"+victim->QCN+" takes advantage of "+victim->QP+ " position and delivers a devastating blow while your guard is down!%^RESET%^"); tell_object(victim, "%^BOLD%^%^RED%^You take advantage of your position " "and deliver a devastating blow to "+who->QCN+" while "+who->QP+" guard is down!%^RESET%^"); tell_room(EWHO, "%^BOLD%^%^RED%^"+victim->QCN+" takes advantage of "+victim->QP+ " position and delivers a devastating blow to "+who->QCN+" while "+who->QP+ " guard is down!%^RESET%^", ({who,victim})); who->do_damage(who->return_limb(),roll_dice(5,12)+25); break; case 30..39: //stun tell_object(victim, "%^BOLD%^%^WHITE%^You take advantage of your position " "and connect with a strike that leaves "+who->QCN+" staggered!%^RESET%^"); tell_object(who, "%^BOLD%^%^WHITE%^"+victim->QCN+" takes advantage of "+victim->QP+ " position and connects with a strike that leaves you staggered!%^RESET%^"); tell_room(EWHO, "%^BOLD%^%^WHITE%^"+victim->QCN+" takes advantage of "+victim->QP+ " position and connects with a strike that leaves "+who->QCN+ " staggered!%^RESET%^", ({who,victim})); who->set_paralyzed(roll_dice(1,10) + 10, "%^BOLD%^%^WHITE%^You are staggered " "by the unexpected blow!%^RESET%^"); break; case 40..49: //trip tell_object(victim, "%^BOLD%^%^BLUE%^You take advantage of your position " "and sweep through "+who->QCN+"'s lower limbs causing "+who->QO+ " to fall prone!%^RESET%^"); tell_object(who, "%^BOLD%^%^BLUE%^"+victim->QCN+" takes advantage of "+victim->QP+ " position and sweeps through your lower limbs causing you to fall prone!%^RESET%^"); tell_room(EWHO, "%^BOLD%^%^BLUE%^"+victim->QCN+" takes advantage of "+victim->QP+ " position and sweeps through "+who->QCN+"'s lower limbs causing "+who->QO+ " to fall prone!%^RESET%^", ({who,victim})); who->set_tripped(random(2)+1, "%^BOLD%^%^BLUE%^You are scrambling to your feet!%^RESET%^"); break; default: break; } victim->execute_attack(); return; } //FUNCTIONS BELOW STILL NEED CONVERTING void internal_execute_attack(object who) { int toAttack, toattack, lastHand, critical_hit; int i, roll, temp1, temp2, touch_attack = 0; object *weapons, current, victim, *protectors, *attackers, EWHO; string target_thing; if(!objectp(who)) return; who->set_for_attack(); //sets attacking to 0 - this function will not get called until it is 0 EWHO = environment(who); if(!objectp(EWHO)) return; if(objectp(who)) { who->reset_critical(); } attackers = who->query_attackers(); if (!sizeof(attackers)) { who->prepare_attack(); if(who->query_combat_mapps("static vars", "attack count") && !who->query_combat_mapps("static vars", "attack loop")) { who->execute_attack(); } return; } if (who->query_property("flee")) { who->prepare_attack(); if(who->query_combat_mapps("static vars", "attack count") && !who->query_combat_mapps("static vars", "attack loop")) { who->execute_attack(); } return; } toAttack = random(sizeof(attackers)); while (!objectp(attackers[toAttack]) || !present(attackers[toAttack],EWHO)) { attackers -= ({attackers[toAttack]}); who->set_attackers(attackers); if (!sizeof(attackers)) { who->prepare_attack(); if(who->query_combat_mapps("static vars", "attack count") && !who->query_combat_mapps("static vars", "attack loop")) { who->execute_attack(); } return; } toAttack = random(sizeof(attackers)); } who->adjust_combat_mapps("vars", "toAttack", toAttack); toattack = 4; who->adjust_combat_mapps("static vars", "toattack", toattack); victim = attackers[toAttack]; protectors = victim->query_active_protectors(victim); if(sizeof(protectors)) { victim = protectors[random(sizeof(protectors))]; } if(!living(victim) && !victim->query("not living")) { who->prepare_attack(); if(who->query_combat_mapps("static vars", "attack count") && !who->query_combat_mapps("static vars", "attack loop")) { who->execute_attack(); } return; } if(FEATS_D->usable_feat(who, "perfect self")) { if(!(int)who->has_ki()) { who->regenerate_ki(4); } } if (member_array(who,(object *)victim->query_attackers()) == -1) { victim->add_attacker(who); EWHO->add_combatant(victim); who->clean_up_attackers(); } if ((!who->do_casting(victim) && !who->query_property("temp_perfect_caster")) && !who->do_functions()) { who->ok_to_wield(); weapons = distinct_array(who->query_wielded()); lastHand = who->query_combat_mapps("static vars", "lastHand"); if(pointerp(weapons) && lastHand < sizeof(weapons)) current = weapons[lastHand]; else if(pointerp(weapons) && lastHand > (sizeof(weapons)-1)) { who->adjust_combat_mapps("static vars", "lastHand", 0); lastHand = 0; if(lastHand < sizeof(weapons)) current = weapons[lastHand]; else current = who; } else current = who; if(current->is_lrweapon() && !FEATS_D->usable_feat(who, "point blank shot")) { tell_object(who,"Your bow is useless in hand to hand combat.\n"); who->prepare_attack(); if(who->query_combat_mapps("static vars", "attack count") && !who->query_combat_mapps("static vars", "attack loop")) { who->execute_attack(); } return; } roll = random(20)+1; target_thing = (string)victim->return_target_limb(); roll = BONUS_D->process_hit(who, victim, i, current, 0, touch_attack); //crit stuff if(sizeof(weapons) && !who->query_property("shapeshifted")) { temp1 = (int)current->query_critical_threat_range(); if(FEATS_D->usable_feat(who, "lethal strikes") && !who->query_property("shapeshifted")) { if(sizeof(weapons) >= 2) { if(weapons[0] != weapons[1]) temp1 += 1; if((int)weapons[0]->query_size() == 1 && (int)weapons[1]->query_size() == 1) temp1 += 1; } else if(sizeof(weapons) == 1) { temp1 += 1; if((int)weapons[0]->query_size() == 1) temp1 += 1; } } } else { temp1 = 2; } if(roll > (20 - temp1)) // if threat range of weapon is 2, then we have a crit threat on a roll of 19 or 20 { if(!victim->query_property("no crit") && ( !interactive(victim) || ((int)victim->query_level() > 5) )) { temp2 = BONUS_D->process_hit(who, victim, i, current); if(temp2) { who->adjust_combat_mapps("static vars", "critical hit", 1); who->adjust_combat_mapps("static vars", "critical message", 1); critical_hit = 1; } } } // end crit stuff if (roll) { if(!victim->query_unconscious() && !victim->query_ghost() && !victim->query_bound()) { if(!extra_hit_calcs(who, victim, current, target_thing) || check_avoidance(who, victim, weapons)) { if(!objectp(who)) return; who->adjust_combat_mapps("static vars", "lastHand", 1, 1); who->adjust_combat_mapps("static vars", "attacking", 0); if(who->query_combat_mapps("static vars", "attack count") && !who->query_combat_mapps("static vars", "attack loop")) { who->execute_attack(); } return; } else calculate_damage(who, victim, current, target_thing, critical_hit); } else calculate_damage(who, victim, current, target_thing, critical_hit); } if(roll == 1) { //if(find_player("saide") && userp(who)) tell_object(find_player("saide"), identify(who) + " rolled a 1 against "+identify(victim)); if(objectp(current)) { if((int)current->query("PoisonDoses")) { if(who->reflex_save(15)) { POISON_D->is_object_poisoned(current, who, "hit", 1); } } } } if(!roll) { //if(find_player("saide") && userp(who)) tell_object(find_player("saide"), identify(who) + " missed "+identify(victim)); if (!current || who->query_property("shapeshifted")) who->miss(who->query_casting(), victim, 0, target_thing); else who->miss(0, victim, (string)current->query_type(), target_thing); } } if(!objectp(who)) { return; } if(!objectp(victim)) { who->adjust_combat_mapps("static vars", "lastHand", 1, 1); who->adjust_combat_mapps("static vars", "attacking", 0); if(who->query_combat_mapps("static vars", "attack count") && !who->query_combat_mapps("static vars", "attack loop")) { who->execute_attack(); } return; } if(FEATS_D->usable_feat(who,"combat reflexes") && who->is_ok_armour("thief") && !who->query_casting() && (int)who->query_property("stabs_available") > 0 && !who->query_paralyzed() && !who->query_tripped()) { who->set_property("stabs_available",-1); if(victim->query_property("stab_resilience")) { victim->set_property("stab_resilience",-1); tell_object(who,"You successfully position yourself to strike where "+victim->QCN+" is vulnerable, but "+victim->QS+" seems unaffected."); tell_object(victim,"You suddenly notice that "+who->QCN+" has moved to strike where you are vulnerable, but you are resilient against the worst of the attack."); tell_room(EWHO,""+who->QCN+" has positioned "+who->QO+"self to strike where "+victim->QCN+" is vulnerable, but "+victim->QS+" seems unaffected.",({victim,who})); } else { tell_object(who,"You successfully position yourself to strike where "+victim->QCN+" is vulnerable."); tell_object(victim,"You suddenly notice that "+who->QCN+" has moved to strike where you are vulnerable."); tell_room(EWHO,""+who->QCN+" has positioned "+who->QO+"self to strike where "+victim->QCN+" is vulnerable.",({victim,who})); "/cmds/mortal/_stab"->scramble_stab(who,victim); } } if (((int)who->query_scrambling() == 1)&& who->is_ok_armour("thief") && who->is_class("thief")) { if(D_BUG_D->scramble_change()) who->set_scrambling(2); } who->adjust_combat_mapps("static vars", "lastHand", 1, 1); who->adjust_combat_mapps("static vars", "attacking", 0); if(who->query_combat_mapps("static vars", "attack count") && !who->query_combat_mapps("static vars", "attack loop")) { who->execute_attack(); } return; } // Does the functions returns 1 if func is executed and 0 if not int do_functions(object who) { object random_targ; if(!objectp(who)) return 0; if(who->query_combat_mapps("vars", "funcCast")) return 0; if(!who->clean_up_attackers()) return 0; who->setFuncCast(1); if (who->query_func_chance() > (random(100)+1)) { random_targ = who->return_player_target(50); if ((!objectp(random_targ))) return 0; who->setFuncing(1); call_other(who, who->get_random_func(), random_targ); return 1; } return 0; } mixed return_player_target(object who, int flag) { int x; object *myTargets = ({}), attackers; if(!objectp(who)) return 0; if(!who->clean_up_attackers()) { return 0; } attackers = who->query_attackers(); if(!intp(flag)) flag = 50; if(roll_dice(1,100) > flag) return attackers[random(sizeof(attackers))]; for(x = 0;x < sizeof(attackers);x++) { if(!interactive(attackers[x])) continue; myTargets += ({attackers[x]}); continue; } if(sizeof(myTargets)) return myTargets[random(sizeof(myTargets))]; else return attackers[random(sizeof(attackers))]; } int do_casting(object who, object targ) { string this_spell, spell_type, spell_file; object tempspell; if(!objectp(who) || !objectp(environment(who))) return 0; if(!objectp(targ)) targ = who->return_player_target(50); if(!objectp(targ) || !present(targ, environment(who))) return 0; if (who->query_combat_mapps("vars", "castFunc")) return 0; who->setCastFunc(1); if ((int)who->query_spell_chance() > (random(100)+1)) { this_spell = (string)who->get_random_spell(); if (this_spell) { spell_file="/cmds/spells/"+this_spell[0..0]+"/_"+replace_string(this_spell," ","_")+".c"; if (file_exists(spell_file)) { tempspell=new(spell_file); if(!objectp(tempspell)) { who->setCastFunc(0); return 0; } if ((int)tempspell->query_target_required() == 1) { tempspell->use_spell(who,targ,who->query_level()); } else { tempspell->use_spell(who,0,who->query_level()); } } } return 1; } return 0; } void spring_attack(object ob) { object *attackers; if(!objectp(ob)) { return; } attackers = ob->query_attackers(); attackers -= ({ 0 }); if(!sizeof(attackers)) { return; } tell_object(ob,"%^BOLD%^%^CYAN%^You use the momentum of your dodge to " "try and land another attack!"); tell_room(environment(ob),"%^BOLD%^%^CYAN%^"+ob->QCN+" uses the momentum " "of "+ob->QP+" dodge to try and land another attack!",ob); ob->execute_attack(); return; } void counter_attack(object ob) { object *attackers; if(!objectp(ob)) { return; } attackers = ob->query_attackers(); attackers -= ({ 0 }); if(!sizeof(attackers)) { return; } tell_object(ob,"%^RESET%^%^BOLD%^%^GREEN%^You take advantage of the opening and " "counter attack!%^RESET%^"); tell_room(environment(ob),"%^RESET%^%^BOLD%^%^GREEN%^"+ob->QCN+" takes advantage " "of the opening and counter attacks!%^RESET%^",ob); ob->execute_attack(); return; } int isPkill(object who) { int i,j; object killedBy, *attackers, EWHO; if(!objectp(who)) return 0; if(!objectp(EWHO = environment(who))) return 0; if(!userp(who) && !who->is_townsman()) { return 0; } attackers = who->query_attackers(); if (!sizeof(attackers)) { return 0; } if(objectp(attackers[0])) { if (attackers[0]->query_property("spell") && objectp(attackers[0]->query_property("spell"))) { killedBy = (attackers[0]->query_property("spell"))->query_caster(); } if(!objectp(killedBy)) { killedBy = attackers[0]; } } if(EWHO->query_property("arena") && (who->query_property("safe arena") && killedBy->query_property("safe arena"))) { return 0; } j = sizeof(attackers); for (i=0;i<j;i++) { if(objectp(attackers[i])) { if (userp(attackers[i]) || isPlayerMonster(attackers[i])) { return attackers[i]; } if (attackers[i]->is_townsman()) { return attackers[i]; } if (attackers[i]->query_property("knock unconscious")) { return attackers[i]; } if (attackers[i]->is_spell() && objectp(attackers[i]->query_caster()) && interactive(attackers[i]->query_caster())) { return attackers[i]->query_caster(); } } } return 0; } int isPlayerMonster(object ob) { object spell; if(!objectp(ob)) { return 0; } if(spell = ob->query_property("spell")) { if (!objectp(spell)) { return 0; } if (objectp(spell->query_caster())) { return userp(spell->query_caster()); } } return 0; } void continue_attack(object who) { object killedBy; int attack, toattack; object EWHO, *attackers; if(!objectp(who)) return; if(!objectp(EWHO = environment(who)) || who->query_ghost()) return; if(who->is_player() && !interactive(who) && !who->query_property("bounty hunter")) { return; } attackers = who->query_attackers(); who->check_death(); if(who->query_dead()) { who->adjust_combat_mapps("static vars", "dead", 0); who->die((attackers && killedBy ? killedBy : 0)); if(objectp(who)) who->cease_all_attacks(); return; } //if((0) && !any_attack) casting = 0; // ??? if(!who->query_combat_mapps("vars", "any attack") && !who->query_combat_mapps("static vars") && !sizeof(attackers) && (userp(who) || !sizeof(who->query_combat_mapps("arrays", "atnames")))) return; if(!who->query_wimped() || userp(who)) { if(!who->clean_up_attackers()) return; } if(((int)who->query_hp()*100)/(int)who->query_max_hp() < who->query_wimpy()) { if(time() > (int)who->query_property("running_away_time")) { who->remove_property("running_away_time"); who->set_property("running_away_time",time()+2); who->run_away(); return; } } who->set_wimped(0); attack = who->query_combat_mapps("static vars", "attack"); toattack = who->query_combat_mapps("static vars", "toattack"); attack++; if (attack > toattack-1) { attack = 0; if (!who->query_paralyzed()) { if (who->do_i_win()) { EWHO->add_combatant(who); } } else { if(objectp(who)) { message("my_combat", who->query_paralyze_message(),who); } } } who->adjust_combat_mapps("static vars", "attack", attack); return; } int doPkill(object who) { int i,j; object *attackers; if(!objectp(who)) { return 0; } if (who->query_property("to die")) { return 0; } if (who->query_hp() < (-20* who->query_max_hp())) { return 0; } attackers = who->query_attackers(); j = sizeof(attackers); for (i=0;i<j;i++) { if(!objectp(attackers[i])) { continue; } attackers[i]->remove_attacker(who); } who->cease_all_attacks(); who->set_hidden(0); who->set_magic_hidden(0); tell_object(who,"%^BOLD%^%^RED%^You have fallen unconscious due to egregious wounds."); if(objectp(environment(who))) tell_room(environment(who),"%^BOLD%^%^RED%^"+who->QCN+" falls unconscious due to horrible wounds.",who); return 1; } varargs int check_death(object who, object pot) { object *death, magi, *newattackers, killedBy; int xxx, exp, i,minions, falling; object spellthing, *attackers; if(!objectp(who)) return 0; if(who->query_combat_mapps("static vars", "dead")) return 1; falling = who->query_property("falling"); // These lines added by if (userp(who) && who->query_hp() <1 && ( falling < time() - (__COMBAT_SPEED__*3)+4 )) // Lujke to stop people { // dying while // waiting for kits to hit who->set_property("falling", time()); // return 0; // } // if (who->query_hp() < 1 && !who->query_ghost() ) { who->remove_property("falling"); // This also added by Lujke as above if(wizardp(who) && !who->query_killable()) { who->set_hp((int)who->query_max_hp()); tell_object(who,"You are immortal and cannot die."); return 0; } attackers = who->query_attackers(); if(objectp(pot)) { attackers += ({pot}); } if (sizeof(attackers)) { if (!who->is_player() && !who->is_townsman()) { newattackers = attackers; for (i = 0;i < sizeof(attackers);i++) { if(!objectp(attackers[i])) { newattackers -= ({attackers[i]}); continue; } if(attackers[i]->query_property("minion")) { newattackers -= ({attackers[i]}); minions = 1; continue; } if(attackers[i]->query_property("spell") && !attackers[i]->query_property("keep exp")) { newattackers -= ({attackers[i]}); spellthing = attackers[i]->query_property("spell"); if(!objectp(spellthing)) continue; magi = spellthing->query_caster(); if (member_array(magi, newattackers) == -1 && objectp(magi)) { newattackers += ({magi}); } continue; } else if(attackers[i]->is_spell()) { newattackers -= ({attackers[i]}); spellthing = attackers[i]; magi = spellthing->query_caster(); if (member_array(magi, newattackers) == -1 && objectp(magi)) { newattackers += ({magi}); } } continue; } attackers = newattackers; who->adjust_combat_mapps("arrays", "attackers", attackers); if(sizeof(attackers) && objectp(attackers[0])) { attackers[0]->add_kill((string)who->query_name()); if(avatarp(attackers[0]) && attackers[0]->query_disguised()) { if(userp(attackers[0])) who->add_death((string)attackers[0]->getParsableName()); else who->add_death((string)attackers[0]->query_vis_name()); } else { if(userp(attackers[0])) who->add_death((string)attackers[0]->getParsableName()); else who->add_death((string)attackers[0]->query_name()); } } for(i = 0;i < sizeof(attackers);i++) { if(!objectp(attackers[i])) { continue; } if(!objectp(environment(who)) || environment(who)->query_property("arena")) continue; exp = who->query_exp(); attackers[i]->set_property("GainedExpFrom", who); attackers[i]->doExp(attackers[i],exp,sizeof(attackers) + minions); attackers[i]->remove_property("GainedExpFrom"); continue; } if(!sizeof(attackers)) return 1; killedBy = attackers[0]; who->set("killedBy", killedBy); who->adjust_combat_mapps("static vars", "dead", 1); return 1; } if (killedBy = who->isPkill()) { who->set("killedBy", killedBy); if(who->doPkill()) { return 1; } } newattackers = attackers; for (i = 0;i < sizeof(attackers);i++) { if(!objectp(attackers[i])) { newattackers -= ({attackers[i]}); continue; } if(attackers[i]->query_property("minion")) { newattackers -= ({attackers[i]}); minions = 1; continue; } if (attackers[i]->query_property("spell") && !attackers[i]->query_property("keep exp")) { newattackers -= ({ attackers[i]}); spellthing = attackers[i]->query_property("spell"); if(!objectp(spellthing)) continue; magi= spellthing->query_caster(); if(member_array(magi, newattackers) == -1) { newattackers += ({magi}); } } continue; } attackers = newattackers; who->adjust_combat_mapps("arrays", "attackers", attackers); if(sizeof(attackers) && objectp(attackers[0])) { attackers[0]->add_kill((string)who->query_name()); if (avatarp(attackers[0]) && attackers[0]->query_disguised()) { if(userp(attackers[0])) who->add_death((string)attackers[0]->getParsableName()); else who->add_death((string)attackers[0]->query_vis_name()); } else { if(attackers[0]->is_spell()) { if(userp(attackers[0]->query_caster())) who->add_death((string)attackers[0]->query_caster()->getParsableName()); else who->add_death( (attackers[0]->query_caster())->QCN ); } if(userp(attackers[0])) who->add_death((string)attackers[0]->getParsableName()); else who->add_death((string)attackers[0]->query_name()); } xxx = sizeof(death = all_inventory(attackers[0])); while (xxx--) { death[xxx]->notify_kill(TO); } if(!objectp(killedBy) && attackers[0]->query_property("spell") && objectp(attackers[0]->query_property("spell"))) { killedBy = attackers[0]->query_property("spell")->query_caster(); } if(!objectp(killedBy)) { killedBy = attackers[0]; who->set("killedBy", killedBy); } } if (who->is_townsman()) { for (i = 0;i < sizeof(attackers);i++) { if (!objectp(attackers[i])) continue; if(objectp(environment(who)) && environment(who)->query_property("arena")) continue; exp = who->query_exp(); attackers[i]->set_property("GainedExpFrom", who); attackers[i]->doExp(attackers[i],exp,sizeof(attackers) + minions); attackers[i]->set_property("GainedExpFrom", who); continue; } } if (!environment(who)->query_property("arena") || (!who->query_property("safe arena") || !killedBy->query_property("safe arena"))) { if(objectp(killedBy)) { log_file("kills", who->query_name()+" ("+(int)who->query_level()+") was killed by "+killedBy->query_name()+" ("+(int)killedBy->query_level()+")\n"); log_file("kills"," "+file_name(killedBy)+" (uid:"+getuid(killedBy)+") \n (creator = "+killedBy->query_creator()+") ["+file_name(environment(who))+"]\n"); } else { log_file("kills", who->query_name()+" ("+(int)who->query_level()+") was killed by "+identify(killedBy)+" ("+identify(killedBy)+")\n"); if(objectp(environment(who))) { log_file("kills"," "+file_name(killedBy)+" (uid:"+getuid(killedBy)+") \n (creator = "+identify(killedBy)+") ["+file_name(environment(who))+"]\n"); } else { log_file("kills"," "+file_name(killedBy)+" (uid:"+getuid(killedBy)+") \n (creator = "+identify(killedBy)+") ["+identify(who)+"]\n"); } } } if(who->isPkill() || killedBy->query_property("bounty hunter")) { if (!(environment(who)->query_property("arena")) || (!who->query_property("safe arena") || !killedBy->query_property("safe arena"))) { if (!wizardp(who) && !wizardp(killedBy)) { log_file("pkills",who->query_name()+" ("+(int)who->query_alignment()+") was killed by "+killedBy->query_name()+" ("+(int)killedBy->query_alignment()+")\n"); KILLING_D->do_bad_pkill(killedBy,who); } } } if (who->isPkill()) { log_file("killers"," "+capitalize(who->query_name())+" was killed by "+capitalize(killedBy->query_name())+"\n"); who->set("no pk", 1); who->set("just_been_pkilled",1); who->set_pk_death_flag(); who->perma_death(); who->remove_property("to die"); if (!random(100)) { log_file("permaDeaths"," "+capitalize(who->query_name())+" was perma killed by "+capitalize(killedBy->query_name())+"\n"); tell_object(who,"%^BOLD%^%^FLASH%^This really would have been be a permadeath had the code been in."); } } who->adjust_combat_mapps("static vars", "dead", 1); return 1; } } return 0; } void doExp(object who, int how, int split) { int max,per; if(!objectp(who)) { return; } //how = how/split; // already getting split in the party daemon, so was getting split again if (who->query_max_level()) { if(max = (int)who->query_max_level()) { if(max < (int)who->query_lowest_level()) { // 5% if they are 5 levels higher than the max level if((int)who->query_lowest_level() - max > 4) { per = 5; } else { per = (int)who->query_lowest_level() - max; switch(per) { case 4: per = 20; break; case 3: per = 40; break; case 2: per = 60; break; case 1: per = 80; break; default: per = 5; break; } } if(per == 0) { how = 0; } else { how = to_int(how * (per * 0.01)); } } } } who->add_exp(how); return; } int kill_ob(object who, object victim, int which) { object *borg_people, *inven, EWHO, *attackers; int i, initiative, k, myinit; string *pkill; if(!objectp(who)) { return 0; } if(!objectp(EWHO = environment(who))) return 0; if(!objectp(victim)) { return 0; } if (!objectp(environment(victim))) { return 0; } if ((base_name(EWHO)=="/d/shadowgate/void") || (base_name(environment(victim)) =="/d/shadowgate/void")) { return 0; } if (victim == who) return 0; if (!who->ok_to_kill(victim)) { return 0; } if (!sizeof(who->query_attackers())) { who->init_attack(); } pkill = ({}); borg_people = (object *)victim->query_attackers(); if (!borg_people) borg_people = ({}); if(!(environment(victim)->query_property("arena")) && (!who->query_property("safe arena") || !victim->query_property("safe arena"))) { if(member_array(who, borg_people) == -1) { if (interactive(who) && interactive(victim) || (victim->is_townsman()) || who->is_townsman()) { if (!wizardp(who) && !wizardp(victim)) { if (PO->is_spell()) { if(objectp(PO->query_caster())) { if(member_array(PO->query_caster(), borg_people) == -1) { log_file("killers"," ##"+capitalize((PO->query_caster())->query_name())+" " "attacked "+capitalize(who->query_name())+" at "+ctime(time())+".\n"); if (!avatarp(PO->query_caster())) KILLING_D->check_actions(PO->query_caster(),who); } } else { log_file("killers"," ##"+capitalize(who->query_name())+" attacked " ""+capitalize(victim->query_name())+".\n"); if (!avatarp(who)) KILLING_D->check_actions(who, victim); } } else { log_file("killers"," ##"+capitalize(who->query_name())+" attacked " ""+capitalize(victim->query_name())+".\n"); if (!avatarp(who)) KILLING_D->check_actions(who,victim); } } } } } if(objectp(victim)) { victim->check_death(); } if(interactive(who) && !userp(victim)) { inven = all_inventory(EWHO); inven = filter_array(inven,"classic_swarm",FILTERS_D); for(i=0;i<sizeof(inven);i++) { if(!objectp(inven[i])) { continue; } inven[i]->add_attacker(who); EWHO->add_combatant(inven[i]); continue; } } /* changed from 0 to 1 to faciliate PK patch */ if(who->query_attacked()) { return 1; } attackers = who->query_attackers(); i = member_array(victim, attackers); if ((i == -1) && (!which)) { // roll surprise and stuff // assume we won myinit = who->query_initiative(); if((string)who->query_race() == "human" && (string)who->query("subrace") == "tsarven") myinit -= 1; if (myinit < (int)victim->query_initiative()) { who->set_toattack(2); victim->set_toattack(4); } else { who->set_attack(4); victim->set_toattack(2); } victim->add_attacker(who); EWHO->add_combatant(victim); } if (i > -1) { //tell_object(who, "You are already attacking "+victim->QCN+"!\n"); // don't really need this, it looks funny when some feats use it. return 1; } who->add_attacker(victim); EWHO->add_combatant(who); who->adjust_combat_mapps("vars", "any attack", 1); return 1; } int valid_object(object ob) { if(!objectp(ob)) return 0; return 1; } int clean_up_attackers(object who) { object *hunters_tmp=({}), *attackers_tmp=({}), *full_tmp, ob, *uncon_att=({}), EWHO; int i, tmp; string *pkillsatt, *pkillsvic, *atnames; if (!objectp(who)) return 0; if (!objectp(EWHO = environment(who))) return 0; full_tmp = who->query_combat_mapps("arrays", "hunters") + who->query_combat_mapps("arrays", "attackers"); atnames = who->query_combat_mapps("arrays", "atnames"); if (interactive(who)) { pkillsatt = who->query_pkilled(); if (!pointerp(pkillsatt)) pkillsatt = ({}); } for (i=0, tmp = sizeof(full_tmp); i<tmp; i++) { if (full_tmp[i] == who || !objectp(full_tmp[i])) continue; if (member_array(full_tmp[i], (attackers_tmp+hunters_tmp)) != -1) continue; if (!objectp(environment(full_tmp[i]))) continue; if (environment(full_tmp[i]) != EWHO) { if (interactive(who) && interactive(full_tmp[i])) continue; hunters_tmp += ({ full_tmp[i]}); continue; } if (full_tmp[i]->query_ghost()) { atnames-=({full_tmp[i]->query_name()}); continue; } if (interactive(full_tmp[i]) && interactive(who)) { pkillsvic = full_tmp[i]->query_pkilled(); if (!pointerp(pkillsvic)) pkillsvic = ({}); if (member_array(full_tmp[i]->query_name(),pkillsatt) != -1) pkillsatt = pkillsatt + ({full_tmp[i]->query_name()}); if (member_array(who->query_name(),pkillsvic) != -1) pkillsvic = pkillsvic + ({who->query_name()}); } if (!full_tmp[i]->query_bound() && !full_tmp[i]->query_unconscious()) { attackers_tmp += who->doProtection(full_tmp[i]); } else { uncon_att += ({full_tmp[i]}); } } if (!userp(who) && !EWHO->query_property("arena")) { for (i=0, tmp = sizeof(atnames); i<tmp; i++) { if (ob=present(atnames[i],EWHO)) attackers_tmp += ({ob}); continue; } } if (sizeof(attackers_tmp) == 0) { for (i=0, tmp = sizeof(uncon_att); i<tmp; i++) { attackers_tmp += who->doProtection(uncon_att[i]); } } attackers_tmp = distinct_array(attackers_tmp); attackers_tmp -= ({ 0 }); attackers_tmp = filter_array(attackers_tmp, "valid_object", TO); hunters_tmp -= ({ 0 }); for(i = 0;i < sizeof(attackers_tmp);i++) { } who->adjust_combat_mapps("arrays", "attackers", attackers_tmp); who->adjust_combat_mapps("arrays", "hunters", hunters_tmp); who->adjust_combat_mapps("vars", "any attack", sizeof(attackers_tmp)); who->adjust_combat_mapps("static vars", "hunting", sizeof(hunters_tmp)); return who->query_combat_mapps("vars", "any attack"); }
38.788712
466
0.546737
[ "object", "shape" ]